1 /******************************************************************************
   2 ** This file is an amalgamation of many separate C source files from SQLite
   3 ** version 3.7.16.2.  By combining all the individual C code files into this
   4 ** single large file, the entire code can be compiled as a single translation
   5 ** unit.  This allows many compilers to do optimizations that would not be
   6 ** possible if the files were compiled separately.  Performance improvements
   7 ** of 5% or more are commonly seen when SQLite is compiled as a single
   8 ** translation unit.
   9 **
  10 ** This file is all you need to compile SQLite.  To use SQLite in other
  11 ** programs, you need this file and the "sqlite3.h" header file that defines
  12 ** the programming interface to the SQLite library.  (If you do not have
  13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
  15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16 ** if you want a wrapper to interface SQLite with your choice of programming
  17 ** language. The code for the "sqlite3" command-line shell is also in a
  18 ** separate file. This file contains only code for the core SQLite library.
  19 */
  20 #define SQLITE_CORE 1
  21 #define SQLITE_AMALGAMATION 1
  22 #ifndef SQLITE_PRIVATE
  23 # define SQLITE_PRIVATE static
  24 #endif
  25 #ifndef SQLITE_API
  26 # define SQLITE_API
  27 #endif
  28 /************** Begin file sqliteInt.h ***************************************/
  29 /*
  30 ** 2001 September 15
  31 **
  32 ** The author disclaims copyright to this source code.  In place of
  33 ** a legal notice, here is a blessing:
  34 **
  35 **    May you do good and not evil.
  36 **    May you find forgiveness for yourself and forgive others.
  37 **    May you share freely, never taking more than you give.
  38 **
  39 *************************************************************************
  40 ** Internal interface definitions for SQLite.
  41 **
  42 */
  43 #ifndef _SQLITEINT_H_
  44 #define _SQLITEINT_H_
  45 
  46 /*
  47 ** These #defines should enable >2GB file support on POSIX if the
  48 ** underlying operating system supports it.  If the OS lacks
  49 ** large file support, or if the OS is windows, these should be no-ops.
  50 **
  51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
  52 ** system #includes.  Hence, this block of code must be the very first
  53 ** code in all source files.
  54 **
  55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  56 ** on the compiler command line.  This is necessary if you are compiling
  57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
  59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
  60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
  61 ** portability you should omit LFS.
  62 **
  63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
  64 */
  65 #ifndef SQLITE_DISABLE_LFS
  66 # define _LARGE_FILE       1
  67 # ifndef _FILE_OFFSET_BITS
  68 #   define _FILE_OFFSET_BITS 64
  69 # endif
  70 # define _LARGEFILE_SOURCE 1
  71 #endif
  72 
  73 /*
  74 ** Include the configuration header output by 'configure' if we're using the
  75 ** autoconf-based build
  76 */
  77 #ifdef _HAVE_SQLITE_CONFIG_H
  78 #include "config.h"
  79 #endif
  80 
  81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  82 /************** Begin file sqliteLimit.h *************************************/
  83 /*
  84 ** 2007 May 7
  85 **
  86 ** The author disclaims copyright to this source code.  In place of
  87 ** a legal notice, here is a blessing:
  88 **
  89 **    May you do good and not evil.
  90 **    May you find forgiveness for yourself and forgive others.
  91 **    May you share freely, never taking more than you give.
  92 **
  93 *************************************************************************
  94 **
  95 ** This file defines various limits of what SQLite can process.
  96 */
  97 
  98 /*
  99 ** The maximum length of a TEXT or BLOB in bytes.   This also
 100 ** limits the size of a row in a table or index.
 101 **
 102 ** The hard limit is the ability of a 32-bit signed integer
 103 ** to count the size: 2^31-1 or 2147483647.
 104 */
 105 #ifndef SQLITE_MAX_LENGTH
 106 # define SQLITE_MAX_LENGTH 1000000000
 107 #endif
 108 
 109 /*
 110 ** This is the maximum number of
 111 **
 112 **    * Columns in a table
 113 **    * Columns in an index
 114 **    * Columns in a view
 115 **    * Terms in the SET clause of an UPDATE statement
 116 **    * Terms in the result set of a SELECT statement
 117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
 118 **    * Terms in the VALUES clause of an INSERT statement
 119 **
 120 ** The hard upper limit here is 32676.  Most database people will
 121 ** tell you that in a well-normalized database, you usually should
 122 ** not have more than a dozen or so columns in any table.  And if
 123 ** that is the case, there is no point in having more than a few
 124 ** dozen values in any of the other situations described above.
 125 */
 126 #ifndef SQLITE_MAX_COLUMN
 127 # define SQLITE_MAX_COLUMN 2000
 128 #endif
 129 
 130 /*
 131 ** The maximum length of a single SQL statement in bytes.
 132 **
 133 ** It used to be the case that setting this value to zero would
 134 ** turn the limit off.  That is no longer true.  It is not possible
 135 ** to turn this limit off.
 136 */
 137 #ifndef SQLITE_MAX_SQL_LENGTH
 138 # define SQLITE_MAX_SQL_LENGTH 1000000000
 139 #endif
 140 
 141 /*
 142 ** The maximum depth of an expression tree. This is limited to
 143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
 144 ** want to place more severe limits on the complexity of an
 145 ** expression.
 146 **
 147 ** A value of 0 used to mean that the limit was not enforced.
 148 ** But that is no longer true.  The limit is now strictly enforced
 149 ** at all times.
 150 */
 151 #ifndef SQLITE_MAX_EXPR_DEPTH
 152 # define SQLITE_MAX_EXPR_DEPTH 1000
 153 #endif
 154 
 155 /*
 156 ** The maximum number of terms in a compound SELECT statement.
 157 ** The code generator for compound SELECT statements does one
 158 ** level of recursion for each term.  A stack overflow can result
 159 ** if the number of terms is too large.  In practice, most SQL
 160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
 161 ** any limit on the number of terms in a compount SELECT.
 162 */
 163 #ifndef SQLITE_MAX_COMPOUND_SELECT
 164 # define SQLITE_MAX_COMPOUND_SELECT 500
 165 #endif
 166 
 167 /*
 168 ** The maximum number of opcodes in a VDBE program.
 169 ** Not currently enforced.
 170 */
 171 #ifndef SQLITE_MAX_VDBE_OP
 172 # define SQLITE_MAX_VDBE_OP 25000
 173 #endif
 174 
 175 /*
 176 ** The maximum number of arguments to an SQL function.
 177 */
 178 #ifndef SQLITE_MAX_FUNCTION_ARG
 179 # define SQLITE_MAX_FUNCTION_ARG 127
 180 #endif
 181 
 182 /*
 183 ** The maximum number of in-memory pages to use for the main database
 184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
 185 */
 186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
 187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
 188 #endif
 189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
 190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
 191 #endif
 192 
 193 /*
 194 ** The default number of frames to accumulate in the log file before
 195 ** checkpointing the database in WAL mode.
 196 */
 197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
 198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
 199 #endif
 200 
 201 /*
 202 ** The maximum number of attached databases.  This must be between 0
 203 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
 204 ** is used internally to track attached databases.
 205 */
 206 #ifndef SQLITE_MAX_ATTACHED
 207 # define SQLITE_MAX_ATTACHED 10
 208 #endif
 209 
 210 
 211 /*
 212 ** The maximum value of a ?nnn wildcard that the parser will accept.
 213 */
 214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
 215 # define SQLITE_MAX_VARIABLE_NUMBER 999
 216 #endif
 217 
 218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
 219 ** imposed by the use of 16-bit offsets within each page.
 220 **
 221 ** Earlier versions of SQLite allowed the user to change this value at
 222 ** compile time. This is no longer permitted, on the grounds that it creates
 223 ** a library that is technically incompatible with an SQLite library
 224 ** compiled with a different limit. If a process operating on a database
 225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
 226 ** compiled with the default page-size limit will not be able to rollback
 227 ** the aborted transaction. This could lead to database corruption.
 228 */
 229 #ifdef SQLITE_MAX_PAGE_SIZE
 230 # undef SQLITE_MAX_PAGE_SIZE
 231 #endif
 232 #define SQLITE_MAX_PAGE_SIZE 65536
 233 
 234 
 235 /*
 236 ** The default size of a database page.
 237 */
 238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
 239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
 240 #endif
 241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
 242 # undef SQLITE_DEFAULT_PAGE_SIZE
 243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
 244 #endif
 245 
 246 /*
 247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
 248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
 249 ** device characteristics (sector-size and atomic write() support),
 250 ** SQLite may choose a larger value. This constant is the maximum value
 251 ** SQLite will choose on its own.
 252 */
 253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
 254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
 255 #endif
 256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
 257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
 258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
 259 #endif
 260 
 261 
 262 /*
 263 ** Maximum number of pages in one database file.
 264 **
 265 ** This is really just the default value for the max_page_count pragma.
 266 ** This value can be lowered (or raised) at run-time using that the
 267 ** max_page_count macro.
 268 */
 269 #ifndef SQLITE_MAX_PAGE_COUNT
 270 # define SQLITE_MAX_PAGE_COUNT 1073741823
 271 #endif
 272 
 273 /*
 274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
 275 ** operator.
 276 */
 277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
 278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
 279 #endif
 280 
 281 /*
 282 ** Maximum depth of recursion for triggers.
 283 **
 284 ** A value of 1 means that a trigger program will not be able to itself
 285 ** fire any triggers. A value of 0 means that no trigger programs at all
 286 ** may be executed.
 287 */
 288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
 289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
 290 #endif
 291 
 292 /************** End of sqliteLimit.h *****************************************/
 293 /************** Continuing where we left off in sqliteInt.h ******************/
 294 
 295 /* Disable nuisance warnings on Borland compilers */
 296 #if defined(__BORLANDC__)
 297 #pragma warn -rch /* unreachable code */
 298 #pragma warn -ccc /* Condition is always true or false */
 299 #pragma warn -aus /* Assigned value is never used */
 300 #pragma warn -csu /* Comparing signed and unsigned */
 301 #pragma warn -spa /* Suspicious pointer arithmetic */
 302 #endif
 303 
 304 /* Needed for various definitions... */
 305 #ifndef _GNU_SOURCE
 306 # define _GNU_SOURCE
 307 #endif
 308 
 309 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
 310 # define _BSD_SOURCE
 311 #endif
 312 
 313 /*
 314 ** Include standard header files as necessary
 315 */
 316 #ifdef HAVE_STDINT_H
 317 #include <stdint.h>
 318 #endif
 319 #ifdef HAVE_INTTYPES_H
 320 #include <inttypes.h>
 321 #endif
 322 
 323 /*
 324 ** The following macros are used to cast pointers to integers and
 325 ** integers to pointers.  The way you do this varies from one compiler
 326 ** to the next, so we have developed the following set of #if statements
 327 ** to generate appropriate macros for a wide range of compilers.
 328 **
 329 ** The correct "ANSI" way to do this is to use the intptr_t type.
 330 ** Unfortunately, that typedef is not available on all compilers, or
 331 ** if it is available, it requires an #include of specific headers
 332 ** that vary from one machine to the next.
 333 **
 334 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
 335 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
 336 ** So we have to define the macros in different ways depending on the
 337 ** compiler.
 338 */
 339 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
 340 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
 341 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
 342 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
 343 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
 344 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
 345 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
 346 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
 347 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
 348 #else                          /* Generates a warning - but it always works */
 349 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
 350 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
 351 #endif
 352 
 353 /*
 354 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
 355 ** 0 means mutexes are permanently disable and the library is never
 356 ** threadsafe.  1 means the library is serialized which is the highest
 357 ** level of threadsafety.  2 means the libary is multithreaded - multiple
 358 ** threads can use SQLite as long as no two threads try to use the same
 359 ** database connection at the same time.
 360 **
 361 ** Older versions of SQLite used an optional THREADSAFE macro.
 362 ** We support that for legacy.
 363 */
 364 #if !defined(SQLITE_THREADSAFE)
 365 #if defined(THREADSAFE)
 366 # define SQLITE_THREADSAFE THREADSAFE
 367 #else
 368 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
 369 #endif
 370 #endif
 371 
 372 /*
 373 ** Powersafe overwrite is on by default.  But can be turned off using
 374 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
 375 */
 376 #ifndef SQLITE_POWERSAFE_OVERWRITE
 377 # define SQLITE_POWERSAFE_OVERWRITE 1
 378 #endif
 379 
 380 /*
 381 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
 382 ** It determines whether or not the features related to
 383 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
 384 ** be overridden at runtime using the sqlite3_config() API.
 385 */
 386 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
 387 # define SQLITE_DEFAULT_MEMSTATUS 1
 388 #endif
 389 
 390 /*
 391 ** Exactly one of the following macros must be defined in order to
 392 ** specify which memory allocation subsystem to use.
 393 **
 394 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
 395 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
 396 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
 397 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
 398 **
 399 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
 400 ** assert() macro is enabled, each call into the Win32 native heap subsystem
 401 ** will cause HeapValidate to be called.  If heap validation should fail, an
 402 ** assertion will be triggered.
 403 **
 404 ** (Historical note:  There used to be several other options, but we've
 405 ** pared it down to just these three.)
 406 **
 407 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
 408 ** the default.
 409 */
 410 #if defined(SQLITE_SYSTEM_MALLOC) \
 411   + defined(SQLITE_WIN32_MALLOC) \
 412   + defined(SQLITE_ZERO_MALLOC) \
 413   + defined(SQLITE_MEMDEBUG)>1
 414 # error "Two or more of the following compile-time configuration options\
 415  are defined but at most one is allowed:\
 416  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
 417  SQLITE_ZERO_MALLOC"
 418 #endif
 419 #if defined(SQLITE_SYSTEM_MALLOC) \
 420   + defined(SQLITE_WIN32_MALLOC) \
 421   + defined(SQLITE_ZERO_MALLOC) \
 422   + defined(SQLITE_MEMDEBUG)==0
 423 # define SQLITE_SYSTEM_MALLOC 1
 424 #endif
 425 
 426 /*
 427 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
 428 ** sizes of memory allocations below this value where possible.
 429 */
 430 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
 431 # define SQLITE_MALLOC_SOFT_LIMIT 1024
 432 #endif
 433 
 434 /*
 435 ** We need to define _XOPEN_SOURCE as follows in order to enable
 436 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
 437 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
 438 ** so it is omitted there.  See ticket #2673.
 439 **
 440 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
 441 ** implemented on some systems.  So we avoid defining it at all
 442 ** if it is already defined or if it is unneeded because we are
 443 ** not doing a threadsafe build.  Ticket #2681.
 444 **
 445 ** See also ticket #2741.
 446 */
 447 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \
 448  && !defined(__APPLE__) && SQLITE_THREADSAFE
 449 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
 450 #endif
 451 
 452 /*
 453 ** The TCL headers are only needed when compiling the TCL bindings.
 454 */
 455 #if defined(SQLITE_TCL) || defined(TCLSH)
 456 # include <tcl.h>
 457 #endif
 458 
 459 /*
 460 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
 461 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
 462 ** make it true by defining or undefining NDEBUG.
 463 **
 464 ** Setting NDEBUG makes the code smaller and run faster by disabling the
 465 ** number assert() statements in the code.  So we want the default action
 466 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
 467 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
 468 ** feature.
 469 */
 470 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
 471 # define NDEBUG 1
 472 #endif
 473 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
 474 # undef NDEBUG
 475 #endif
 476 
 477 /*
 478 ** The testcase() macro is used to aid in coverage testing.  When
 479 ** doing coverage testing, the condition inside the argument to
 480 ** testcase() must be evaluated both true and false in order to
 481 ** get full branch coverage.  The testcase() macro is inserted
 482 ** to help ensure adequate test coverage in places where simple
 483 ** condition/decision coverage is inadequate.  For example, testcase()
 484 ** can be used to make sure boundary values are tested.  For
 485 ** bitmask tests, testcase() can be used to make sure each bit
 486 ** is significant and used at least once.  On switch statements
 487 ** where multiple cases go to the same block of code, testcase()
 488 ** can insure that all cases are evaluated.
 489 **
 490 */
 491 #ifdef SQLITE_COVERAGE_TEST
 492 SQLITE_PRIVATE   void sqlite3Coverage(int);
 493 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
 494 #else
 495 # define testcase(X)
 496 #endif
 497 
 498 /*
 499 ** The TESTONLY macro is used to enclose variable declarations or
 500 ** other bits of code that are needed to support the arguments
 501 ** within testcase() and assert() macros.
 502 */
 503 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
 504 # define TESTONLY(X)  X
 505 #else
 506 # define TESTONLY(X)
 507 #endif
 508 
 509 /*
 510 ** Sometimes we need a small amount of code such as a variable initialization
 511 ** to setup for a later assert() statement.  We do not want this code to
 512 ** appear when assert() is disabled.  The following macro is therefore
 513 ** used to contain that setup code.  The "VVA" acronym stands for
 514 ** "Verification, Validation, and Accreditation".  In other words, the
 515 ** code within VVA_ONLY() will only run during verification processes.
 516 */
 517 #ifndef NDEBUG
 518 # define VVA_ONLY(X)  X
 519 #else
 520 # define VVA_ONLY(X)
 521 #endif
 522 
 523 /*
 524 ** The ALWAYS and NEVER macros surround boolean expressions which
 525 ** are intended to always be true or false, respectively.  Such
 526 ** expressions could be omitted from the code completely.  But they
 527 ** are included in a few cases in order to enhance the resilience
 528 ** of SQLite to unexpected behavior - to make the code "self-healing"
 529 ** or "ductile" rather than being "brittle" and crashing at the first
 530 ** hint of unplanned behavior.
 531 **
 532 ** In other words, ALWAYS and NEVER are added for defensive code.
 533 **
 534 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
 535 ** be true and false so that the unreachable code then specify will
 536 ** not be counted as untested code.
 537 */
 538 #if defined(SQLITE_COVERAGE_TEST)
 539 # define ALWAYS(X)      (1)
 540 # define NEVER(X)       (0)
 541 #elif !defined(NDEBUG)
 542 # define ALWAYS(X)      ((X)?1:(assert(0),0))
 543 # define NEVER(X)       ((X)?(assert(0),1):0)
 544 #else
 545 # define ALWAYS(X)      (X)
 546 # define NEVER(X)       (X)
 547 #endif
 548 
 549 /*
 550 ** Return true (non-zero) if the input is a integer that is too large
 551 ** to fit in 32-bits.  This macro is used inside of various testcase()
 552 ** macros to verify that we have tested SQLite for large-file support.
 553 */
 554 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
 555 
 556 /*
 557 ** The macro unlikely() is a hint that surrounds a boolean
 558 ** expression that is usually false.  Macro likely() surrounds
 559 ** a boolean expression that is usually true.  GCC is able to
 560 ** use these hints to generate better code, sometimes.
 561 */
 562 #if defined(__GNUC__) && 0
 563 # define likely(X)    __builtin_expect((X),1)
 564 # define unlikely(X)  __builtin_expect((X),0)
 565 #else
 566 # define likely(X)    !!(X)
 567 # define unlikely(X)  !!(X)
 568 #endif
 569 
 570 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
 571 /************** Begin file sqlite3.h *****************************************/
 572 /*
 573 ** 2001 September 15
 574 **
 575 ** The author disclaims copyright to this source code.  In place of
 576 ** a legal notice, here is a blessing:
 577 **
 578 **    May you do good and not evil.
 579 **    May you find forgiveness for yourself and forgive others.
 580 **    May you share freely, never taking more than you give.
 581 **
 582 *************************************************************************
 583 ** This header file defines the interface that the SQLite library
 584 ** presents to client programs.  If a C-function, structure, datatype,
 585 ** or constant definition does not appear in this file, then it is
 586 ** not a published API of SQLite, is subject to change without
 587 ** notice, and should not be referenced by programs that use SQLite.
 588 **
 589 ** Some of the definitions that are in this file are marked as
 590 ** "experimental".  Experimental interfaces are normally new
 591 ** features recently added to SQLite.  We do not anticipate changes
 592 ** to experimental interfaces but reserve the right to make minor changes
 593 ** if experience from use "in the wild" suggest such changes are prudent.
 594 **
 595 ** The official C-language API documentation for SQLite is derived
 596 ** from comments in this file.  This file is the authoritative source
 597 ** on how SQLite interfaces are suppose to operate.
 598 **
 599 ** The name of this file under configuration management is "sqlite.h.in".
 600 ** The makefile makes some minor changes to this file (such as inserting
 601 ** the version number) and changes its name to "sqlite3.h" as
 602 ** part of the build process.
 603 */
 604 #ifndef _SQLITE3_H_
 605 #define _SQLITE3_H_
 606 #include <stdarg.h>     /* Needed for the definition of va_list */
 607 
 608 /*
 609 ** Make sure we can call this stuff from C++.
 610 */
 611 #if 0
 612 extern "C" {
 613 #endif
 614 
 615 
 616 /*
 617 ** Add the ability to override 'extern'
 618 */
 619 #ifndef SQLITE_EXTERN
 620 # define SQLITE_EXTERN extern
 621 #endif
 622 
 623 #ifndef SQLITE_API
 624 # define SQLITE_API
 625 #endif
 626 
 627 
 628 /*
 629 ** These no-op macros are used in front of interfaces to mark those
 630 ** interfaces as either deprecated or experimental.  New applications
 631 ** should not use deprecated interfaces - they are support for backwards
 632 ** compatibility only.  Application writers should be aware that
 633 ** experimental interfaces are subject to change in point releases.
 634 **
 635 ** These macros used to resolve to various kinds of compiler magic that
 636 ** would generate warning messages when they were used.  But that
 637 ** compiler magic ended up generating such a flurry of bug reports
 638 ** that we have taken it all out and gone back to using simple
 639 ** noop macros.
 640 */
 641 #define SQLITE_DEPRECATED
 642 #define SQLITE_EXPERIMENTAL
 643 
 644 /*
 645 ** Ensure these symbols were not defined by some previous header file.
 646 */
 647 #ifdef SQLITE_VERSION
 648 # undef SQLITE_VERSION
 649 #endif
 650 #ifdef SQLITE_VERSION_NUMBER
 651 # undef SQLITE_VERSION_NUMBER
 652 #endif
 653 
 654 /*
 655 ** CAPI3REF: Compile-Time Library Version Numbers
 656 **
 657 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
 658 ** evaluates to a string literal that is the SQLite version in the
 659 ** format "X.Y.Z" where X is the major version number (always 3 for
 660 ** SQLite3) and Y is the minor version number and Z is the release number.)^
 661 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
 662 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
 663 ** numbers used in [SQLITE_VERSION].)^
 664 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
 665 ** be larger than the release from which it is derived.  Either Y will
 666 ** be held constant and Z will be incremented or else Y will be incremented
 667 ** and Z will be reset to zero.
 668 **
 669 ** Since version 3.6.18, SQLite source code has been stored in the
 670 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
 671 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
 672 ** a string which identifies a particular check-in of SQLite
 673 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
 674 ** string contains the date and time of the check-in (UTC) and an SHA1
 675 ** hash of the entire source tree.
 676 **
 677 ** See also: [sqlite3_libversion()],
 678 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 679 ** [sqlite_version()] and [sqlite_source_id()].
 680 */
 681 #define SQLITE_VERSION        "3.7.16.2"
 682 #define SQLITE_VERSION_NUMBER 3007016
 683 #define SQLITE_SOURCE_ID      "2013-04-12 11:52:43 cbea02d93865ce0e06789db95fd9168ebac970c7"
 684 
 685 /*
 686 ** CAPI3REF: Run-Time Library Version Numbers
 687 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
 688 **
 689 ** These interfaces provide the same information as the [SQLITE_VERSION],
 690 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
 691 ** but are associated with the library instead of the header file.  ^(Cautious
 692 ** programmers might include assert() statements in their application to
 693 ** verify that values returned by these interfaces match the macros in
 694 ** the header, and thus insure that the application is
 695 ** compiled with matching library and header files.
 696 **
 697 ** <blockquote><pre>
 698 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
 699 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
 700 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
 701 ** </pre></blockquote>)^
 702 **
 703 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
 704 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
 705 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
 706 ** function is provided for use in DLLs since DLL users usually do not have
 707 ** direct access to string constants within the DLL.  ^The
 708 ** sqlite3_libversion_number() function returns an integer equal to
 709 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
 710 ** a pointer to a string constant whose value is the same as the
 711 ** [SQLITE_SOURCE_ID] C preprocessor macro.
 712 **
 713 ** See also: [sqlite_version()] and [sqlite_source_id()].
 714 */
 715 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
 716 SQLITE_API const char *sqlite3_libversion(void);
 717 SQLITE_API const char *sqlite3_sourceid(void);
 718 SQLITE_API int sqlite3_libversion_number(void);
 719 
 720 /*
 721 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
 722 **
 723 ** ^The sqlite3_compileoption_used() function returns 0 or 1
 724 ** indicating whether the specified option was defined at
 725 ** compile time.  ^The SQLITE_ prefix may be omitted from the
 726 ** option name passed to sqlite3_compileoption_used().
 727 **
 728 ** ^The sqlite3_compileoption_get() function allows iterating
 729 ** over the list of options that were defined at compile time by
 730 ** returning the N-th compile time option string.  ^If N is out of range,
 731 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
 732 ** prefix is omitted from any strings returned by
 733 ** sqlite3_compileoption_get().
 734 **
 735 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
 736 ** and sqlite3_compileoption_get() may be omitted by specifying the
 737 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
 738 **
 739 ** See also: SQL functions [sqlite_compileoption_used()] and
 740 ** [sqlite_compileoption_get()] and the [compile_options pragma].
 741 */
 742 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 743 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
 744 SQLITE_API const char *sqlite3_compileoption_get(int N);
 745 #endif
 746 
 747 /*
 748 ** CAPI3REF: Test To See If The Library Is Threadsafe
 749 **
 750 ** ^The sqlite3_threadsafe() function returns zero if and only if
 751 ** SQLite was compiled with mutexing code omitted due to the
 752 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
 753 **
 754 ** SQLite can be compiled with or without mutexes.  When
 755 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
 756 ** are enabled and SQLite is threadsafe.  When the
 757 ** [SQLITE_THREADSAFE] macro is 0,
 758 ** the mutexes are omitted.  Without the mutexes, it is not safe
 759 ** to use SQLite concurrently from more than one thread.
 760 **
 761 ** Enabling mutexes incurs a measurable performance penalty.
 762 ** So if speed is of utmost importance, it makes sense to disable
 763 ** the mutexes.  But for maximum safety, mutexes should be enabled.
 764 ** ^The default behavior is for mutexes to be enabled.
 765 **
 766 ** This interface can be used by an application to make sure that the
 767 ** version of SQLite that it is linking against was compiled with
 768 ** the desired setting of the [SQLITE_THREADSAFE] macro.
 769 **
 770 ** This interface only reports on the compile-time mutex setting
 771 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
 772 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
 773 ** can be fully or partially disabled using a call to [sqlite3_config()]
 774 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
 775 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
 776 ** sqlite3_threadsafe() function shows only the compile-time setting of
 777 ** thread safety, not any run-time changes to that setting made by
 778 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
 779 ** is unchanged by calls to sqlite3_config().)^
 780 **
 781 ** See the [threading mode] documentation for additional information.
 782 */
 783 SQLITE_API int sqlite3_threadsafe(void);
 784 
 785 /*
 786 ** CAPI3REF: Database Connection Handle
 787 ** KEYWORDS: {database connection} {database connections}
 788 **
 789 ** Each open SQLite database is represented by a pointer to an instance of
 790 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
 791 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
 792 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
 793 ** and [sqlite3_close_v2()] are its destructors.  There are many other
 794 ** interfaces (such as
 795 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
 796 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
 797 ** sqlite3 object.
 798 */
 799 typedef struct sqlite3 sqlite3;
 800 
 801 /*
 802 ** CAPI3REF: 64-Bit Integer Types
 803 ** KEYWORDS: sqlite_int64 sqlite_uint64
 804 **
 805 ** Because there is no cross-platform way to specify 64-bit integer types
 806 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
 807 **
 808 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
 809 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
 810 ** compatibility only.
 811 **
 812 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
 813 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
 814 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
 815 ** between 0 and +18446744073709551615 inclusive.
 816 */
 817 #ifdef SQLITE_INT64_TYPE
 818   typedef SQLITE_INT64_TYPE sqlite_int64;
 819   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
 820 #elif defined(_MSC_VER) || defined(__BORLANDC__)
 821   typedef __int64 sqlite_int64;
 822   typedef unsigned __int64 sqlite_uint64;
 823 #else
 824   typedef long long int sqlite_int64;
 825   typedef unsigned long long int sqlite_uint64;
 826 #endif
 827 typedef sqlite_int64 sqlite3_int64;
 828 typedef sqlite_uint64 sqlite3_uint64;
 829 
 830 /*
 831 ** If compiling for a processor that lacks floating point support,
 832 ** substitute integer for floating-point.
 833 */
 834 #ifdef SQLITE_OMIT_FLOATING_POINT
 835 # define double sqlite3_int64
 836 #endif
 837 
 838 /*
 839 ** CAPI3REF: Closing A Database Connection
 840 **
 841 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
 842 ** for the [sqlite3] object.
 843 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
 844 ** the [sqlite3] object is successfully destroyed and all associated
 845 ** resources are deallocated.
 846 **
 847 ** ^If the database connection is associated with unfinalized prepared
 848 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
 849 ** will leave the database connection open and return [SQLITE_BUSY].
 850 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
 851 ** and unfinished sqlite3_backups, then the database connection becomes
 852 ** an unusable "zombie" which will automatically be deallocated when the
 853 ** last prepared statement is finalized or the last sqlite3_backup is
 854 ** finished.  The sqlite3_close_v2() interface is intended for use with
 855 ** host languages that are garbage collected, and where the order in which
 856 ** destructors are called is arbitrary.
 857 **
 858 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
 859 ** [sqlite3_blob_close | close] all [BLOB handles], and
 860 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
 861 ** with the [sqlite3] object prior to attempting to close the object.  ^If
 862 ** sqlite3_close_v2() is called on a [database connection] that still has
 863 ** outstanding [prepared statements], [BLOB handles], and/or
 864 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
 865 ** of resources is deferred until all [prepared statements], [BLOB handles],
 866 ** and [sqlite3_backup] objects are also destroyed.
 867 **
 868 ** ^If an [sqlite3] object is destroyed while a transaction is open,
 869 ** the transaction is automatically rolled back.
 870 **
 871 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
 872 ** must be either a NULL
 873 ** pointer or an [sqlite3] object pointer obtained
 874 ** from [sqlite3_open()], [sqlite3_open16()], or
 875 ** [sqlite3_open_v2()], and not previously closed.
 876 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
 877 ** argument is a harmless no-op.
 878 */
 879 SQLITE_API int sqlite3_close(sqlite3*);
 880 SQLITE_API int sqlite3_close_v2(sqlite3*);
 881 
 882 /*
 883 ** The type for a callback function.
 884 ** This is legacy and deprecated.  It is included for historical
 885 ** compatibility and is not documented.
 886 */
 887 typedef int (*sqlite3_callback)(void*,int,char**, char**);
 888 
 889 /*
 890 ** CAPI3REF: One-Step Query Execution Interface
 891 **
 892 ** The sqlite3_exec() interface is a convenience wrapper around
 893 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
 894 ** that allows an application to run multiple statements of SQL
 895 ** without having to use a lot of C code.
 896 **
 897 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
 898 ** semicolon-separate SQL statements passed into its 2nd argument,
 899 ** in the context of the [database connection] passed in as its 1st
 900 ** argument.  ^If the callback function of the 3rd argument to
 901 ** sqlite3_exec() is not NULL, then it is invoked for each result row
 902 ** coming out of the evaluated SQL statements.  ^The 4th argument to
 903 ** sqlite3_exec() is relayed through to the 1st argument of each
 904 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
 905 ** is NULL, then no callback is ever invoked and result rows are
 906 ** ignored.
 907 **
 908 ** ^If an error occurs while evaluating the SQL statements passed into
 909 ** sqlite3_exec(), then execution of the current statement stops and
 910 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
 911 ** is not NULL then any error message is written into memory obtained
 912 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
 913 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
 914 ** on error message strings returned through the 5th parameter of
 915 ** of sqlite3_exec() after the error message string is no longer needed.
 916 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
 917 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
 918 ** NULL before returning.
 919 **
 920 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
 921 ** routine returns SQLITE_ABORT without invoking the callback again and
 922 ** without running any subsequent SQL statements.
 923 **
 924 ** ^The 2nd argument to the sqlite3_exec() callback function is the
 925 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
 926 ** callback is an array of pointers to strings obtained as if from
 927 ** [sqlite3_column_text()], one for each column.  ^If an element of a
 928 ** result row is NULL then the corresponding string pointer for the
 929 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
 930 ** sqlite3_exec() callback is an array of pointers to strings where each
 931 ** entry represents the name of corresponding result column as obtained
 932 ** from [sqlite3_column_name()].
 933 **
 934 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
 935 ** to an empty string, or a pointer that contains only whitespace and/or
 936 ** SQL comments, then no SQL statements are evaluated and the database
 937 ** is not changed.
 938 **
 939 ** Restrictions:
 940 **
 941 ** <ul>
 942 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
 943 **      is a valid and open [database connection].
 944 ** <li> The application must not close [database connection] specified by
 945 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
 946 ** <li> The application must not modify the SQL statement text passed into
 947 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
 948 ** </ul>
 949 */
 950 SQLITE_API int sqlite3_exec(
 951   sqlite3*,                                  /* An open database */
 952   const char *sql,                           /* SQL to be evaluated */
 953   int (*callback)(void*,int,char**,char**),  /* Callback function */
 954   void *,                                    /* 1st argument to callback */
 955   char **errmsg                              /* Error msg written here */
 956 );
 957 
 958 /*
 959 ** CAPI3REF: Result Codes
 960 ** KEYWORDS: SQLITE_OK {error code} {error codes}
 961 ** KEYWORDS: {result code} {result codes}
 962 **
 963 ** Many SQLite functions return an integer result code from the set shown
 964 ** here in order to indicate success or failure.
 965 **
 966 ** New error codes may be added in future versions of SQLite.
 967 **
 968 ** See also: [SQLITE_IOERR_READ | extended result codes],
 969 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
 970 */
 971 #define SQLITE_OK           0   /* Successful result */
 972 /* beginning-of-error-codes */
 973 #define SQLITE_ERROR        1   /* SQL error or missing database */
 974 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
 975 #define SQLITE_PERM         3   /* Access permission denied */
 976 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
 977 #define SQLITE_BUSY         5   /* The database file is locked */
 978 #define SQLITE_LOCKED       6   /* A table in the database is locked */
 979 #define SQLITE_NOMEM        7   /* A malloc() failed */
 980 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
 981 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
 982 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
 983 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
 984 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
 985 #define SQLITE_FULL        13   /* Insertion failed because database is full */
 986 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
 987 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
 988 #define SQLITE_EMPTY       16   /* Database is empty */
 989 #define SQLITE_SCHEMA      17   /* The database schema changed */
 990 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
 991 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
 992 #define SQLITE_MISMATCH    20   /* Data type mismatch */
 993 #define SQLITE_MISUSE      21   /* Library used incorrectly */
 994 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
 995 #define SQLITE_AUTH        23   /* Authorization denied */
 996 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
 997 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
 998 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
 999 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
1000 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
1001 /* end-of-error-codes */
1002 
1003 /*
1004 ** CAPI3REF: Extended Result Codes
1005 ** KEYWORDS: {extended error code} {extended error codes}
1006 ** KEYWORDS: {extended result code} {extended result codes}
1007 **
1008 ** In its default configuration, SQLite API routines return one of 26 integer
1009 ** [SQLITE_OK | result codes].  However, experience has shown that many of
1010 ** these result codes are too coarse-grained.  They do not provide as
1011 ** much information about problems as programmers might like.  In an effort to
1012 ** address this, newer versions of SQLite (version 3.3.8 and later) include
1013 ** support for additional result codes that provide more detailed information
1014 ** about errors. The extended result codes are enabled or disabled
1015 ** on a per database connection basis using the
1016 ** [sqlite3_extended_result_codes()] API.
1017 **
1018 ** Some of the available extended result codes are listed here.
1019 ** One may expect the number of extended result codes will be expand
1020 ** over time.  Software that uses extended result codes should expect
1021 ** to see new result codes in future releases of SQLite.
1022 **
1023 ** The SQLITE_OK result code will never be extended.  It will always
1024 ** be exactly zero.
1025 */
1026 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1027 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1028 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1029 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1030 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1031 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1032 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1033 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1034 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1035 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1036 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1037 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1038 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1039 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1040 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1041 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1042 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1043 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1044 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1045 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1046 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1047 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1048 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
1049 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1050 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1051 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1052 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1053 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
1054 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1055 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1056 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1057 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
1058 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1059 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
1060 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
1061 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
1062 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
1063 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
1064 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
1065 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
1066 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
1067 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
1068 
1069 /*
1070 ** CAPI3REF: Flags For File Open Operations
1071 **
1072 ** These bit values are intended for use in the
1073 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1074 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1075 */
1076 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1077 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1078 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1079 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1080 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1081 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1082 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1083 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1084 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1085 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1086 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1087 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1088 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1089 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1090 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1091 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1092 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1093 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1094 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1095 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1096 
1097 /* Reserved:                         0x00F00000 */
1098 
1099 /*
1100 ** CAPI3REF: Device Characteristics
1101 **
1102 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1103 ** object returns an integer which is a vector of these
1104 ** bit values expressing I/O characteristics of the mass storage
1105 ** device that holds the file that the [sqlite3_io_methods]
1106 ** refers to.
1107 **
1108 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1109 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1110 ** mean that writes of blocks that are nnn bytes in size and
1111 ** are aligned to an address which is an integer multiple of
1112 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1113 ** that when data is appended to a file, the data is appended
1114 ** first then the size of the file is extended, never the other
1115 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1116 ** information is written to disk in the same order as calls
1117 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1118 ** after reboot following a crash or power loss, the only bytes in a
1119 ** file that were written at the application level might have changed
1120 ** and that adjacent bytes, even bytes within the same sector are
1121 ** guaranteed to be unchanged.
1122 */
1123 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1124 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1125 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1126 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1127 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1128 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1129 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1130 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1131 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1132 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1133 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1134 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1135 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1136 
1137 /*
1138 ** CAPI3REF: File Locking Levels
1139 **
1140 ** SQLite uses one of these integer values as the second
1141 ** argument to calls it makes to the xLock() and xUnlock() methods
1142 ** of an [sqlite3_io_methods] object.
1143 */
1144 #define SQLITE_LOCK_NONE          0
1145 #define SQLITE_LOCK_SHARED        1
1146 #define SQLITE_LOCK_RESERVED      2
1147 #define SQLITE_LOCK_PENDING       3
1148 #define SQLITE_LOCK_EXCLUSIVE     4
1149 
1150 /*
1151 ** CAPI3REF: Synchronization Type Flags
1152 **
1153 ** When SQLite invokes the xSync() method of an
1154 ** [sqlite3_io_methods] object it uses a combination of
1155 ** these integer values as the second argument.
1156 **
1157 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1158 ** sync operation only needs to flush data to mass storage.  Inode
1159 ** information need not be flushed. If the lower four bits of the flag
1160 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1161 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1162 ** to use Mac OS X style fullsync instead of fsync().
1163 **
1164 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1165 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1166 ** settings.  The [synchronous pragma] determines when calls to the
1167 ** xSync VFS method occur and applies uniformly across all platforms.
1168 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1169 ** energetic or rigorous or forceful the sync operations are and
1170 ** only make a difference on Mac OSX for the default SQLite code.
1171 ** (Third-party VFS implementations might also make the distinction
1172 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1173 ** operating systems natively supported by SQLite, only Mac OSX
1174 ** cares about the difference.)
1175 */
1176 #define SQLITE_SYNC_NORMAL        0x00002
1177 #define SQLITE_SYNC_FULL          0x00003
1178 #define SQLITE_SYNC_DATAONLY      0x00010
1179 
1180 /*
1181 ** CAPI3REF: OS Interface Open File Handle
1182 **
1183 ** An [sqlite3_file] object represents an open file in the
1184 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1185 ** implementations will
1186 ** want to subclass this object by appending additional fields
1187 ** for their own use.  The pMethods entry is a pointer to an
1188 ** [sqlite3_io_methods] object that defines methods for performing
1189 ** I/O operations on the open file.
1190 */
1191 typedef struct sqlite3_file sqlite3_file;
1192 struct sqlite3_file {
1193   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1194 };
1195 
1196 /*
1197 ** CAPI3REF: OS Interface File Virtual Methods Object
1198 **
1199 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1200 ** [sqlite3_file] object (or, more commonly, a subclass of the
1201 ** [sqlite3_file] object) with a pointer to an instance of this object.
1202 ** This object defines the methods used to perform various operations
1203 ** against the open file represented by the [sqlite3_file] object.
1204 **
1205 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1206 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1207 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1208 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1209 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1210 ** to NULL.
1211 **
1212 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1213 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1214 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1215 ** flag may be ORed in to indicate that only the data of the file
1216 ** and not its inode needs to be synced.
1217 **
1218 ** The integer values to xLock() and xUnlock() are one of
1219 ** <ul>
1220 ** <li> [SQLITE_LOCK_NONE],
1221 ** <li> [SQLITE_LOCK_SHARED],
1222 ** <li> [SQLITE_LOCK_RESERVED],
1223 ** <li> [SQLITE_LOCK_PENDING], or
1224 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1225 ** </ul>
1226 ** xLock() increases the lock. xUnlock() decreases the lock.
1227 ** The xCheckReservedLock() method checks whether any database connection,
1228 ** either in this process or in some other process, is holding a RESERVED,
1229 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1230 ** if such a lock exists and false otherwise.
1231 **
1232 ** The xFileControl() method is a generic interface that allows custom
1233 ** VFS implementations to directly control an open file using the
1234 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1235 ** integer opcode.  The third argument is a generic pointer intended to
1236 ** point to a structure that may contain arguments or space in which to
1237 ** write return values.  Potential uses for xFileControl() might be
1238 ** functions to enable blocking locks with timeouts, to change the
1239 ** locking strategy (for example to use dot-file locks), to inquire
1240 ** about the status of a lock, or to break stale locks.  The SQLite
1241 ** core reserves all opcodes less than 100 for its own use.
1242 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1243 ** Applications that define a custom xFileControl method should use opcodes
1244 ** greater than 100 to avoid conflicts.  VFS implementations should
1245 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1246 ** recognize.
1247 **
1248 ** The xSectorSize() method returns the sector size of the
1249 ** device that underlies the file.  The sector size is the
1250 ** minimum write that can be performed without disturbing
1251 ** other bytes in the file.  The xDeviceCharacteristics()
1252 ** method returns a bit vector describing behaviors of the
1253 ** underlying device:
1254 **
1255 ** <ul>
1256 ** <li> [SQLITE_IOCAP_ATOMIC]
1257 ** <li> [SQLITE_IOCAP_ATOMIC512]
1258 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1259 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1260 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1261 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1262 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1263 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1264 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1265 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1266 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1267 ** </ul>
1268 **
1269 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1270 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1271 ** mean that writes of blocks that are nnn bytes in size and
1272 ** are aligned to an address which is an integer multiple of
1273 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1274 ** that when data is appended to a file, the data is appended
1275 ** first then the size of the file is extended, never the other
1276 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1277 ** information is written to disk in the same order as calls
1278 ** to xWrite().
1279 **
1280 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1281 ** in the unread portions of the buffer with zeros.  A VFS that
1282 ** fails to zero-fill short reads might seem to work.  However,
1283 ** failure to zero-fill short reads will eventually lead to
1284 ** database corruption.
1285 */
1286 typedef struct sqlite3_io_methods sqlite3_io_methods;
1287 struct sqlite3_io_methods {
1288   int iVersion;
1289   int (*xClose)(sqlite3_file*);
1290   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1291   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1292   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1293   int (*xSync)(sqlite3_file*, int flags);
1294   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1295   int (*xLock)(sqlite3_file*, int);
1296   int (*xUnlock)(sqlite3_file*, int);
1297   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1298   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1299   int (*xSectorSize)(sqlite3_file*);
1300   int (*xDeviceCharacteristics)(sqlite3_file*);
1301   /* Methods above are valid for version 1 */
1302   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1303   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1304   void (*xShmBarrier)(sqlite3_file*);
1305   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1306   /* Methods above are valid for version 2 */
1307   /* Additional methods may be added in future releases */
1308 };
1309 
1310 /*
1311 ** CAPI3REF: Standard File Control Opcodes
1312 **
1313 ** These integer constants are opcodes for the xFileControl method
1314 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1315 ** interface.
1316 **
1317 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1318 ** opcode causes the xFileControl method to write the current state of
1319 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1320 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1321 ** into an integer that the pArg argument points to. This capability
1322 ** is used during testing and only needs to be supported when SQLITE_TEST
1323 ** is defined.
1324 ** <ul>
1325 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1326 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1327 ** layer a hint of how large the database file will grow to be during the
1328 ** current transaction.  This hint is not guaranteed to be accurate but it
1329 ** is often close.  The underlying VFS might choose to preallocate database
1330 ** file space based on this hint in order to help writes to the database
1331 ** file run faster.
1332 **
1333 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1334 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1335 ** extends and truncates the database file in chunks of a size specified
1336 ** by the user. The fourth argument to [sqlite3_file_control()] should
1337 ** point to an integer (type int) containing the new chunk-size to use
1338 ** for the nominated database. Allocating database file space in large
1339 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1340 ** improve performance on some systems.
1341 **
1342 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1343 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1344 ** to the [sqlite3_file] object associated with a particular database
1345 ** connection.  See the [sqlite3_file_control()] documentation for
1346 ** additional information.
1347 **
1348 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1349 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1350 ** SQLite and sent to all VFSes in place of a call to the xSync method
1351 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1352 ** Some specialized VFSes need this signal in order to operate correctly
1353 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1354 ** VFSes do not need this signal and should silently ignore this opcode.
1355 ** Applications should not call [sqlite3_file_control()] with this
1356 ** opcode as doing so may disrupt the operation of the specialized VFSes
1357 ** that do require it.
1358 **
1359 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1360 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1361 ** retry counts and intervals for certain disk I/O operations for the
1362 ** windows [VFS] in order to provide robustness in the presence of
1363 ** anti-virus programs.  By default, the windows VFS will retry file read,
1364 ** file write, and file delete operations up to 10 times, with a delay
1365 ** of 25 milliseconds before the first retry and with the delay increasing
1366 ** by an additional 25 milliseconds with each subsequent retry.  This
1367 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1368 ** to be adjusted.  The values are changed for all database connections
1369 ** within the same process.  The argument is a pointer to an array of two
1370 ** integers where the first integer i the new retry count and the second
1371 ** integer is the delay.  If either integer is negative, then the setting
1372 ** is not changed but instead the prior value of that setting is written
1373 ** into the array entry, allowing the current retry settings to be
1374 ** interrogated.  The zDbName parameter is ignored.
1375 **
1376 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1377 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1378 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1379 ** write ahead log and shared memory files used for transaction control
1380 ** are automatically deleted when the latest connection to the database
1381 ** closes.  Setting persistent WAL mode causes those files to persist after
1382 ** close.  Persisting the files is useful when other processes that do not
1383 ** have write permission on the directory containing the database file want
1384 ** to read the database file, as the WAL and shared memory files must exist
1385 ** in order for the database to be readable.  The fourth parameter to
1386 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1387 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1388 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1389 ** WAL persistence setting.
1390 **
1391 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1392 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1393 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1394 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1395 ** xDeviceCharacteristics methods. The fourth parameter to
1396 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1397 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1398 ** mode.  If the integer is -1, then it is overwritten with the current
1399 ** zero-damage mode setting.
1400 **
1401 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1402 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1403 ** a write transaction to indicate that, unless it is rolled back for some
1404 ** reason, the entire database file will be overwritten by the current
1405 ** transaction. This is used by VACUUM operations.
1406 **
1407 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1408 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1409 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1410 ** final bottom-level VFS are written into memory obtained from
1411 ** [sqlite3_malloc()] and the result is stored in the char* variable
1412 ** that the fourth parameter of [sqlite3_file_control()] points to.
1413 ** The caller is responsible for freeing the memory when done.  As with
1414 ** all file-control actions, there is no guarantee that this will actually
1415 ** do anything.  Callers should initialize the char* variable to a NULL
1416 ** pointer in case this file-control is not implemented.  This file-control
1417 ** is intended for diagnostic use only.
1418 **
1419 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1420 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1421 ** file control is sent to the open [sqlite3_file] object corresponding
1422 ** to the database file to which the pragma statement refers. ^The argument
1423 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1424 ** pointers to strings (char**) in which the second element of the array
1425 ** is the name of the pragma and the third element is the argument to the
1426 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1427 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1428 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1429 ** or the equivalent and that string will become the result of the pragma or
1430 ** the error message if the pragma fails. ^If the
1431 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1432 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1433 ** file control returns [SQLITE_OK], then the parser assumes that the
1434 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1435 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1436 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1437 ** that the VFS encountered an error while handling the [PRAGMA] and the
1438 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1439 ** file control occurs at the beginning of pragma statement analysis and so
1440 ** it is able to override built-in [PRAGMA] statements.
1441 **
1442 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1443 ** ^This file-control may be invoked by SQLite on the database file handle
1444 ** shortly after it is opened in order to provide a custom VFS with access
1445 ** to the connections busy-handler callback. The argument is of type (void **)
1446 ** - an array of two (void *) values. The first (void *) actually points
1447 ** to a function of type (int (*)(void *)). In order to invoke the connections
1448 ** busy-handler, this function should be invoked with the second (void *) in
1449 ** the array as the only argument. If it returns non-zero, then the operation
1450 ** should be retried. If it returns zero, the custom VFS should abandon the
1451 ** current operation.
1452 **
1453 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1454 ** ^Application can invoke this file-control to have SQLite generate a
1455 ** temporary filename using the same algorithm that is followed to generate
1456 ** temporary filenames for TEMP tables and other internal uses.  The
1457 ** argument should be a char** which will be filled with the filename
1458 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1459 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1460 **
1461 ** </ul>
1462 */
1463 #define SQLITE_FCNTL_LOCKSTATE               1
1464 #define SQLITE_GET_LOCKPROXYFILE             2
1465 #define SQLITE_SET_LOCKPROXYFILE             3
1466 #define SQLITE_LAST_ERRNO                    4
1467 #define SQLITE_FCNTL_SIZE_HINT               5
1468 #define SQLITE_FCNTL_CHUNK_SIZE              6
1469 #define SQLITE_FCNTL_FILE_POINTER            7
1470 #define SQLITE_FCNTL_SYNC_OMITTED            8
1471 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1472 #define SQLITE_FCNTL_PERSIST_WAL            10
1473 #define SQLITE_FCNTL_OVERWRITE              11
1474 #define SQLITE_FCNTL_VFSNAME                12
1475 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1476 #define SQLITE_FCNTL_PRAGMA                 14
1477 #define SQLITE_FCNTL_BUSYHANDLER            15
1478 #define SQLITE_FCNTL_TEMPFILENAME           16
1479 
1480 /*
1481 ** CAPI3REF: Mutex Handle
1482 **
1483 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1484 ** abstract type for a mutex object.  The SQLite core never looks
1485 ** at the internal representation of an [sqlite3_mutex].  It only
1486 ** deals with pointers to the [sqlite3_mutex] object.
1487 **
1488 ** Mutexes are created using [sqlite3_mutex_alloc()].
1489 */
1490 typedef struct sqlite3_mutex sqlite3_mutex;
1491 
1492 /*
1493 ** CAPI3REF: OS Interface Object
1494 **
1495 ** An instance of the sqlite3_vfs object defines the interface between
1496 ** the SQLite core and the underlying operating system.  The "vfs"
1497 ** in the name of the object stands for "virtual file system".  See
1498 ** the [VFS | VFS documentation] for further information.
1499 **
1500 ** The value of the iVersion field is initially 1 but may be larger in
1501 ** future versions of SQLite.  Additional fields may be appended to this
1502 ** object when the iVersion value is increased.  Note that the structure
1503 ** of the sqlite3_vfs object changes in the transaction between
1504 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1505 ** modified.
1506 **
1507 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1508 ** structure used by this VFS.  mxPathname is the maximum length of
1509 ** a pathname in this VFS.
1510 **
1511 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1512 ** the pNext pointer.  The [sqlite3_vfs_register()]
1513 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1514 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1515 ** searches the list.  Neither the application code nor the VFS
1516 ** implementation should use the pNext pointer.
1517 **
1518 ** The pNext field is the only field in the sqlite3_vfs
1519 ** structure that SQLite will ever modify.  SQLite will only access
1520 ** or modify this field while holding a particular static mutex.
1521 ** The application should never modify anything within the sqlite3_vfs
1522 ** object once the object has been registered.
1523 **
1524 ** The zName field holds the name of the VFS module.  The name must
1525 ** be unique across all VFS modules.
1526 **
1527 ** [[sqlite3_vfs.xOpen]]
1528 ** ^SQLite guarantees that the zFilename parameter to xOpen
1529 ** is either a NULL pointer or string obtained
1530 ** from xFullPathname() with an optional suffix added.
1531 ** ^If a suffix is added to the zFilename parameter, it will
1532 ** consist of a single "-" character followed by no more than
1533 ** 11 alphanumeric and/or "-" characters.
1534 ** ^SQLite further guarantees that
1535 ** the string will be valid and unchanged until xClose() is
1536 ** called. Because of the previous sentence,
1537 ** the [sqlite3_file] can safely store a pointer to the
1538 ** filename if it needs to remember the filename for some reason.
1539 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1540 ** must invent its own temporary name for the file.  ^Whenever the
1541 ** xFilename parameter is NULL it will also be the case that the
1542 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1543 **
1544 ** The flags argument to xOpen() includes all bits set in
1545 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1546 ** or [sqlite3_open16()] is used, then flags includes at least
1547 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1548 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1549 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1550 **
1551 ** ^(SQLite will also add one of the following flags to the xOpen()
1552 ** call, depending on the object being opened:
1553 **
1554 ** <ul>
1555 ** <li>  [SQLITE_OPEN_MAIN_DB]
1556 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1557 ** <li>  [SQLITE_OPEN_TEMP_DB]
1558 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1559 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1560 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1561 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1562 ** <li>  [SQLITE_OPEN_WAL]
1563 ** </ul>)^
1564 **
1565 ** The file I/O implementation can use the object type flags to
1566 ** change the way it deals with files.  For example, an application
1567 ** that does not care about crash recovery or rollback might make
1568 ** the open of a journal file a no-op.  Writes to this journal would
1569 ** also be no-ops, and any attempt to read the journal would return
1570 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1571 ** file will be doing page-aligned sector reads and writes in a random
1572 ** order and set up its I/O subsystem accordingly.
1573 **
1574 ** SQLite might also add one of the following flags to the xOpen method:
1575 **
1576 ** <ul>
1577 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1578 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1579 ** </ul>
1580 **
1581 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1582 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1583 ** will be set for TEMP databases and their journals, transient
1584 ** databases, and subjournals.
1585 **
1586 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1587 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1588 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1589 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1590 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1591 ** be created, and that it is an error if it already exists.
1592 ** It is <i>not</i> used to indicate the file should be opened
1593 ** for exclusive access.
1594 **
1595 ** ^At least szOsFile bytes of memory are allocated by SQLite
1596 ** to hold the  [sqlite3_file] structure passed as the third
1597 ** argument to xOpen.  The xOpen method does not have to
1598 ** allocate the structure; it should just fill it in.  Note that
1599 ** the xOpen method must set the sqlite3_file.pMethods to either
1600 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1601 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1602 ** element will be valid after xOpen returns regardless of the success
1603 ** or failure of the xOpen call.
1604 **
1605 ** [[sqlite3_vfs.xAccess]]
1606 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1607 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1608 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1609 ** to test whether a file is at least readable.   The file can be a
1610 ** directory.
1611 **
1612 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1613 ** output buffer xFullPathname.  The exact size of the output buffer
1614 ** is also passed as a parameter to both  methods. If the output buffer
1615 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1616 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1617 ** to prevent this by setting mxPathname to a sufficiently large value.
1618 **
1619 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1620 ** interfaces are not strictly a part of the filesystem, but they are
1621 ** included in the VFS structure for completeness.
1622 ** The xRandomness() function attempts to return nBytes bytes
1623 ** of good-quality randomness into zOut.  The return value is
1624 ** the actual number of bytes of randomness obtained.
1625 ** The xSleep() method causes the calling thread to sleep for at
1626 ** least the number of microseconds given.  ^The xCurrentTime()
1627 ** method returns a Julian Day Number for the current date and time as
1628 ** a floating point value.
1629 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1630 ** Day Number multiplied by 86400000 (the number of milliseconds in
1631 ** a 24-hour day).
1632 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1633 ** date and time if that method is available (if iVersion is 2 or
1634 ** greater and the function pointer is not NULL) and will fall back
1635 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1636 **
1637 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1638 ** are not used by the SQLite core.  These optional interfaces are provided
1639 ** by some VFSes to facilitate testing of the VFS code. By overriding
1640 ** system calls with functions under its control, a test program can
1641 ** simulate faults and error conditions that would otherwise be difficult
1642 ** or impossible to induce.  The set of system calls that can be overridden
1643 ** varies from one VFS to another, and from one version of the same VFS to the
1644 ** next.  Applications that use these interfaces must be prepared for any
1645 ** or all of these interfaces to be NULL or for their behavior to change
1646 ** from one release to the next.  Applications must not attempt to access
1647 ** any of these methods if the iVersion of the VFS is less than 3.
1648 */
1649 typedef struct sqlite3_vfs sqlite3_vfs;
1650 typedef void (*sqlite3_syscall_ptr)(void);
1651 struct sqlite3_vfs {
1652   int iVersion;            /* Structure version number (currently 3) */
1653   int szOsFile;            /* Size of subclassed sqlite3_file */
1654   int mxPathname;          /* Maximum file pathname length */
1655   sqlite3_vfs *pNext;      /* Next registered VFS */
1656   const char *zName;       /* Name of this virtual file system */
1657   void *pAppData;          /* Pointer to application-specific data */
1658   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1659                int flags, int *pOutFlags);
1660   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1661   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1662   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1663   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1664   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1665   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1666   void (*xDlClose)(sqlite3_vfs*, void*);
1667   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1668   int (*xSleep)(sqlite3_vfs*, int microseconds);
1669   int (*xCurrentTime)(sqlite3_vfs*, double*);
1670   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1671   /*
1672   ** The methods above are in version 1 of the sqlite_vfs object
1673   ** definition.  Those that follow are added in version 2 or later
1674   */
1675   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1676   /*
1677   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1678   ** Those below are for version 3 and greater.
1679   */
1680   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1681   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1682   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1683   /*
1684   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1685   ** New fields may be appended in figure versions.  The iVersion
1686   ** value will increment whenever this happens.
1687   */
1688 };
1689 
1690 /*
1691 ** CAPI3REF: Flags for the xAccess VFS method
1692 **
1693 ** These integer constants can be used as the third parameter to
1694 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1695 ** what kind of permissions the xAccess method is looking for.
1696 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1697 ** simply checks whether the file exists.
1698 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1699 ** checks whether the named directory is both readable and writable
1700 ** (in other words, if files can be added, removed, and renamed within
1701 ** the directory).
1702 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1703 ** [temp_store_directory pragma], though this could change in a future
1704 ** release of SQLite.
1705 ** With SQLITE_ACCESS_READ, the xAccess method
1706 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1707 ** currently unused, though it might be used in a future release of
1708 ** SQLite.
1709 */
1710 #define SQLITE_ACCESS_EXISTS    0
1711 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1712 #define SQLITE_ACCESS_READ      2   /* Unused */
1713 
1714 /*
1715 ** CAPI3REF: Flags for the xShmLock VFS method
1716 **
1717 ** These integer constants define the various locking operations
1718 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1719 ** following are the only legal combinations of flags to the
1720 ** xShmLock method:
1721 **
1722 ** <ul>
1723 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1724 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1725 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1726 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1727 ** </ul>
1728 **
1729 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1730 ** was given no the corresponding lock.
1731 **
1732 ** The xShmLock method can transition between unlocked and SHARED or
1733 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1734 ** and EXCLUSIVE.
1735 */
1736 #define SQLITE_SHM_UNLOCK       1
1737 #define SQLITE_SHM_LOCK         2
1738 #define SQLITE_SHM_SHARED       4
1739 #define SQLITE_SHM_EXCLUSIVE    8
1740 
1741 /*
1742 ** CAPI3REF: Maximum xShmLock index
1743 **
1744 ** The xShmLock method on [sqlite3_io_methods] may use values
1745 ** between 0 and this upper bound as its "offset" argument.
1746 ** The SQLite core will never attempt to acquire or release a
1747 ** lock outside of this range
1748 */
1749 #define SQLITE_SHM_NLOCK        8
1750 
1751 
1752 /*
1753 ** CAPI3REF: Initialize The SQLite Library
1754 **
1755 ** ^The sqlite3_initialize() routine initializes the
1756 ** SQLite library.  ^The sqlite3_shutdown() routine
1757 ** deallocates any resources that were allocated by sqlite3_initialize().
1758 ** These routines are designed to aid in process initialization and
1759 ** shutdown on embedded systems.  Workstation applications using
1760 ** SQLite normally do not need to invoke either of these routines.
1761 **
1762 ** A call to sqlite3_initialize() is an "effective" call if it is
1763 ** the first time sqlite3_initialize() is invoked during the lifetime of
1764 ** the process, or if it is the first time sqlite3_initialize() is invoked
1765 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1766 ** of sqlite3_initialize() does any initialization.  All other calls
1767 ** are harmless no-ops.)^
1768 **
1769 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1770 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1771 ** an effective call to sqlite3_shutdown() does any deinitialization.
1772 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1773 **
1774 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1775 ** is not.  The sqlite3_shutdown() interface must only be called from a
1776 ** single thread.  All open [database connections] must be closed and all
1777 ** other SQLite resources must be deallocated prior to invoking
1778 ** sqlite3_shutdown().
1779 **
1780 ** Among other things, ^sqlite3_initialize() will invoke
1781 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1782 ** will invoke sqlite3_os_end().
1783 **
1784 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1785 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1786 ** the library (perhaps it is unable to allocate a needed resource such
1787 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1788 **
1789 ** ^The sqlite3_initialize() routine is called internally by many other
1790 ** SQLite interfaces so that an application usually does not need to
1791 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1792 ** calls sqlite3_initialize() so the SQLite library will be automatically
1793 ** initialized when [sqlite3_open()] is called if it has not be initialized
1794 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1795 ** compile-time option, then the automatic calls to sqlite3_initialize()
1796 ** are omitted and the application must call sqlite3_initialize() directly
1797 ** prior to using any other SQLite interface.  For maximum portability,
1798 ** it is recommended that applications always invoke sqlite3_initialize()
1799 ** directly prior to using any other SQLite interface.  Future releases
1800 ** of SQLite may require this.  In other words, the behavior exhibited
1801 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1802 ** default behavior in some future release of SQLite.
1803 **
1804 ** The sqlite3_os_init() routine does operating-system specific
1805 ** initialization of the SQLite library.  The sqlite3_os_end()
1806 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1807 ** performed by these routines include allocation or deallocation
1808 ** of static resources, initialization of global variables,
1809 ** setting up a default [sqlite3_vfs] module, or setting up
1810 ** a default configuration using [sqlite3_config()].
1811 **
1812 ** The application should never invoke either sqlite3_os_init()
1813 ** or sqlite3_os_end() directly.  The application should only invoke
1814 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1815 ** interface is called automatically by sqlite3_initialize() and
1816 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1817 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1818 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1819 ** When [custom builds | built for other platforms]
1820 ** (using the [SQLITE_OS_OTHER=1] compile-time
1821 ** option) the application must supply a suitable implementation for
1822 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1823 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1824 ** must return [SQLITE_OK] on success and some other [error code] upon
1825 ** failure.
1826 */
1827 SQLITE_API int sqlite3_initialize(void);
1828 SQLITE_API int sqlite3_shutdown(void);
1829 SQLITE_API int sqlite3_os_init(void);
1830 SQLITE_API int sqlite3_os_end(void);
1831 
1832 /*
1833 ** CAPI3REF: Configuring The SQLite Library
1834 **
1835 ** The sqlite3_config() interface is used to make global configuration
1836 ** changes to SQLite in order to tune SQLite to the specific needs of
1837 ** the application.  The default configuration is recommended for most
1838 ** applications and so this routine is usually not necessary.  It is
1839 ** provided to support rare applications with unusual needs.
1840 **
1841 ** The sqlite3_config() interface is not threadsafe.  The application
1842 ** must insure that no other SQLite interfaces are invoked by other
1843 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1844 ** may only be invoked prior to library initialization using
1845 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1846 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1847 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1848 ** Note, however, that ^sqlite3_config() can be called as part of the
1849 ** implementation of an application-defined [sqlite3_os_init()].
1850 **
1851 ** The first argument to sqlite3_config() is an integer
1852 ** [configuration option] that determines
1853 ** what property of SQLite is to be configured.  Subsequent arguments
1854 ** vary depending on the [configuration option]
1855 ** in the first argument.
1856 **
1857 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1858 ** ^If the option is unknown or SQLite is unable to set the option
1859 ** then this routine returns a non-zero [error code].
1860 */
1861 SQLITE_API int sqlite3_config(int, ...);
1862 
1863 /*
1864 ** CAPI3REF: Configure database connections
1865 **
1866 ** The sqlite3_db_config() interface is used to make configuration
1867 ** changes to a [database connection].  The interface is similar to
1868 ** [sqlite3_config()] except that the changes apply to a single
1869 ** [database connection] (specified in the first argument).
1870 **
1871 ** The second argument to sqlite3_db_config(D,V,...)  is the
1872 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1873 ** that indicates what aspect of the [database connection] is being configured.
1874 ** Subsequent arguments vary depending on the configuration verb.
1875 **
1876 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1877 ** the call is considered successful.
1878 */
1879 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1880 
1881 /*
1882 ** CAPI3REF: Memory Allocation Routines
1883 **
1884 ** An instance of this object defines the interface between SQLite
1885 ** and low-level memory allocation routines.
1886 **
1887 ** This object is used in only one place in the SQLite interface.
1888 ** A pointer to an instance of this object is the argument to
1889 ** [sqlite3_config()] when the configuration option is
1890 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1891 ** By creating an instance of this object
1892 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1893 ** during configuration, an application can specify an alternative
1894 ** memory allocation subsystem for SQLite to use for all of its
1895 ** dynamic memory needs.
1896 **
1897 ** Note that SQLite comes with several [built-in memory allocators]
1898 ** that are perfectly adequate for the overwhelming majority of applications
1899 ** and that this object is only useful to a tiny minority of applications
1900 ** with specialized memory allocation requirements.  This object is
1901 ** also used during testing of SQLite in order to specify an alternative
1902 ** memory allocator that simulates memory out-of-memory conditions in
1903 ** order to verify that SQLite recovers gracefully from such
1904 ** conditions.
1905 **
1906 ** The xMalloc, xRealloc, and xFree methods must work like the
1907 ** malloc(), realloc() and free() functions from the standard C library.
1908 ** ^SQLite guarantees that the second argument to
1909 ** xRealloc is always a value returned by a prior call to xRoundup.
1910 **
1911 ** xSize should return the allocated size of a memory allocation
1912 ** previously obtained from xMalloc or xRealloc.  The allocated size
1913 ** is always at least as big as the requested size but may be larger.
1914 **
1915 ** The xRoundup method returns what would be the allocated size of
1916 ** a memory allocation given a particular requested size.  Most memory
1917 ** allocators round up memory allocations at least to the next multiple
1918 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1919 ** Every memory allocation request coming in through [sqlite3_malloc()]
1920 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1921 ** that causes the corresponding memory allocation to fail.
1922 **
1923 ** The xInit method initializes the memory allocator.  (For example,
1924 ** it might allocate any require mutexes or initialize internal data
1925 ** structures.  The xShutdown method is invoked (indirectly) by
1926 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1927 ** by xInit.  The pAppData pointer is used as the only parameter to
1928 ** xInit and xShutdown.
1929 **
1930 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1931 ** the xInit method, so the xInit method need not be threadsafe.  The
1932 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1933 ** not need to be threadsafe either.  For all other methods, SQLite
1934 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1935 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1936 ** it is by default) and so the methods are automatically serialized.
1937 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1938 ** methods must be threadsafe or else make their own arrangements for
1939 ** serialization.
1940 **
1941 ** SQLite will never invoke xInit() more than once without an intervening
1942 ** call to xShutdown().
1943 */
1944 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1945 struct sqlite3_mem_methods {
1946   void *(*xMalloc)(int);         /* Memory allocation function */
1947   void (*xFree)(void*);          /* Free a prior allocation */
1948   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1949   int (*xSize)(void*);           /* Return the size of an allocation */
1950   int (*xRoundup)(int);          /* Round up request size to allocation size */
1951   int (*xInit)(void*);           /* Initialize the memory allocator */
1952   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1953   void *pAppData;                /* Argument to xInit() and xShutdown() */
1954 };
1955 
1956 /*
1957 ** CAPI3REF: Configuration Options
1958 ** KEYWORDS: {configuration option}
1959 **
1960 ** These constants are the available integer configuration options that
1961 ** can be passed as the first argument to the [sqlite3_config()] interface.
1962 **
1963 ** New configuration options may be added in future releases of SQLite.
1964 ** Existing configuration options might be discontinued.  Applications
1965 ** should check the return code from [sqlite3_config()] to make sure that
1966 ** the call worked.  The [sqlite3_config()] interface will return a
1967 ** non-zero [error code] if a discontinued or unsupported configuration option
1968 ** is invoked.
1969 **
1970 ** <dl>
1971 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1972 ** <dd>There are no arguments to this option.  ^This option sets the
1973 ** [threading mode] to Single-thread.  In other words, it disables
1974 ** all mutexing and puts SQLite into a mode where it can only be used
1975 ** by a single thread.   ^If SQLite is compiled with
1976 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1977 ** it is not possible to change the [threading mode] from its default
1978 ** value of Single-thread and so [sqlite3_config()] will return
1979 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1980 ** configuration option.</dd>
1981 **
1982 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1983 ** <dd>There are no arguments to this option.  ^This option sets the
1984 ** [threading mode] to Multi-thread.  In other words, it disables
1985 ** mutexing on [database connection] and [prepared statement] objects.
1986 ** The application is responsible for serializing access to
1987 ** [database connections] and [prepared statements].  But other mutexes
1988 ** are enabled so that SQLite will be safe to use in a multi-threaded
1989 ** environment as long as no two threads attempt to use the same
1990 ** [database connection] at the same time.  ^If SQLite is compiled with
1991 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1992 ** it is not possible to set the Multi-thread [threading mode] and
1993 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1994 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1995 **
1996 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1997 ** <dd>There are no arguments to this option.  ^This option sets the
1998 ** [threading mode] to Serialized. In other words, this option enables
1999 ** all mutexes including the recursive
2000 ** mutexes on [database connection] and [prepared statement] objects.
2001 ** In this mode (which is the default when SQLite is compiled with
2002 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2003 ** to [database connections] and [prepared statements] so that the
2004 ** application is free to use the same [database connection] or the
2005 ** same [prepared statement] in different threads at the same time.
2006 ** ^If SQLite is compiled with
2007 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2008 ** it is not possible to set the Serialized [threading mode] and
2009 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2010 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2011 **
2012 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2013 ** <dd> ^(This option takes a single argument which is a pointer to an
2014 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
2015 ** alternative low-level memory allocation routines to be used in place of
2016 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
2017 ** its own private copy of the content of the [sqlite3_mem_methods] structure
2018 ** before the [sqlite3_config()] call returns.</dd>
2019 **
2020 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2021 ** <dd> ^(This option takes a single argument which is a pointer to an
2022 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
2023 ** structure is filled with the currently defined memory allocation routines.)^
2024 ** This option can be used to overload the default memory allocation
2025 ** routines with a wrapper that simulations memory allocation failure or
2026 ** tracks memory usage, for example. </dd>
2027 **
2028 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2029 ** <dd> ^This option takes single argument of type int, interpreted as a
2030 ** boolean, which enables or disables the collection of memory allocation
2031 ** statistics. ^(When memory allocation statistics are disabled, the
2032 ** following SQLite interfaces become non-operational:
2033 **   <ul>
2034 **   <li> [sqlite3_memory_used()]
2035 **   <li> [sqlite3_memory_highwater()]
2036 **   <li> [sqlite3_soft_heap_limit64()]
2037 **   <li> [sqlite3_status()]
2038 **   </ul>)^
2039 ** ^Memory allocation statistics are enabled by default unless SQLite is
2040 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2041 ** allocation statistics are disabled by default.
2042 ** </dd>
2043 **
2044 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2045 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2046 ** scratch memory.  There are three arguments:  A pointer an 8-byte
2047 ** aligned memory buffer from which the scratch allocations will be
2048 ** drawn, the size of each scratch allocation (sz),
2049 ** and the maximum number of scratch allocations (N).  The sz
2050 ** argument must be a multiple of 16.
2051 ** The first argument must be a pointer to an 8-byte aligned buffer
2052 ** of at least sz*N bytes of memory.
2053 ** ^SQLite will use no more than two scratch buffers per thread.  So
2054 ** N should be set to twice the expected maximum number of threads.
2055 ** ^SQLite will never require a scratch buffer that is more than 6
2056 ** times the database page size. ^If SQLite needs needs additional
2057 ** scratch memory beyond what is provided by this configuration option, then
2058 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2059 **
2060 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2061 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2062 ** the database page cache with the default page cache implementation.
2063 ** This configuration should not be used if an application-define page
2064 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2065 ** There are three arguments to this option: A pointer to 8-byte aligned
2066 ** memory, the size of each page buffer (sz), and the number of pages (N).
2067 ** The sz argument should be the size of the largest database page
2068 ** (a power of two between 512 and 32768) plus a little extra for each
2069 ** page header.  ^The page header size is 20 to 40 bytes depending on
2070 ** the host architecture.  ^It is harmless, apart from the wasted memory,
2071 ** to make sz a little too large.  The first
2072 ** argument should point to an allocation of at least sz*N bytes of memory.
2073 ** ^SQLite will use the memory provided by the first argument to satisfy its
2074 ** memory needs for the first N pages that it adds to cache.  ^If additional
2075 ** page cache memory is needed beyond what is provided by this option, then
2076 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2077 ** The pointer in the first argument must
2078 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2079 ** will be undefined.</dd>
2080 **
2081 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2082 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2083 ** for all of its dynamic memory allocation needs beyond those provided
2084 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2085 ** There are three arguments: An 8-byte aligned pointer to the memory,
2086 ** the number of bytes in the memory buffer, and the minimum allocation size.
2087 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2088 ** to using its default memory allocator (the system malloc() implementation),
2089 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2090 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2091 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2092 ** allocator is engaged to handle all of SQLites memory allocation needs.
2093 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2094 ** boundary or subsequent behavior of SQLite will be undefined.
2095 ** The minimum allocation size is capped at 2**12. Reasonable values
2096 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2097 **
2098 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2099 ** <dd> ^(This option takes a single argument which is a pointer to an
2100 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2101 ** alternative low-level mutex routines to be used in place
2102 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2103 ** content of the [sqlite3_mutex_methods] structure before the call to
2104 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2105 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2106 ** the entire mutexing subsystem is omitted from the build and hence calls to
2107 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2108 ** return [SQLITE_ERROR].</dd>
2109 **
2110 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2111 ** <dd> ^(This option takes a single argument which is a pointer to an
2112 ** instance of the [sqlite3_mutex_methods] structure.  The
2113 ** [sqlite3_mutex_methods]
2114 ** structure is filled with the currently defined mutex routines.)^
2115 ** This option can be used to overload the default mutex allocation
2116 ** routines with a wrapper used to track mutex usage for performance
2117 ** profiling or testing, for example.   ^If SQLite is compiled with
2118 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2119 ** the entire mutexing subsystem is omitted from the build and hence calls to
2120 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2121 ** return [SQLITE_ERROR].</dd>
2122 **
2123 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2124 ** <dd> ^(This option takes two arguments that determine the default
2125 ** memory allocation for the lookaside memory allocator on each
2126 ** [database connection].  The first argument is the
2127 ** size of each lookaside buffer slot and the second is the number of
2128 ** slots allocated to each database connection.)^  ^(This option sets the
2129 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2130 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2131 ** configuration on individual connections.)^ </dd>
2132 **
2133 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2134 ** <dd> ^(This option takes a single argument which is a pointer to
2135 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2136 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2137 ** object and uses it for page cache memory allocations.</dd>
2138 **
2139 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2140 ** <dd> ^(This option takes a single argument which is a pointer to an
2141 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2142 ** page cache implementation into that object.)^ </dd>
2143 **
2144 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2145 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2146 ** function with a call signature of void(*)(void*,int,const char*),
2147 ** and a pointer to void. ^If the function pointer is not NULL, it is
2148 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2149 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2150 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2151 ** passed through as the first parameter to the application-defined logger
2152 ** function whenever that function is invoked.  ^The second parameter to
2153 ** the logger function is a copy of the first parameter to the corresponding
2154 ** [sqlite3_log()] call and is intended to be a [result code] or an
2155 ** [extended result code].  ^The third parameter passed to the logger is
2156 ** log message after formatting via [sqlite3_snprintf()].
2157 ** The SQLite logging interface is not reentrant; the logger function
2158 ** supplied by the application must not invoke any SQLite interface.
2159 ** In a multi-threaded application, the application-defined logger
2160 ** function must be threadsafe. </dd>
2161 **
2162 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2163 ** <dd> This option takes a single argument of type int. If non-zero, then
2164 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2165 ** is globally disabled. If URI handling is globally enabled, all filenames
2166 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2167 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2168 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2169 ** connection is opened. If it is globally disabled, filenames are
2170 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2171 ** database connection is opened. By default, URI handling is globally
2172 ** disabled. The default value may be changed by compiling with the
2173 ** [SQLITE_USE_URI] symbol defined.
2174 **
2175 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2176 ** <dd> This option takes a single integer argument which is interpreted as
2177 ** a boolean in order to enable or disable the use of covering indices for
2178 ** full table scans in the query optimizer.  The default setting is determined
2179 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2180 ** if that compile-time option is omitted.
2181 ** The ability to disable the use of covering indices for full table scans
2182 ** is because some incorrectly coded legacy applications might malfunction
2183 ** malfunction when the optimization is enabled.  Providing the ability to
2184 ** disable the optimization allows the older, buggy application code to work
2185 ** without change even with newer versions of SQLite.
2186 **
2187 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2188 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2189 ** <dd> These options are obsolete and should not be used by new code.
2190 ** They are retained for backwards compatibility but are now no-ops.
2191 ** </dl>
2192 **
2193 ** [[SQLITE_CONFIG_SQLLOG]]
2194 ** <dt>SQLITE_CONFIG_SQLLOG
2195 ** <dd>This option is only available if sqlite is compiled with the
2196 ** SQLITE_ENABLE_SQLLOG pre-processor macro defined. The first argument should
2197 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2198 ** The second should be of type (void*). The callback is invoked by the library
2199 ** in three separate circumstances, identified by the value passed as the
2200 ** fourth parameter. If the fourth parameter is 0, then the database connection
2201 ** passed as the second argument has just been opened. The third argument
2202 ** points to a buffer containing the name of the main database file. If the
2203 ** fourth parameter is 1, then the SQL statement that the third parameter
2204 ** points to has just been executed. Or, if the fourth parameter is 2, then
2205 ** the connection being passed as the second parameter is being closed. The
2206 ** third parameter is passed NULL In this case.
2207 ** </dl>
2208 */
2209 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2210 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2211 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2212 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2213 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2214 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2215 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2216 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2217 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2218 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2219 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2220 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2221 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2222 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2223 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2224 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2225 #define SQLITE_CONFIG_URI          17  /* int */
2226 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2227 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2228 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2229 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2230 
2231 /*
2232 ** CAPI3REF: Database Connection Configuration Options
2233 **
2234 ** These constants are the available integer configuration options that
2235 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2236 **
2237 ** New configuration options may be added in future releases of SQLite.
2238 ** Existing configuration options might be discontinued.  Applications
2239 ** should check the return code from [sqlite3_db_config()] to make sure that
2240 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2241 ** non-zero [error code] if a discontinued or unsupported configuration option
2242 ** is invoked.
2243 **
2244 ** <dl>
2245 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2246 ** <dd> ^This option takes three additional arguments that determine the
2247 ** [lookaside memory allocator] configuration for the [database connection].
2248 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2249 ** pointer to a memory buffer to use for lookaside memory.
2250 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2251 ** may be NULL in which case SQLite will allocate the
2252 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2253 ** size of each lookaside buffer slot.  ^The third argument is the number of
2254 ** slots.  The size of the buffer in the first argument must be greater than
2255 ** or equal to the product of the second and third arguments.  The buffer
2256 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2257 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2258 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2259 ** configuration for a database connection can only be changed when that
2260 ** connection is not currently using lookaside memory, or in other words
2261 ** when the "current value" returned by
2262 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2263 ** Any attempt to change the lookaside memory configuration when lookaside
2264 ** memory is in use leaves the configuration unchanged and returns
2265 ** [SQLITE_BUSY].)^</dd>
2266 **
2267 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2268 ** <dd> ^This option is used to enable or disable the enforcement of
2269 ** [foreign key constraints].  There should be two additional arguments.
2270 ** The first argument is an integer which is 0 to disable FK enforcement,
2271 ** positive to enable FK enforcement or negative to leave FK enforcement
2272 ** unchanged.  The second parameter is a pointer to an integer into which
2273 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2274 ** following this call.  The second parameter may be a NULL pointer, in
2275 ** which case the FK enforcement setting is not reported back. </dd>
2276 **
2277 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2278 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2279 ** There should be two additional arguments.
2280 ** The first argument is an integer which is 0 to disable triggers,
2281 ** positive to enable triggers or negative to leave the setting unchanged.
2282 ** The second parameter is a pointer to an integer into which
2283 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2284 ** following this call.  The second parameter may be a NULL pointer, in
2285 ** which case the trigger setting is not reported back. </dd>
2286 **
2287 ** </dl>
2288 */
2289 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2290 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2291 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2292 
2293 
2294 /*
2295 ** CAPI3REF: Enable Or Disable Extended Result Codes
2296 **
2297 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2298 ** [extended result codes] feature of SQLite. ^The extended result
2299 ** codes are disabled by default for historical compatibility.
2300 */
2301 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2302 
2303 /*
2304 ** CAPI3REF: Last Insert Rowid
2305 **
2306 ** ^Each entry in an SQLite table has a unique 64-bit signed
2307 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2308 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2309 ** names are not also used by explicitly declared columns. ^If
2310 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2311 ** is another alias for the rowid.
2312 **
2313 ** ^This routine returns the [rowid] of the most recent
2314 ** successful [INSERT] into the database from the [database connection]
2315 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2316 ** records the last insert rowid of both ordinary tables and [virtual tables].
2317 ** ^If no successful [INSERT]s
2318 ** have ever occurred on that database connection, zero is returned.
2319 **
2320 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2321 ** method, then this routine will return the [rowid] of the inserted
2322 ** row as long as the trigger or virtual table method is running.
2323 ** But once the trigger or virtual table method ends, the value returned
2324 ** by this routine reverts to what it was before the trigger or virtual
2325 ** table method began.)^
2326 **
2327 ** ^An [INSERT] that fails due to a constraint violation is not a
2328 ** successful [INSERT] and does not change the value returned by this
2329 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2330 ** and INSERT OR ABORT make no changes to the return value of this
2331 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2332 ** encounters a constraint violation, it does not fail.  The
2333 ** INSERT continues to completion after deleting rows that caused
2334 ** the constraint problem so INSERT OR REPLACE will always change
2335 ** the return value of this interface.)^
2336 **
2337 ** ^For the purposes of this routine, an [INSERT] is considered to
2338 ** be successful even if it is subsequently rolled back.
2339 **
2340 ** This function is accessible to SQL statements via the
2341 ** [last_insert_rowid() SQL function].
2342 **
2343 ** If a separate thread performs a new [INSERT] on the same
2344 ** database connection while the [sqlite3_last_insert_rowid()]
2345 ** function is running and thus changes the last insert [rowid],
2346 ** then the value returned by [sqlite3_last_insert_rowid()] is
2347 ** unpredictable and might not equal either the old or the new
2348 ** last insert [rowid].
2349 */
2350 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2351 
2352 /*
2353 ** CAPI3REF: Count The Number Of Rows Modified
2354 **
2355 ** ^This function returns the number of database rows that were changed
2356 ** or inserted or deleted by the most recently completed SQL statement
2357 ** on the [database connection] specified by the first parameter.
2358 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2359 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2360 ** triggers or [foreign key actions] are not counted.)^ Use the
2361 ** [sqlite3_total_changes()] function to find the total number of changes
2362 ** including changes caused by triggers and foreign key actions.
2363 **
2364 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2365 ** are not counted.  Only real table changes are counted.
2366 **
2367 ** ^(A "row change" is a change to a single row of a single table
2368 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2369 ** are changed as side effects of [REPLACE] constraint resolution,
2370 ** rollback, ABORT processing, [DROP TABLE], or by any other
2371 ** mechanisms do not count as direct row changes.)^
2372 **
2373 ** A "trigger context" is a scope of execution that begins and
2374 ** ends with the script of a [CREATE TRIGGER | trigger].
2375 ** Most SQL statements are
2376 ** evaluated outside of any trigger.  This is the "top level"
2377 ** trigger context.  If a trigger fires from the top level, a
2378 ** new trigger context is entered for the duration of that one
2379 ** trigger.  Subtriggers create subcontexts for their duration.
2380 **
2381 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2382 ** not create a new trigger context.
2383 **
2384 ** ^This function returns the number of direct row changes in the
2385 ** most recent INSERT, UPDATE, or DELETE statement within the same
2386 ** trigger context.
2387 **
2388 ** ^Thus, when called from the top level, this function returns the
2389 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2390 ** that also occurred at the top level.  ^(Within the body of a trigger,
2391 ** the sqlite3_changes() interface can be called to find the number of
2392 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2393 ** statement within the body of the same trigger.
2394 ** However, the number returned does not include changes
2395 ** caused by subtriggers since those have their own context.)^
2396 **
2397 ** See also the [sqlite3_total_changes()] interface, the
2398 ** [count_changes pragma], and the [changes() SQL function].
2399 **
2400 ** If a separate thread makes changes on the same database connection
2401 ** while [sqlite3_changes()] is running then the value returned
2402 ** is unpredictable and not meaningful.
2403 */
2404 SQLITE_API int sqlite3_changes(sqlite3*);
2405 
2406 /*
2407 ** CAPI3REF: Total Number Of Rows Modified
2408 **
2409 ** ^This function returns the number of row changes caused by [INSERT],
2410 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2411 ** ^(The count returned by sqlite3_total_changes() includes all changes
2412 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2413 ** [foreign key actions]. However,
2414 ** the count does not include changes used to implement [REPLACE] constraints,
2415 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2416 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2417 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2418 ** are counted.)^
2419 ** ^The sqlite3_total_changes() function counts the changes as soon as
2420 ** the statement that makes them is completed (when the statement handle
2421 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2422 **
2423 ** See also the [sqlite3_changes()] interface, the
2424 ** [count_changes pragma], and the [total_changes() SQL function].
2425 **
2426 ** If a separate thread makes changes on the same database connection
2427 ** while [sqlite3_total_changes()] is running then the value
2428 ** returned is unpredictable and not meaningful.
2429 */
2430 SQLITE_API int sqlite3_total_changes(sqlite3*);
2431 
2432 /*
2433 ** CAPI3REF: Interrupt A Long-Running Query
2434 **
2435 ** ^This function causes any pending database operation to abort and
2436 ** return at its earliest opportunity. This routine is typically
2437 ** called in response to a user action such as pressing "Cancel"
2438 ** or Ctrl-C where the user wants a long query operation to halt
2439 ** immediately.
2440 **
2441 ** ^It is safe to call this routine from a thread different from the
2442 ** thread that is currently running the database operation.  But it
2443 ** is not safe to call this routine with a [database connection] that
2444 ** is closed or might close before sqlite3_interrupt() returns.
2445 **
2446 ** ^If an SQL operation is very nearly finished at the time when
2447 ** sqlite3_interrupt() is called, then it might not have an opportunity
2448 ** to be interrupted and might continue to completion.
2449 **
2450 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2451 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2452 ** that is inside an explicit transaction, then the entire transaction
2453 ** will be rolled back automatically.
2454 **
2455 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2456 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2457 ** that are started after the sqlite3_interrupt() call and before the
2458 ** running statements reaches zero are interrupted as if they had been
2459 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2460 ** that are started after the running statement count reaches zero are
2461 ** not effected by the sqlite3_interrupt().
2462 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2463 ** SQL statements is a no-op and has no effect on SQL statements
2464 ** that are started after the sqlite3_interrupt() call returns.
2465 **
2466 ** If the database connection closes while [sqlite3_interrupt()]
2467 ** is running then bad things will likely happen.
2468 */
2469 SQLITE_API void sqlite3_interrupt(sqlite3*);
2470 
2471 /*
2472 ** CAPI3REF: Determine If An SQL Statement Is Complete
2473 **
2474 ** These routines are useful during command-line input to determine if the
2475 ** currently entered text seems to form a complete SQL statement or
2476 ** if additional input is needed before sending the text into
2477 ** SQLite for parsing.  ^These routines return 1 if the input string
2478 ** appears to be a complete SQL statement.  ^A statement is judged to be
2479 ** complete if it ends with a semicolon token and is not a prefix of a
2480 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2481 ** string literals or quoted identifier names or comments are not
2482 ** independent tokens (they are part of the token in which they are
2483 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2484 ** and comments that follow the final semicolon are ignored.
2485 **
2486 ** ^These routines return 0 if the statement is incomplete.  ^If a
2487 ** memory allocation fails, then SQLITE_NOMEM is returned.
2488 **
2489 ** ^These routines do not parse the SQL statements thus
2490 ** will not detect syntactically incorrect SQL.
2491 **
2492 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2493 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2494 ** automatically by sqlite3_complete16().  If that initialization fails,
2495 ** then the return value from sqlite3_complete16() will be non-zero
2496 ** regardless of whether or not the input SQL is complete.)^
2497 **
2498 ** The input to [sqlite3_complete()] must be a zero-terminated
2499 ** UTF-8 string.
2500 **
2501 ** The input to [sqlite3_complete16()] must be a zero-terminated
2502 ** UTF-16 string in native byte order.
2503 */
2504 SQLITE_API int sqlite3_complete(const char *sql);
2505 SQLITE_API int sqlite3_complete16(const void *sql);
2506 
2507 /*
2508 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2509 **
2510 ** ^This routine sets a callback function that might be invoked whenever
2511 ** an attempt is made to open a database table that another thread
2512 ** or process has locked.
2513 **
2514 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2515 ** is returned immediately upon encountering the lock.  ^If the busy callback
2516 ** is not NULL, then the callback might be invoked with two arguments.
2517 **
2518 ** ^The first argument to the busy handler is a copy of the void* pointer which
2519 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2520 ** the busy handler callback is the number of times that the busy handler has
2521 ** been invoked for this locking event.  ^If the
2522 ** busy callback returns 0, then no additional attempts are made to
2523 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2524 ** ^If the callback returns non-zero, then another attempt
2525 ** is made to open the database for reading and the cycle repeats.
2526 **
2527 ** The presence of a busy handler does not guarantee that it will be invoked
2528 ** when there is lock contention. ^If SQLite determines that invoking the busy
2529 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2530 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2531 ** Consider a scenario where one process is holding a read lock that
2532 ** it is trying to promote to a reserved lock and
2533 ** a second process is holding a reserved lock that it is trying
2534 ** to promote to an exclusive lock.  The first process cannot proceed
2535 ** because it is blocked by the second and the second process cannot
2536 ** proceed because it is blocked by the first.  If both processes
2537 ** invoke the busy handlers, neither will make any progress.  Therefore,
2538 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2539 ** will induce the first process to release its read lock and allow
2540 ** the second process to proceed.
2541 **
2542 ** ^The default busy callback is NULL.
2543 **
2544 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2545 ** when SQLite is in the middle of a large transaction where all the
2546 ** changes will not fit into the in-memory cache.  SQLite will
2547 ** already hold a RESERVED lock on the database file, but it needs
2548 ** to promote this lock to EXCLUSIVE so that it can spill cache
2549 ** pages into the database file without harm to concurrent
2550 ** readers.  ^If it is unable to promote the lock, then the in-memory
2551 ** cache will be left in an inconsistent state and so the error
2552 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2553 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2554 ** forces an automatic rollback of the changes.  See the
2555 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2556 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2557 ** this is important.
2558 **
2559 ** ^(There can only be a single busy handler defined for each
2560 ** [database connection].  Setting a new busy handler clears any
2561 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2562 ** will also set or clear the busy handler.
2563 **
2564 ** The busy callback should not take any actions which modify the
2565 ** database connection that invoked the busy handler.  Any such actions
2566 ** result in undefined behavior.
2567 **
2568 ** A busy handler must not close the database connection
2569 ** or [prepared statement] that invoked the busy handler.
2570 */
2571 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2572 
2573 /*
2574 ** CAPI3REF: Set A Busy Timeout
2575 **
2576 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2577 ** for a specified amount of time when a table is locked.  ^The handler
2578 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2579 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2580 ** the handler returns 0 which causes [sqlite3_step()] to return
2581 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2582 **
2583 ** ^Calling this routine with an argument less than or equal to zero
2584 ** turns off all busy handlers.
2585 **
2586 ** ^(There can only be a single busy handler for a particular
2587 ** [database connection] any any given moment.  If another busy handler
2588 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2589 ** this routine, that other busy handler is cleared.)^
2590 */
2591 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2592 
2593 /*
2594 ** CAPI3REF: Convenience Routines For Running Queries
2595 **
2596 ** This is a legacy interface that is preserved for backwards compatibility.
2597 ** Use of this interface is not recommended.
2598 **
2599 ** Definition: A <b>result table</b> is memory data structure created by the
2600 ** [sqlite3_get_table()] interface.  A result table records the
2601 ** complete query results from one or more queries.
2602 **
2603 ** The table conceptually has a number of rows and columns.  But
2604 ** these numbers are not part of the result table itself.  These
2605 ** numbers are obtained separately.  Let N be the number of rows
2606 ** and M be the number of columns.
2607 **
2608 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2609 ** There are (N+1)*M elements in the array.  The first M pointers point
2610 ** to zero-terminated strings that  contain the names of the columns.
2611 ** The remaining entries all point to query results.  NULL values result
2612 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2613 ** string representation as returned by [sqlite3_column_text()].
2614 **
2615 ** A result table might consist of one or more memory allocations.
2616 ** It is not safe to pass a result table directly to [sqlite3_free()].
2617 ** A result table should be deallocated using [sqlite3_free_table()].
2618 **
2619 ** ^(As an example of the result table format, suppose a query result
2620 ** is as follows:
2621 **
2622 ** <blockquote><pre>
2623 **        Name        | Age
2624 **        -----------------------
2625 **        Alice       | 43
2626 **        Bob         | 28
2627 **        Cindy       | 21
2628 ** </pre></blockquote>
2629 **
2630 ** There are two column (M==2) and three rows (N==3).  Thus the
2631 ** result table has 8 entries.  Suppose the result table is stored
2632 ** in an array names azResult.  Then azResult holds this content:
2633 **
2634 ** <blockquote><pre>
2635 **        azResult[0] = "Name";
2636 **        azResult[1] = "Age";
2637 **        azResult[2] = "Alice";
2638 **        azResult[3] = "43";
2639 **        azResult[4] = "Bob";
2640 **        azResult[5] = "28";
2641 **        azResult[6] = "Cindy";
2642 **        azResult[7] = "21";
2643 ** </pre></blockquote>)^
2644 **
2645 ** ^The sqlite3_get_table() function evaluates one or more
2646 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2647 ** string of its 2nd parameter and returns a result table to the
2648 ** pointer given in its 3rd parameter.
2649 **
2650 ** After the application has finished with the result from sqlite3_get_table(),
2651 ** it must pass the result table pointer to sqlite3_free_table() in order to
2652 ** release the memory that was malloced.  Because of the way the
2653 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2654 ** function must not try to call [sqlite3_free()] directly.  Only
2655 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2656 **
2657 ** The sqlite3_get_table() interface is implemented as a wrapper around
2658 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2659 ** to any internal data structures of SQLite.  It uses only the public
2660 ** interface defined here.  As a consequence, errors that occur in the
2661 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2662 ** reflected in subsequent calls to [sqlite3_errcode()] or
2663 ** [sqlite3_errmsg()].
2664 */
2665 SQLITE_API int sqlite3_get_table(
2666   sqlite3 *db,          /* An open database */
2667   const char *zSql,     /* SQL to be evaluated */
2668   char ***pazResult,    /* Results of the query */
2669   int *pnRow,           /* Number of result rows written here */
2670   int *pnColumn,        /* Number of result columns written here */
2671   char **pzErrmsg       /* Error msg written here */
2672 );
2673 SQLITE_API void sqlite3_free_table(char **result);
2674 
2675 /*
2676 ** CAPI3REF: Formatted String Printing Functions
2677 **
2678 ** These routines are work-alikes of the "printf()" family of functions
2679 ** from the standard C library.
2680 **
2681 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2682 ** results into memory obtained from [sqlite3_malloc()].
2683 ** The strings returned by these two routines should be
2684 ** released by [sqlite3_free()].  ^Both routines return a
2685 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2686 ** memory to hold the resulting string.
2687 **
2688 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2689 ** the standard C library.  The result is written into the
2690 ** buffer supplied as the second parameter whose size is given by
2691 ** the first parameter. Note that the order of the
2692 ** first two parameters is reversed from snprintf().)^  This is an
2693 ** historical accident that cannot be fixed without breaking
2694 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2695 ** returns a pointer to its buffer instead of the number of
2696 ** characters actually written into the buffer.)^  We admit that
2697 ** the number of characters written would be a more useful return
2698 ** value but we cannot change the implementation of sqlite3_snprintf()
2699 ** now without breaking compatibility.
2700 **
2701 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2702 ** guarantees that the buffer is always zero-terminated.  ^The first
2703 ** parameter "n" is the total size of the buffer, including space for
2704 ** the zero terminator.  So the longest string that can be completely
2705 ** written will be n-1 characters.
2706 **
2707 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2708 **
2709 ** These routines all implement some additional formatting
2710 ** options that are useful for constructing SQL statements.
2711 ** All of the usual printf() formatting options apply.  In addition, there
2712 ** is are "%q", "%Q", and "%z" options.
2713 **
2714 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2715 ** string from the argument list.  But %q also doubles every '\'' character.
2716 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2717 ** character it escapes that character and allows it to be inserted into
2718 ** the string.
2719 **
2720 ** For example, assume the string variable zText contains text as follows:
2721 **
2722 ** <blockquote><pre>
2723 **  char *zText = "It's a happy day!";
2724 ** </pre></blockquote>
2725 **
2726 ** One can use this text in an SQL statement as follows:
2727 **
2728 ** <blockquote><pre>
2729 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2730 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2731 **  sqlite3_free(zSQL);
2732 ** </pre></blockquote>
2733 **
2734 ** Because the %q format string is used, the '\'' character in zText
2735 ** is escaped and the SQL generated is as follows:
2736 **
2737 ** <blockquote><pre>
2738 **  INSERT INTO table1 VALUES('It''s a happy day!')
2739 ** </pre></blockquote>
2740 **
2741 ** This is correct.  Had we used %s instead of %q, the generated SQL
2742 ** would have looked like this:
2743 **
2744 ** <blockquote><pre>
2745 **  INSERT INTO table1 VALUES('It's a happy day!');
2746 ** </pre></blockquote>
2747 **
2748 ** This second example is an SQL syntax error.  As a general rule you should
2749 ** always use %q instead of %s when inserting text into a string literal.
2750 **
2751 ** ^(The %Q option works like %q except it also adds single quotes around
2752 ** the outside of the total string.  Additionally, if the parameter in the
2753 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2754 ** single quotes).)^  So, for example, one could say:
2755 **
2756 ** <blockquote><pre>
2757 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2758 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2759 **  sqlite3_free(zSQL);
2760 ** </pre></blockquote>
2761 **
2762 ** The code above will render a correct SQL statement in the zSQL
2763 ** variable even if the zText variable is a NULL pointer.
2764 **
2765 ** ^(The "%z" formatting option works like "%s" but with the
2766 ** addition that after the string has been read and copied into
2767 ** the result, [sqlite3_free()] is called on the input string.)^
2768 */
2769 SQLITE_API char *sqlite3_mprintf(const char*,...);
2770 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2771 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2772 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2773 
2774 /*
2775 ** CAPI3REF: Memory Allocation Subsystem
2776 **
2777 ** The SQLite core uses these three routines for all of its own
2778 ** internal memory allocation needs. "Core" in the previous sentence
2779 ** does not include operating-system specific VFS implementation.  The
2780 ** Windows VFS uses native malloc() and free() for some operations.
2781 **
2782 ** ^The sqlite3_malloc() routine returns a pointer to a block
2783 ** of memory at least N bytes in length, where N is the parameter.
2784 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2785 ** memory, it returns a NULL pointer.  ^If the parameter N to
2786 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2787 ** a NULL pointer.
2788 **
2789 ** ^Calling sqlite3_free() with a pointer previously returned
2790 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2791 ** that it might be reused.  ^The sqlite3_free() routine is
2792 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2793 ** to sqlite3_free() is harmless.  After being freed, memory
2794 ** should neither be read nor written.  Even reading previously freed
2795 ** memory might result in a segmentation fault or other severe error.
2796 ** Memory corruption, a segmentation fault, or other severe error
2797 ** might result if sqlite3_free() is called with a non-NULL pointer that
2798 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2799 **
2800 ** ^(The sqlite3_realloc() interface attempts to resize a
2801 ** prior memory allocation to be at least N bytes, where N is the
2802 ** second parameter.  The memory allocation to be resized is the first
2803 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2804 ** is a NULL pointer then its behavior is identical to calling
2805 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2806 ** ^If the second parameter to sqlite3_realloc() is zero or
2807 ** negative then the behavior is exactly the same as calling
2808 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2809 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2810 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2811 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2812 ** of the prior allocation are copied into the beginning of buffer returned
2813 ** by sqlite3_realloc() and the prior allocation is freed.
2814 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2815 ** is not freed.
2816 **
2817 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2818 ** is always aligned to at least an 8 byte boundary, or to a
2819 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2820 ** option is used.
2821 **
2822 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2823 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2824 ** implementation of these routines to be omitted.  That capability
2825 ** is no longer provided.  Only built-in memory allocators can be used.
2826 **
2827 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2828 ** the system malloc() and free() directly when converting
2829 ** filenames between the UTF-8 encoding used by SQLite
2830 ** and whatever filename encoding is used by the particular Windows
2831 ** installation.  Memory allocation errors were detected, but
2832 ** they were reported back as [SQLITE_CANTOPEN] or
2833 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2834 **
2835 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2836 ** must be either NULL or else pointers obtained from a prior
2837 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2838 ** not yet been released.
2839 **
2840 ** The application must not read or write any part of
2841 ** a block of memory after it has been released using
2842 ** [sqlite3_free()] or [sqlite3_realloc()].
2843 */
2844 SQLITE_API void *sqlite3_malloc(int);
2845 SQLITE_API void *sqlite3_realloc(void*, int);
2846 SQLITE_API void sqlite3_free(void*);
2847 
2848 /*
2849 ** CAPI3REF: Memory Allocator Statistics
2850 **
2851 ** SQLite provides these two interfaces for reporting on the status
2852 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2853 ** routines, which form the built-in memory allocation subsystem.
2854 **
2855 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2856 ** of memory currently outstanding (malloced but not freed).
2857 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2858 ** value of [sqlite3_memory_used()] since the high-water mark
2859 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2860 ** [sqlite3_memory_highwater()] include any overhead
2861 ** added by SQLite in its implementation of [sqlite3_malloc()],
2862 ** but not overhead added by the any underlying system library
2863 ** routines that [sqlite3_malloc()] may call.
2864 **
2865 ** ^The memory high-water mark is reset to the current value of
2866 ** [sqlite3_memory_used()] if and only if the parameter to
2867 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2868 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2869 ** prior to the reset.
2870 */
2871 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2872 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2873 
2874 /*
2875 ** CAPI3REF: Pseudo-Random Number Generator
2876 **
2877 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2878 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2879 ** already uses the largest possible [ROWID].  The PRNG is also used for
2880 ** the build-in random() and randomblob() SQL functions.  This interface allows
2881 ** applications to access the same PRNG for other purposes.
2882 **
2883 ** ^A call to this routine stores N bytes of randomness into buffer P.
2884 **
2885 ** ^The first time this routine is invoked (either internally or by
2886 ** the application) the PRNG is seeded using randomness obtained
2887 ** from the xRandomness method of the default [sqlite3_vfs] object.
2888 ** ^On all subsequent invocations, the pseudo-randomness is generated
2889 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2890 ** method.
2891 */
2892 SQLITE_API void sqlite3_randomness(int N, void *P);
2893 
2894 /*
2895 ** CAPI3REF: Compile-Time Authorization Callbacks
2896 **
2897 ** ^This routine registers an authorizer callback with a particular
2898 ** [database connection], supplied in the first argument.
2899 ** ^The authorizer callback is invoked as SQL statements are being compiled
2900 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2901 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2902 ** points during the compilation process, as logic is being created
2903 ** to perform various actions, the authorizer callback is invoked to
2904 ** see if those actions are allowed.  ^The authorizer callback should
2905 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2906 ** specific action but allow the SQL statement to continue to be
2907 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2908 ** rejected with an error.  ^If the authorizer callback returns
2909 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2910 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2911 ** the authorizer will fail with an error message.
2912 **
2913 ** When the callback returns [SQLITE_OK], that means the operation
2914 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2915 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2916 ** authorizer will fail with an error message explaining that
2917 ** access is denied.
2918 **
2919 ** ^The first parameter to the authorizer callback is a copy of the third
2920 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2921 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2922 ** the particular action to be authorized. ^The third through sixth parameters
2923 ** to the callback are zero-terminated strings that contain additional
2924 ** details about the action to be authorized.
2925 **
2926 ** ^If the action code is [SQLITE_READ]
2927 ** and the callback returns [SQLITE_IGNORE] then the
2928 ** [prepared statement] statement is constructed to substitute
2929 ** a NULL value in place of the table column that would have
2930 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2931 ** return can be used to deny an untrusted user access to individual
2932 ** columns of a table.
2933 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2934 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2935 ** [truncate optimization] is disabled and all rows are deleted individually.
2936 **
2937 ** An authorizer is used when [sqlite3_prepare | preparing]
2938 ** SQL statements from an untrusted source, to ensure that the SQL statements
2939 ** do not try to access data they are not allowed to see, or that they do not
2940 ** try to execute malicious statements that damage the database.  For
2941 ** example, an application may allow a user to enter arbitrary
2942 ** SQL queries for evaluation by a database.  But the application does
2943 ** not want the user to be able to make arbitrary changes to the
2944 ** database.  An authorizer could then be put in place while the
2945 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2946 ** disallows everything except [SELECT] statements.
2947 **
2948 ** Applications that need to process SQL from untrusted sources
2949 ** might also consider lowering resource limits using [sqlite3_limit()]
2950 ** and limiting database size using the [max_page_count] [PRAGMA]
2951 ** in addition to using an authorizer.
2952 **
2953 ** ^(Only a single authorizer can be in place on a database connection
2954 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2955 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2956 ** The authorizer is disabled by default.
2957 **
2958 ** The authorizer callback must not do anything that will modify
2959 ** the database connection that invoked the authorizer callback.
2960 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2961 ** database connections for the meaning of "modify" in this paragraph.
2962 **
2963 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2964 ** statement might be re-prepared during [sqlite3_step()] due to a
2965 ** schema change.  Hence, the application should ensure that the
2966 ** correct authorizer callback remains in place during the [sqlite3_step()].
2967 **
2968 ** ^Note that the authorizer callback is invoked only during
2969 ** [sqlite3_prepare()] or its variants.  Authorization is not
2970 ** performed during statement evaluation in [sqlite3_step()], unless
2971 ** as stated in the previous paragraph, sqlite3_step() invokes
2972 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2973 */
2974 SQLITE_API int sqlite3_set_authorizer(
2975   sqlite3*,
2976   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2977   void *pUserData
2978 );
2979 
2980 /*
2981 ** CAPI3REF: Authorizer Return Codes
2982 **
2983 ** The [sqlite3_set_authorizer | authorizer callback function] must
2984 ** return either [SQLITE_OK] or one of these two constants in order
2985 ** to signal SQLite whether or not the action is permitted.  See the
2986 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2987 ** information.
2988 **
2989 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2990 ** from the [sqlite3_vtab_on_conflict()] interface.
2991 */
2992 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2993 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2994 
2995 /*
2996 ** CAPI3REF: Authorizer Action Codes
2997 **
2998 ** The [sqlite3_set_authorizer()] interface registers a callback function
2999 ** that is invoked to authorize certain SQL statement actions.  The
3000 ** second parameter to the callback is an integer code that specifies
3001 ** what action is being authorized.  These are the integer action codes that
3002 ** the authorizer callback may be passed.
3003 **
3004 ** These action code values signify what kind of operation is to be
3005 ** authorized.  The 3rd and 4th parameters to the authorization
3006 ** callback function will be parameters or NULL depending on which of these
3007 ** codes is used as the second parameter.  ^(The 5th parameter to the
3008 ** authorizer callback is the name of the database ("main", "temp",
3009 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3010 ** is the name of the inner-most trigger or view that is responsible for
3011 ** the access attempt or NULL if this access attempt is directly from
3012 ** top-level SQL code.
3013 */
3014 /******************************************* 3rd ************ 4th ***********/
3015 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3016 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3017 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3018 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3019 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3020 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3021 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3022 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3023 #define SQLITE_DELETE                9   /* Table Name      NULL            */
3024 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3025 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3026 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3027 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3028 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3029 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3030 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3031 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3032 #define SQLITE_INSERT               18   /* Table Name      NULL            */
3033 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3034 #define SQLITE_READ                 20   /* Table Name      Column Name     */
3035 #define SQLITE_SELECT               21   /* NULL            NULL            */
3036 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3037 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3038 #define SQLITE_ATTACH               24   /* Filename        NULL            */
3039 #define SQLITE_DETACH               25   /* Database Name   NULL            */
3040 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3041 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
3042 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3043 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3044 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3045 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3046 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3047 #define SQLITE_COPY                  0   /* No longer used */
3048 
3049 /*
3050 ** CAPI3REF: Tracing And Profiling Functions
3051 **
3052 ** These routines register callback functions that can be used for
3053 ** tracing and profiling the execution of SQL statements.
3054 **
3055 ** ^The callback function registered by sqlite3_trace() is invoked at
3056 ** various times when an SQL statement is being run by [sqlite3_step()].
3057 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3058 ** SQL statement text as the statement first begins executing.
3059 ** ^(Additional sqlite3_trace() callbacks might occur
3060 ** as each triggered subprogram is entered.  The callbacks for triggers
3061 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3062 **
3063 ** ^The callback function registered by sqlite3_profile() is invoked
3064 ** as each SQL statement finishes.  ^The profile callback contains
3065 ** the original statement text and an estimate of wall-clock time
3066 ** of how long that statement took to run.  ^The profile callback
3067 ** time is in units of nanoseconds, however the current implementation
3068 ** is only capable of millisecond resolution so the six least significant
3069 ** digits in the time are meaningless.  Future versions of SQLite
3070 ** might provide greater resolution on the profiler callback.  The
3071 ** sqlite3_profile() function is considered experimental and is
3072 ** subject to change in future versions of SQLite.
3073 */
3074 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3075 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3076    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3077 
3078 /*
3079 ** CAPI3REF: Query Progress Callbacks
3080 **
3081 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3082 ** function X to be invoked periodically during long running calls to
3083 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3084 ** database connection D.  An example use for this
3085 ** interface is to keep a GUI updated during a large query.
3086 **
3087 ** ^The parameter P is passed through as the only parameter to the
3088 ** callback function X.  ^The parameter N is the number of
3089 ** [virtual machine instructions] that are evaluated between successive
3090 ** invocations of the callback X.
3091 **
3092 ** ^Only a single progress handler may be defined at one time per
3093 ** [database connection]; setting a new progress handler cancels the
3094 ** old one.  ^Setting parameter X to NULL disables the progress handler.
3095 ** ^The progress handler is also disabled by setting N to a value less
3096 ** than 1.
3097 **
3098 ** ^If the progress callback returns non-zero, the operation is
3099 ** interrupted.  This feature can be used to implement a
3100 ** "Cancel" button on a GUI progress dialog box.
3101 **
3102 ** The progress handler callback must not do anything that will modify
3103 ** the database connection that invoked the progress handler.
3104 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3105 ** database connections for the meaning of "modify" in this paragraph.
3106 **
3107 */
3108 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3109 
3110 /*
3111 ** CAPI3REF: Opening A New Database Connection
3112 **
3113 ** ^These routines open an SQLite database file as specified by the
3114 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3115 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3116 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3117 ** returned in *ppDb, even if an error occurs.  The only exception is that
3118 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3119 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3120 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3121 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3122 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3123 ** an English language description of the error following a failure of any
3124 ** of the sqlite3_open() routines.
3125 **
3126 ** ^The default encoding for the database will be UTF-8 if
3127 ** sqlite3_open() or sqlite3_open_v2() is called and
3128 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3129 **
3130 ** Whether or not an error occurs when it is opened, resources
3131 ** associated with the [database connection] handle should be released by
3132 ** passing it to [sqlite3_close()] when it is no longer required.
3133 **
3134 ** The sqlite3_open_v2() interface works like sqlite3_open()
3135 ** except that it accepts two additional parameters for additional control
3136 ** over the new database connection.  ^(The flags parameter to
3137 ** sqlite3_open_v2() can take one of
3138 ** the following three values, optionally combined with the
3139 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3140 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3141 **
3142 ** <dl>
3143 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3144 ** <dd>The database is opened in read-only mode.  If the database does not
3145 ** already exist, an error is returned.</dd>)^
3146 **
3147 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3148 ** <dd>The database is opened for reading and writing if possible, or reading
3149 ** only if the file is write protected by the operating system.  In either
3150 ** case the database must already exist, otherwise an error is returned.</dd>)^
3151 **
3152 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3153 ** <dd>The database is opened for reading and writing, and is created if
3154 ** it does not already exist. This is the behavior that is always used for
3155 ** sqlite3_open() and sqlite3_open16().</dd>)^
3156 ** </dl>
3157 **
3158 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3159 ** combinations shown above optionally combined with other
3160 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3161 ** then the behavior is undefined.
3162 **
3163 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3164 ** opens in the multi-thread [threading mode] as long as the single-thread
3165 ** mode has not been set at compile-time or start-time.  ^If the
3166 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3167 ** in the serialized [threading mode] unless single-thread was
3168 ** previously selected at compile-time or start-time.
3169 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3170 ** eligible to use [shared cache mode], regardless of whether or not shared
3171 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3172 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3173 ** participate in [shared cache mode] even if it is enabled.
3174 **
3175 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3176 ** [sqlite3_vfs] object that defines the operating system interface that
3177 ** the new database connection should use.  ^If the fourth parameter is
3178 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3179 **
3180 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3181 ** is created for the connection.  ^This in-memory database will vanish when
3182 ** the database connection is closed.  Future versions of SQLite might
3183 ** make use of additional special filenames that begin with the ":" character.
3184 ** It is recommended that when a database filename actually does begin with
3185 ** a ":" character you should prefix the filename with a pathname such as
3186 ** "./" to avoid ambiguity.
3187 **
3188 ** ^If the filename is an empty string, then a private, temporary
3189 ** on-disk database will be created.  ^This private database will be
3190 ** automatically deleted as soon as the database connection is closed.
3191 **
3192 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3193 **
3194 ** ^If [URI filename] interpretation is enabled, and the filename argument
3195 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3196 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3197 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3198 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3199 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3200 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3201 ** by default, but future releases of SQLite might enable URI filename
3202 ** interpretation by default.  See "[URI filenames]" for additional
3203 ** information.
3204 **
3205 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3206 ** authority, then it must be either an empty string or the string
3207 ** "localhost". ^If the authority is not an empty string or "localhost", an
3208 ** error is returned to the caller. ^The fragment component of a URI, if
3209 ** present, is ignored.
3210 **
3211 ** ^SQLite uses the path component of the URI as the name of the disk file
3212 ** which contains the database. ^If the path begins with a '/' character,
3213 ** then it is interpreted as an absolute path. ^If the path does not begin
3214 ** with a '/' (meaning that the authority section is omitted from the URI)
3215 ** then the path is interpreted as a relative path.
3216 ** ^On windows, the first component of an absolute path
3217 ** is a drive specification (e.g. "C:").
3218 **
3219 ** [[core URI query parameters]]
3220 ** The query component of a URI may contain parameters that are interpreted
3221 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3222 ** SQLite interprets the following three query parameters:
3223 **
3224 ** <ul>
3225 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3226 **     a VFS object that provides the operating system interface that should
3227 **     be used to access the database file on disk. ^If this option is set to
3228 **     an empty string the default VFS object is used. ^Specifying an unknown
3229 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3230 **     present, then the VFS specified by the option takes precedence over
3231 **     the value passed as the fourth parameter to sqlite3_open_v2().
3232 **
3233 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3234 **     "rwc", or "memory". Attempting to set it to any other value is
3235 **     an error)^.
3236 **     ^If "ro" is specified, then the database is opened for read-only
3237 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3238 **     third argument to sqlite3_open_v2(). ^If the mode option is set to
3239 **     "rw", then the database is opened for read-write (but not create)
3240 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3241 **     been set. ^Value "rwc" is equivalent to setting both
3242 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3243 **     set to "memory" then a pure [in-memory database] that never reads
3244 **     or writes from disk is used. ^It is an error to specify a value for
3245 **     the mode parameter that is less restrictive than that specified by
3246 **     the flags passed in the third parameter to sqlite3_open_v2().
3247 **
3248 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3249 **     "private". ^Setting it to "shared" is equivalent to setting the
3250 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3251 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3252 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3253 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3254 **     a URI filename, its value overrides any behavior requested by setting
3255 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3256 ** </ul>
3257 **
3258 ** ^Specifying an unknown parameter in the query component of a URI is not an
3259 ** error.  Future versions of SQLite might understand additional query
3260 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3261 ** additional information.
3262 **
3263 ** [[URI filename examples]] <h3>URI filename examples</h3>
3264 **
3265 ** <table border="1" align=center cellpadding=5>
3266 ** <tr><th> URI filenames <th> Results
3267 ** <tr><td> file:data.db <td>
3268 **          Open the file "data.db" in the current directory.
3269 ** <tr><td> file:/home/fred/data.db<br>
3270 **          file:///home/fred/data.db <br>
3271 **          file://localhost/home/fred/data.db <br> <td>
3272 **          Open the database file "/home/fred/data.db".
3273 ** <tr><td> file://darkstar/home/fred/data.db <td>
3274 **          An error. "darkstar" is not a recognized authority.
3275 ** <tr><td style="white-space:nowrap">
3276 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3277 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3278 **          C:. Note that the %20 escaping in this example is not strictly
3279 **          necessary - space characters can be used literally
3280 **          in URI filenames.
3281 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3282 **          Open file "data.db" in the current directory for read-only access.
3283 **          Regardless of whether or not shared-cache mode is enabled by
3284 **          default, use a private cache.
3285 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3286 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3287 ** <tr><td> file:data.db?mode=readonly <td>
3288 **          An error. "readonly" is not a valid option for the "mode" parameter.
3289 ** </table>
3290 **
3291 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3292 ** query components of a URI. A hexadecimal escape sequence consists of a
3293 ** percent sign - "%" - followed by exactly two hexadecimal digits
3294 ** specifying an octet value. ^Before the path or query components of a
3295 ** URI filename are interpreted, they are encoded using UTF-8 and all
3296 ** hexadecimal escape sequences replaced by a single byte containing the
3297 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3298 ** the results are undefined.
3299 **
3300 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3301 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3302 ** codepage is currently defined.  Filenames containing international
3303 ** characters must be converted to UTF-8 prior to passing them into
3304 ** sqlite3_open() or sqlite3_open_v2().
3305 **
3306 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3307 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3308 ** features that require the use of temporary files may fail.
3309 **
3310 ** See also: [sqlite3_temp_directory]
3311 */
3312 SQLITE_API int sqlite3_open(
3313   const char *filename,   /* Database filename (UTF-8) */
3314   sqlite3 **ppDb          /* OUT: SQLite db handle */
3315 );
3316 SQLITE_API int sqlite3_open16(
3317   const void *filename,   /* Database filename (UTF-16) */
3318   sqlite3 **ppDb          /* OUT: SQLite db handle */
3319 );
3320 SQLITE_API int sqlite3_open_v2(
3321   const char *filename,   /* Database filename (UTF-8) */
3322   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3323   int flags,              /* Flags */
3324   const char *zVfs        /* Name of VFS module to use */
3325 );
3326 
3327 /*
3328 ** CAPI3REF: Obtain Values For URI Parameters
3329 **
3330 ** These are utility routines, useful to VFS implementations, that check
3331 ** to see if a database file was a URI that contained a specific query
3332 ** parameter, and if so obtains the value of that query parameter.
3333 **
3334 ** If F is the database filename pointer passed into the xOpen() method of
3335 ** a VFS implementation when the flags parameter to xOpen() has one or
3336 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3337 ** P is the name of the query parameter, then
3338 ** sqlite3_uri_parameter(F,P) returns the value of the P
3339 ** parameter if it exists or a NULL pointer if P does not appear as a
3340 ** query parameter on F.  If P is a query parameter of F
3341 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3342 ** a pointer to an empty string.
3343 **
3344 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3345 ** parameter and returns true (1) or false (0) according to the value
3346 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3347 ** value of query parameter P is one of "yes", "true", or "on" in any
3348 ** case or if the value begins with a non-zero number.  The
3349 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3350 ** query parameter P is one of "no", "false", or "off" in any case or
3351 ** if the value begins with a numeric zero.  If P is not a query
3352 ** parameter on F or if the value of P is does not match any of the
3353 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3354 **
3355 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3356 ** 64-bit signed integer and returns that integer, or D if P does not
3357 ** exist.  If the value of P is something other than an integer, then
3358 ** zero is returned.
3359 **
3360 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3361 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3362 ** is not a database file pathname pointer that SQLite passed into the xOpen
3363 ** VFS method, then the behavior of this routine is undefined and probably
3364 ** undesirable.
3365 */
3366 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3367 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3368 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3369 
3370 
3371 /*
3372 ** CAPI3REF: Error Codes And Messages
3373 **
3374 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3375 ** [extended result code] for the most recent failed sqlite3_* API call
3376 ** associated with a [database connection]. If a prior API call failed
3377 ** but the most recent API call succeeded, the return value from
3378 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3379 ** interface is the same except that it always returns the
3380 ** [extended result code] even when extended result codes are
3381 ** disabled.
3382 **
3383 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3384 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3385 ** ^(Memory to hold the error message string is managed internally.
3386 ** The application does not need to worry about freeing the result.
3387 ** However, the error string might be overwritten or deallocated by
3388 ** subsequent calls to other SQLite interface functions.)^
3389 **
3390 ** ^The sqlite3_errstr() interface returns the English-language text
3391 ** that describes the [result code], as UTF-8.
3392 ** ^(Memory to hold the error message string is managed internally
3393 ** and must not be freed by the application)^.
3394 **
3395 ** When the serialized [threading mode] is in use, it might be the
3396 ** case that a second error occurs on a separate thread in between
3397 ** the time of the first error and the call to these interfaces.
3398 ** When that happens, the second error will be reported since these
3399 ** interfaces always report the most recent result.  To avoid
3400 ** this, each thread can obtain exclusive use of the [database connection] D
3401 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3402 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3403 ** all calls to the interfaces listed here are completed.
3404 **
3405 ** If an interface fails with SQLITE_MISUSE, that means the interface
3406 ** was invoked incorrectly by the application.  In that case, the
3407 ** error code and message may or may not be set.
3408 */
3409 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3410 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3411 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3412 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3413 SQLITE_API const char *sqlite3_errstr(int);
3414 
3415 /*
3416 ** CAPI3REF: SQL Statement Object
3417 ** KEYWORDS: {prepared statement} {prepared statements}
3418 **
3419 ** An instance of this object represents a single SQL statement.
3420 ** This object is variously known as a "prepared statement" or a
3421 ** "compiled SQL statement" or simply as a "statement".
3422 **
3423 ** The life of a statement object goes something like this:
3424 **
3425 ** <ol>
3426 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3427 **      function.
3428 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3429 **      interfaces.
3430 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3431 ** <li> Reset the statement using [sqlite3_reset()] then go back
3432 **      to step 2.  Do this zero or more times.
3433 ** <li> Destroy the object using [sqlite3_finalize()].
3434 ** </ol>
3435 **
3436 ** Refer to documentation on individual methods above for additional
3437 ** information.
3438 */
3439 typedef struct sqlite3_stmt sqlite3_stmt;
3440 
3441 /*
3442 ** CAPI3REF: Run-time Limits
3443 **
3444 ** ^(This interface allows the size of various constructs to be limited
3445 ** on a connection by connection basis.  The first parameter is the
3446 ** [database connection] whose limit is to be set or queried.  The
3447 ** second parameter is one of the [limit categories] that define a
3448 ** class of constructs to be size limited.  The third parameter is the
3449 ** new limit for that construct.)^
3450 **
3451 ** ^If the new limit is a negative number, the limit is unchanged.
3452 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3453 ** [limits | hard upper bound]
3454 ** set at compile-time by a C preprocessor macro called
3455 ** [limits | SQLITE_MAX_<i>NAME</i>].
3456 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3457 ** ^Attempts to increase a limit above its hard upper bound are
3458 ** silently truncated to the hard upper bound.
3459 **
3460 ** ^Regardless of whether or not the limit was changed, the
3461 ** [sqlite3_limit()] interface returns the prior value of the limit.
3462 ** ^Hence, to find the current value of a limit without changing it,
3463 ** simply invoke this interface with the third parameter set to -1.
3464 **
3465 ** Run-time limits are intended for use in applications that manage
3466 ** both their own internal database and also databases that are controlled
3467 ** by untrusted external sources.  An example application might be a
3468 ** web browser that has its own databases for storing history and
3469 ** separate databases controlled by JavaScript applications downloaded
3470 ** off the Internet.  The internal databases can be given the
3471 ** large, default limits.  Databases managed by external sources can
3472 ** be given much smaller limits designed to prevent a denial of service
3473 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3474 ** interface to further control untrusted SQL.  The size of the database
3475 ** created by an untrusted script can be contained using the
3476 ** [max_page_count] [PRAGMA].
3477 **
3478 ** New run-time limit categories may be added in future releases.
3479 */
3480 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3481 
3482 /*
3483 ** CAPI3REF: Run-Time Limit Categories
3484 ** KEYWORDS: {limit category} {*limit categories}
3485 **
3486 ** These constants define various performance limits
3487 ** that can be lowered at run-time using [sqlite3_limit()].
3488 ** The synopsis of the meanings of the various limits is shown below.
3489 ** Additional information is available at [limits | Limits in SQLite].
3490 **
3491 ** <dl>
3492 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3493 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3494 **
3495 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3496 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3497 **
3498 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3499 ** <dd>The maximum number of columns in a table definition or in the
3500 ** result set of a [SELECT] or the maximum number of columns in an index
3501 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3502 **
3503 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3504 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3505 **
3506 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3507 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3508 **
3509 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3510 ** <dd>The maximum number of instructions in a virtual machine program
3511 ** used to implement an SQL statement.  This limit is not currently
3512 ** enforced, though that might be added in some future release of
3513 ** SQLite.</dd>)^
3514 **
3515 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3516 ** <dd>The maximum number of arguments on a function.</dd>)^
3517 **
3518 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3519 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3520 **
3521 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3522 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3523 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3524 ** [GLOB] operators.</dd>)^
3525 **
3526 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3527 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3528 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3529 **
3530 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3531 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3532 ** </dl>
3533 */
3534 #define SQLITE_LIMIT_LENGTH                    0
3535 #define SQLITE_LIMIT_SQL_LENGTH                1
3536 #define SQLITE_LIMIT_COLUMN                    2
3537 #define SQLITE_LIMIT_EXPR_DEPTH                3
3538 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3539 #define SQLITE_LIMIT_VDBE_OP                   5
3540 #define SQLITE_LIMIT_FUNCTION_ARG              6
3541 #define SQLITE_LIMIT_ATTACHED                  7
3542 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3543 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3544 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3545 
3546 /*
3547 ** CAPI3REF: Compiling An SQL Statement
3548 ** KEYWORDS: {SQL statement compiler}
3549 **
3550 ** To execute an SQL query, it must first be compiled into a byte-code
3551 ** program using one of these routines.
3552 **
3553 ** The first argument, "db", is a [database connection] obtained from a
3554 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3555 ** [sqlite3_open16()].  The database connection must not have been closed.
3556 **
3557 ** The second argument, "zSql", is the statement to be compiled, encoded
3558 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3559 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3560 ** use UTF-16.
3561 **
3562 ** ^If the nByte argument is less than zero, then zSql is read up to the
3563 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3564 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3565 ** zSql string ends at either the first '\000' or '\u0000' character or
3566 ** the nByte-th byte, whichever comes first. If the caller knows
3567 ** that the supplied string is nul-terminated, then there is a small
3568 ** performance advantage to be gained by passing an nByte parameter that
3569 ** is equal to the number of bytes in the input string <i>including</i>
3570 ** the nul-terminator bytes as this saves SQLite from having to
3571 ** make a copy of the input string.
3572 **
3573 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3574 ** past the end of the first SQL statement in zSql.  These routines only
3575 ** compile the first statement in zSql, so *pzTail is left pointing to
3576 ** what remains uncompiled.
3577 **
3578 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3579 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3580 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3581 ** string or a comment) then *ppStmt is set to NULL.
3582 ** The calling procedure is responsible for deleting the compiled
3583 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3584 ** ppStmt may not be NULL.
3585 **
3586 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3587 ** otherwise an [error code] is returned.
3588 **
3589 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3590 ** recommended for all new programs. The two older interfaces are retained
3591 ** for backwards compatibility, but their use is discouraged.
3592 ** ^In the "v2" interfaces, the prepared statement
3593 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3594 ** original SQL text. This causes the [sqlite3_step()] interface to
3595 ** behave differently in three ways:
3596 **
3597 ** <ol>
3598 ** <li>
3599 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3600 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3601 ** statement and try to run it again.
3602 ** </li>
3603 **
3604 ** <li>
3605 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3606 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3607 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3608 ** and the application would have to make a second call to [sqlite3_reset()]
3609 ** in order to find the underlying cause of the problem. With the "v2" prepare
3610 ** interfaces, the underlying reason for the error is returned immediately.
3611 ** </li>
3612 **
3613 ** <li>
3614 ** ^If the specific value bound to [parameter | host parameter] in the
3615 ** WHERE clause might influence the choice of query plan for a statement,
3616 ** then the statement will be automatically recompiled, as if there had been
3617 ** a schema change, on the first  [sqlite3_step()] call following any change
3618 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3619 ** ^The specific value of WHERE-clause [parameter] might influence the
3620 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3621 ** or [GLOB] operator or if the parameter is compared to an indexed column
3622 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3623 ** the
3624 ** </li>
3625 ** </ol>
3626 */
3627 SQLITE_API int sqlite3_prepare(
3628   sqlite3 *db,            /* Database handle */
3629   const char *zSql,       /* SQL statement, UTF-8 encoded */
3630   int nByte,              /* Maximum length of zSql in bytes. */
3631   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3632   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3633 );
3634 SQLITE_API int sqlite3_prepare_v2(
3635   sqlite3 *db,            /* Database handle */
3636   const char *zSql,       /* SQL statement, UTF-8 encoded */
3637   int nByte,              /* Maximum length of zSql in bytes. */
3638   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3639   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3640 );
3641 SQLITE_API int sqlite3_prepare16(
3642   sqlite3 *db,            /* Database handle */
3643   const void *zSql,       /* SQL statement, UTF-16 encoded */
3644   int nByte,              /* Maximum length of zSql in bytes. */
3645   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3646   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3647 );
3648 SQLITE_API int sqlite3_prepare16_v2(
3649   sqlite3 *db,            /* Database handle */
3650   const void *zSql,       /* SQL statement, UTF-16 encoded */
3651   int nByte,              /* Maximum length of zSql in bytes. */
3652   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3653   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3654 );
3655 
3656 /*
3657 ** CAPI3REF: Retrieving Statement SQL
3658 **
3659 ** ^This interface can be used to retrieve a saved copy of the original
3660 ** SQL text used to create a [prepared statement] if that statement was
3661 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3662 */
3663 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3664 
3665 /*
3666 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3667 **
3668 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3669 ** and only if the [prepared statement] X makes no direct changes to
3670 ** the content of the database file.
3671 **
3672 ** Note that [application-defined SQL functions] or
3673 ** [virtual tables] might change the database indirectly as a side effect.
3674 ** ^(For example, if an application defines a function "eval()" that
3675 ** calls [sqlite3_exec()], then the following SQL statement would
3676 ** change the database file through side-effects:
3677 **
3678 ** <blockquote><pre>
3679 **    SELECT eval('DELETE FROM t1') FROM t2;
3680 ** </pre></blockquote>
3681 **
3682 ** But because the [SELECT] statement does not change the database file
3683 ** directly, sqlite3_stmt_readonly() would still return true.)^
3684 **
3685 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3686 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3687 ** since the statements themselves do not actually modify the database but
3688 ** rather they control the timing of when other statements modify the
3689 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3690 ** sqlite3_stmt_readonly() to return true since, while those statements
3691 ** change the configuration of a database connection, they do not make
3692 ** changes to the content of the database files on disk.
3693 */
3694 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3695 
3696 /*
3697 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3698 **
3699 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3700 ** [prepared statement] S has been stepped at least once using
3701 ** [sqlite3_step(S)] but has not run to completion and/or has not
3702 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3703 ** interface returns false if S is a NULL pointer.  If S is not a
3704 ** NULL pointer and is not a pointer to a valid [prepared statement]
3705 ** object, then the behavior is undefined and probably undesirable.
3706 **
3707 ** This interface can be used in combination [sqlite3_next_stmt()]
3708 ** to locate all prepared statements associated with a database
3709 ** connection that are in need of being reset.  This can be used,
3710 ** for example, in diagnostic routines to search for prepared
3711 ** statements that are holding a transaction open.
3712 */
3713 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3714 
3715 /*
3716 ** CAPI3REF: Dynamically Typed Value Object
3717 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3718 **
3719 ** SQLite uses the sqlite3_value object to represent all values
3720 ** that can be stored in a database table. SQLite uses dynamic typing
3721 ** for the values it stores.  ^Values stored in sqlite3_value objects
3722 ** can be integers, floating point values, strings, BLOBs, or NULL.
3723 **
3724 ** An sqlite3_value object may be either "protected" or "unprotected".
3725 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3726 ** will accept either a protected or an unprotected sqlite3_value.
3727 ** Every interface that accepts sqlite3_value arguments specifies
3728 ** whether or not it requires a protected sqlite3_value.
3729 **
3730 ** The terms "protected" and "unprotected" refer to whether or not
3731 ** a mutex is held.  An internal mutex is held for a protected
3732 ** sqlite3_value object but no mutex is held for an unprotected
3733 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3734 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3735 ** or if SQLite is run in one of reduced mutex modes
3736 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3737 ** then there is no distinction between protected and unprotected
3738 ** sqlite3_value objects and they can be used interchangeably.  However,
3739 ** for maximum code portability it is recommended that applications
3740 ** still make the distinction between protected and unprotected
3741 ** sqlite3_value objects even when not strictly required.
3742 **
3743 ** ^The sqlite3_value objects that are passed as parameters into the
3744 ** implementation of [application-defined SQL functions] are protected.
3745 ** ^The sqlite3_value object returned by
3746 ** [sqlite3_column_value()] is unprotected.
3747 ** Unprotected sqlite3_value objects may only be used with
3748 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3749 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3750 ** interfaces require protected sqlite3_value objects.
3751 */
3752 typedef struct Mem sqlite3_value;
3753 
3754 /*
3755 ** CAPI3REF: SQL Function Context Object
3756 **
3757 ** The context in which an SQL function executes is stored in an
3758 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3759 ** is always first parameter to [application-defined SQL functions].
3760 ** The application-defined SQL function implementation will pass this
3761 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3762 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3763 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3764 ** and/or [sqlite3_set_auxdata()].
3765 */
3766 typedef struct sqlite3_context sqlite3_context;
3767 
3768 /*
3769 ** CAPI3REF: Binding Values To Prepared Statements
3770 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3771 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3772 **
3773 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3774 ** literals may be replaced by a [parameter] that matches one of following
3775 ** templates:
3776 **
3777 ** <ul>
3778 ** <li>  ?
3779 ** <li>  ?NNN
3780 ** <li>  :VVV
3781 ** <li>  @VVV
3782 ** <li>  $VVV
3783 ** </ul>
3784 **
3785 ** In the templates above, NNN represents an integer literal,
3786 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3787 ** parameters (also called "host parameter names" or "SQL parameters")
3788 ** can be set using the sqlite3_bind_*() routines defined here.
3789 **
3790 ** ^The first argument to the sqlite3_bind_*() routines is always
3791 ** a pointer to the [sqlite3_stmt] object returned from
3792 ** [sqlite3_prepare_v2()] or its variants.
3793 **
3794 ** ^The second argument is the index of the SQL parameter to be set.
3795 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3796 ** SQL parameter is used more than once, second and subsequent
3797 ** occurrences have the same index as the first occurrence.
3798 ** ^The index for named parameters can be looked up using the
3799 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3800 ** for "?NNN" parameters is the value of NNN.
3801 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3802 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3803 **
3804 ** ^The third argument is the value to bind to the parameter.
3805 **
3806 ** ^(In those routines that have a fourth argument, its value is the
3807 ** number of bytes in the parameter.  To be clear: the value is the
3808 ** number of <u>bytes</u> in the value, not the number of characters.)^
3809 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3810 ** is negative, then the length of the string is
3811 ** the number of bytes up to the first zero terminator.
3812 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3813 ** the behavior is undefined.
3814 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3815 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3816 ** where the NUL terminator would occur assuming the string were NUL
3817 ** terminated.  If any NUL characters occur at byte offsets less than
3818 ** the value of the fourth parameter then the resulting string value will
3819 ** contain embedded NULs.  The result of expressions involving strings
3820 ** with embedded NULs is undefined.
3821 **
3822 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3823 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3824 ** string after SQLite has finished with it.  ^The destructor is called
3825 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3826 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3827 ** ^If the fifth argument is
3828 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3829 ** information is in static, unmanaged space and does not need to be freed.
3830 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3831 ** SQLite makes its own private copy of the data immediately, before
3832 ** the sqlite3_bind_*() routine returns.
3833 **
3834 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3835 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3836 ** (just an integer to hold its size) while it is being processed.
3837 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3838 ** content is later written using
3839 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3840 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3841 **
3842 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3843 ** for the [prepared statement] or with a prepared statement for which
3844 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3845 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3846 ** routine is passed a [prepared statement] that has been finalized, the
3847 ** result is undefined and probably harmful.
3848 **
3849 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3850 ** ^Unbound parameters are interpreted as NULL.
3851 **
3852 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3853 ** [error code] if anything goes wrong.
3854 ** ^[SQLITE_RANGE] is returned if the parameter
3855 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3856 **
3857 ** See also: [sqlite3_bind_parameter_count()],
3858 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3859 */
3860 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3861 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3862 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3863 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3864 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3865 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3866 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3867 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3868 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3869 
3870 /*
3871 ** CAPI3REF: Number Of SQL Parameters
3872 **
3873 ** ^This routine can be used to find the number of [SQL parameters]
3874 ** in a [prepared statement].  SQL parameters are tokens of the
3875 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3876 ** placeholders for values that are [sqlite3_bind_blob | bound]
3877 ** to the parameters at a later time.
3878 **
3879 ** ^(This routine actually returns the index of the largest (rightmost)
3880 ** parameter. For all forms except ?NNN, this will correspond to the
3881 ** number of unique parameters.  If parameters of the ?NNN form are used,
3882 ** there may be gaps in the list.)^
3883 **
3884 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3885 ** [sqlite3_bind_parameter_name()], and
3886 ** [sqlite3_bind_parameter_index()].
3887 */
3888 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3889 
3890 /*
3891 ** CAPI3REF: Name Of A Host Parameter
3892 **
3893 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3894 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3895 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3896 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3897 ** respectively.
3898 ** In other words, the initial ":" or "$" or "@" or "?"
3899 ** is included as part of the name.)^
3900 ** ^Parameters of the form "?" without a following integer have no name
3901 ** and are referred to as "nameless" or "anonymous parameters".
3902 **
3903 ** ^The first host parameter has an index of 1, not 0.
3904 **
3905 ** ^If the value N is out of range or if the N-th parameter is
3906 ** nameless, then NULL is returned.  ^The returned string is
3907 ** always in UTF-8 encoding even if the named parameter was
3908 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3909 ** [sqlite3_prepare16_v2()].
3910 **
3911 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3912 ** [sqlite3_bind_parameter_count()], and
3913 ** [sqlite3_bind_parameter_index()].
3914 */
3915 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3916 
3917 /*
3918 ** CAPI3REF: Index Of A Parameter With A Given Name
3919 **
3920 ** ^Return the index of an SQL parameter given its name.  ^The
3921 ** index value returned is suitable for use as the second
3922 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3923 ** is returned if no matching parameter is found.  ^The parameter
3924 ** name must be given in UTF-8 even if the original statement
3925 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3926 **
3927 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3928 ** [sqlite3_bind_parameter_count()], and
3929 ** [sqlite3_bind_parameter_index()].
3930 */
3931 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3932 
3933 /*
3934 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3935 **
3936 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3937 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3938 ** ^Use this routine to reset all host parameters to NULL.
3939 */
3940 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3941 
3942 /*
3943 ** CAPI3REF: Number Of Columns In A Result Set
3944 **
3945 ** ^Return the number of columns in the result set returned by the
3946 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3947 ** statement that does not return data (for example an [UPDATE]).
3948 **
3949 ** See also: [sqlite3_data_count()]
3950 */
3951 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3952 
3953 /*
3954 ** CAPI3REF: Column Names In A Result Set
3955 **
3956 ** ^These routines return the name assigned to a particular column
3957 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3958 ** interface returns a pointer to a zero-terminated UTF-8 string
3959 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3960 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3961 ** that implements the [SELECT] statement. ^The second parameter is the
3962 ** column number.  ^The leftmost column is number 0.
3963 **
3964 ** ^The returned string pointer is valid until either the [prepared statement]
3965 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3966 ** reprepared by the first call to [sqlite3_step()] for a particular run
3967 ** or until the next call to
3968 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3969 **
3970 ** ^If sqlite3_malloc() fails during the processing of either routine
3971 ** (for example during a conversion from UTF-8 to UTF-16) then a
3972 ** NULL pointer is returned.
3973 **
3974 ** ^The name of a result column is the value of the "AS" clause for
3975 ** that column, if there is an AS clause.  If there is no AS clause
3976 ** then the name of the column is unspecified and may change from
3977 ** one release of SQLite to the next.
3978 */
3979 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3980 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3981 
3982 /*
3983 ** CAPI3REF: Source Of Data In A Query Result
3984 **
3985 ** ^These routines provide a means to determine the database, table, and
3986 ** table column that is the origin of a particular result column in
3987 ** [SELECT] statement.
3988 ** ^The name of the database or table or column can be returned as
3989 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3990 ** the database name, the _table_ routines return the table name, and
3991 ** the origin_ routines return the column name.
3992 ** ^The returned string is valid until the [prepared statement] is destroyed
3993 ** using [sqlite3_finalize()] or until the statement is automatically
3994 ** reprepared by the first call to [sqlite3_step()] for a particular run
3995 ** or until the same information is requested
3996 ** again in a different encoding.
3997 **
3998 ** ^The names returned are the original un-aliased names of the
3999 ** database, table, and column.
4000 **
4001 ** ^The first argument to these interfaces is a [prepared statement].
4002 ** ^These functions return information about the Nth result column returned by
4003 ** the statement, where N is the second function argument.
4004 ** ^The left-most column is column 0 for these routines.
4005 **
4006 ** ^If the Nth column returned by the statement is an expression or
4007 ** subquery and is not a column value, then all of these functions return
4008 ** NULL.  ^These routine might also return NULL if a memory allocation error
4009 ** occurs.  ^Otherwise, they return the name of the attached database, table,
4010 ** or column that query result column was extracted from.
4011 **
4012 ** ^As with all other SQLite APIs, those whose names end with "16" return
4013 ** UTF-16 encoded strings and the other functions return UTF-8.
4014 **
4015 ** ^These APIs are only available if the library was compiled with the
4016 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4017 **
4018 ** If two or more threads call one or more of these routines against the same
4019 ** prepared statement and column at the same time then the results are
4020 ** undefined.
4021 **
4022 ** If two or more threads call one or more
4023 ** [sqlite3_column_database_name | column metadata interfaces]
4024 ** for the same [prepared statement] and result column
4025 ** at the same time then the results are undefined.
4026 */
4027 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4028 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4029 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4030 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4031 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4032 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4033 
4034 /*
4035 ** CAPI3REF: Declared Datatype Of A Query Result
4036 **
4037 ** ^(The first parameter is a [prepared statement].
4038 ** If this statement is a [SELECT] statement and the Nth column of the
4039 ** returned result set of that [SELECT] is a table column (not an
4040 ** expression or subquery) then the declared type of the table
4041 ** column is returned.)^  ^If the Nth column of the result set is an
4042 ** expression or subquery, then a NULL pointer is returned.
4043 ** ^The returned string is always UTF-8 encoded.
4044 **
4045 ** ^(For example, given the database schema:
4046 **
4047 ** CREATE TABLE t1(c1 VARIANT);
4048 **
4049 ** and the following statement to be compiled:
4050 **
4051 ** SELECT c1 + 1, c1 FROM t1;
4052 **
4053 ** this routine would return the string "VARIANT" for the second result
4054 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4055 **
4056 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
4057 ** is declared to contain a particular type does not mean that the
4058 ** data stored in that column is of the declared type.  SQLite is
4059 ** strongly typed, but the typing is dynamic not static.  ^Type
4060 ** is associated with individual values, not with the containers
4061 ** used to hold those values.
4062 */
4063 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4064 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4065 
4066 /*
4067 ** CAPI3REF: Evaluate An SQL Statement
4068 **
4069 ** After a [prepared statement] has been prepared using either
4070 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4071 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4072 ** must be called one or more times to evaluate the statement.
4073 **
4074 ** The details of the behavior of the sqlite3_step() interface depend
4075 ** on whether the statement was prepared using the newer "v2" interface
4076 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4077 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4078 ** new "v2" interface is recommended for new applications but the legacy
4079 ** interface will continue to be supported.
4080 **
4081 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4082 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4083 ** ^With the "v2" interface, any of the other [result codes] or
4084 ** [extended result codes] might be returned as well.
4085 **
4086 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4087 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4088 ** or occurs outside of an explicit transaction, then you can retry the
4089 ** statement.  If the statement is not a [COMMIT] and occurs within an
4090 ** explicit transaction then you should rollback the transaction before
4091 ** continuing.
4092 **
4093 ** ^[SQLITE_DONE] means that the statement has finished executing
4094 ** successfully.  sqlite3_step() should not be called again on this virtual
4095 ** machine without first calling [sqlite3_reset()] to reset the virtual
4096 ** machine back to its initial state.
4097 **
4098 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4099 ** is returned each time a new row of data is ready for processing by the
4100 ** caller. The values may be accessed using the [column access functions].
4101 ** sqlite3_step() is called again to retrieve the next row of data.
4102 **
4103 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4104 ** violation) has occurred.  sqlite3_step() should not be called again on
4105 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4106 ** ^With the legacy interface, a more specific error code (for example,
4107 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4108 ** can be obtained by calling [sqlite3_reset()] on the
4109 ** [prepared statement].  ^In the "v2" interface,
4110 ** the more specific error code is returned directly by sqlite3_step().
4111 **
4112 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4113 ** Perhaps it was called on a [prepared statement] that has
4114 ** already been [sqlite3_finalize | finalized] or on one that had
4115 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4116 ** be the case that the same database connection is being used by two or
4117 ** more threads at the same moment in time.
4118 **
4119 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4120 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4121 ** other than [SQLITE_ROW] before any subsequent invocation of
4122 ** sqlite3_step().  Failure to reset the prepared statement using
4123 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4124 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4125 ** calling [sqlite3_reset()] automatically in this circumstance rather
4126 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4127 ** break because any application that ever receives an SQLITE_MISUSE error
4128 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4129 ** can be used to restore the legacy behavior.
4130 **
4131 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4132 ** API always returns a generic error code, [SQLITE_ERROR], following any
4133 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4134 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4135 ** specific [error codes] that better describes the error.
4136 ** We admit that this is a goofy design.  The problem has been fixed
4137 ** with the "v2" interface.  If you prepare all of your SQL statements
4138 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4139 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4140 ** then the more specific [error codes] are returned directly
4141 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4142 */
4143 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4144 
4145 /*
4146 ** CAPI3REF: Number of columns in a result set
4147 **
4148 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4149 ** current row of the result set of [prepared statement] P.
4150 ** ^If prepared statement P does not have results ready to return
4151 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4152 ** interfaces) then sqlite3_data_count(P) returns 0.
4153 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4154 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4155 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4156 ** will return non-zero if previous call to [sqlite3_step](P) returned
4157 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4158 ** where it always returns zero since each step of that multi-step
4159 ** pragma returns 0 columns of data.
4160 **
4161 ** See also: [sqlite3_column_count()]
4162 */
4163 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4164 
4165 /*
4166 ** CAPI3REF: Fundamental Datatypes
4167 ** KEYWORDS: SQLITE_TEXT
4168 **
4169 ** ^(Every value in SQLite has one of five fundamental datatypes:
4170 **
4171 ** <ul>
4172 ** <li> 64-bit signed integer
4173 ** <li> 64-bit IEEE floating point number
4174 ** <li> string
4175 ** <li> BLOB
4176 ** <li> NULL
4177 ** </ul>)^
4178 **
4179 ** These constants are codes for each of those types.
4180 **
4181 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4182 ** for a completely different meaning.  Software that links against both
4183 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4184 ** SQLITE_TEXT.
4185 */
4186 #define SQLITE_INTEGER  1
4187 #define SQLITE_FLOAT    2
4188 #define SQLITE_BLOB     4
4189 #define SQLITE_NULL     5
4190 #ifdef SQLITE_TEXT
4191 # undef SQLITE_TEXT
4192 #else
4193 # define SQLITE_TEXT     3
4194 #endif
4195 #define SQLITE3_TEXT     3
4196 
4197 /*
4198 ** CAPI3REF: Result Values From A Query
4199 ** KEYWORDS: {column access functions}
4200 **
4201 ** These routines form the "result set" interface.
4202 **
4203 ** ^These routines return information about a single column of the current
4204 ** result row of a query.  ^In every case the first argument is a pointer
4205 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4206 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4207 ** and the second argument is the index of the column for which information
4208 ** should be returned. ^The leftmost column of the result set has the index 0.
4209 ** ^The number of columns in the result can be determined using
4210 ** [sqlite3_column_count()].
4211 **
4212 ** If the SQL statement does not currently point to a valid row, or if the
4213 ** column index is out of range, the result is undefined.
4214 ** These routines may only be called when the most recent call to
4215 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4216 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4217 ** If any of these routines are called after [sqlite3_reset()] or
4218 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4219 ** something other than [SQLITE_ROW], the results are undefined.
4220 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4221 ** are called from a different thread while any of these routines
4222 ** are pending, then the results are undefined.
4223 **
4224 ** ^The sqlite3_column_type() routine returns the
4225 ** [SQLITE_INTEGER | datatype code] for the initial data type
4226 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4227 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4228 ** returned by sqlite3_column_type() is only meaningful if no type
4229 ** conversions have occurred as described below.  After a type conversion,
4230 ** the value returned by sqlite3_column_type() is undefined.  Future
4231 ** versions of SQLite may change the behavior of sqlite3_column_type()
4232 ** following a type conversion.
4233 **
4234 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4235 ** routine returns the number of bytes in that BLOB or string.
4236 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4237 ** the string to UTF-8 and then returns the number of bytes.
4238 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4239 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4240 ** the number of bytes in that string.
4241 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4242 **
4243 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4244 ** routine returns the number of bytes in that BLOB or string.
4245 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4246 ** the string to UTF-16 and then returns the number of bytes.
4247 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4248 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4249 ** the number of bytes in that string.
4250 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4251 **
4252 ** ^The values returned by [sqlite3_column_bytes()] and
4253 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4254 ** of the string.  ^For clarity: the values returned by
4255 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4256 ** bytes in the string, not the number of characters.
4257 **
4258 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4259 ** even empty strings, are always zero-terminated.  ^The return
4260 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4261 **
4262 ** ^The object returned by [sqlite3_column_value()] is an
4263 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4264 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4265 ** If the [unprotected sqlite3_value] object returned by
4266 ** [sqlite3_column_value()] is used in any other way, including calls
4267 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4268 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4269 **
4270 ** These routines attempt to convert the value where appropriate.  ^For
4271 ** example, if the internal representation is FLOAT and a text result
4272 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4273 ** conversion automatically.  ^(The following table details the conversions
4274 ** that are applied:
4275 **
4276 ** <blockquote>
4277 ** <table border="1">
4278 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4279 **
4280 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4281 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4282 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4283 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4284 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4285 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4286 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4287 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4288 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4289 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4290 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4291 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4292 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4293 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4294 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4295 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4296 ** </table>
4297 ** </blockquote>)^
4298 **
4299 ** The table above makes reference to standard C library functions atoi()
4300 ** and atof().  SQLite does not really use these functions.  It has its
4301 ** own equivalent internal routines.  The atoi() and atof() names are
4302 ** used in the table for brevity and because they are familiar to most
4303 ** C programmers.
4304 **
4305 ** Note that when type conversions occur, pointers returned by prior
4306 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4307 ** sqlite3_column_text16() may be invalidated.
4308 ** Type conversions and pointer invalidations might occur
4309 ** in the following cases:
4310 **
4311 ** <ul>
4312 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4313 **      sqlite3_column_text16() is called.  A zero-terminator might
4314 **      need to be added to the string.</li>
4315 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4316 **      sqlite3_column_text16() is called.  The content must be converted
4317 **      to UTF-16.</li>
4318 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4319 **      sqlite3_column_text() is called.  The content must be converted
4320 **      to UTF-8.</li>
4321 ** </ul>
4322 **
4323 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4324 ** not invalidate a prior pointer, though of course the content of the buffer
4325 ** that the prior pointer references will have been modified.  Other kinds
4326 ** of conversion are done in place when it is possible, but sometimes they
4327 ** are not possible and in those cases prior pointers are invalidated.
4328 **
4329 ** The safest and easiest to remember policy is to invoke these routines
4330 ** in one of the following ways:
4331 **
4332 ** <ul>
4333 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4334 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4335 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4336 ** </ul>
4337 **
4338 ** In other words, you should call sqlite3_column_text(),
4339 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4340 ** into the desired format, then invoke sqlite3_column_bytes() or
4341 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4342 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4343 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4344 ** with calls to sqlite3_column_bytes().
4345 **
4346 ** ^The pointers returned are valid until a type conversion occurs as
4347 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4348 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4349 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4350 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4351 ** [sqlite3_free()].
4352 **
4353 ** ^(If a memory allocation error occurs during the evaluation of any
4354 ** of these routines, a default value is returned.  The default value
4355 ** is either the integer 0, the floating point number 0.0, or a NULL
4356 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4357 ** [SQLITE_NOMEM].)^
4358 */
4359 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4360 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4361 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4362 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4363 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4364 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4365 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4366 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4367 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4368 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4369 
4370 /*
4371 ** CAPI3REF: Destroy A Prepared Statement Object
4372 **
4373 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4374 ** ^If the most recent evaluation of the statement encountered no errors
4375 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4376 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4377 ** sqlite3_finalize(S) returns the appropriate [error code] or
4378 ** [extended error code].
4379 **
4380 ** ^The sqlite3_finalize(S) routine can be called at any point during
4381 ** the life cycle of [prepared statement] S:
4382 ** before statement S is ever evaluated, after
4383 ** one or more calls to [sqlite3_reset()], or after any call
4384 ** to [sqlite3_step()] regardless of whether or not the statement has
4385 ** completed execution.
4386 **
4387 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4388 **
4389 ** The application must finalize every [prepared statement] in order to avoid
4390 ** resource leaks.  It is a grievous error for the application to try to use
4391 ** a prepared statement after it has been finalized.  Any use of a prepared
4392 ** statement after it has been finalized can result in undefined and
4393 ** undesirable behavior such as segfaults and heap corruption.
4394 */
4395 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4396 
4397 /*
4398 ** CAPI3REF: Reset A Prepared Statement Object
4399 **
4400 ** The sqlite3_reset() function is called to reset a [prepared statement]
4401 ** object back to its initial state, ready to be re-executed.
4402 ** ^Any SQL statement variables that had values bound to them using
4403 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4404 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4405 **
4406 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4407 ** back to the beginning of its program.
4408 **
4409 ** ^If the most recent call to [sqlite3_step(S)] for the
4410 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4411 ** or if [sqlite3_step(S)] has never before been called on S,
4412 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4413 **
4414 ** ^If the most recent call to [sqlite3_step(S)] for the
4415 ** [prepared statement] S indicated an error, then
4416 ** [sqlite3_reset(S)] returns an appropriate [error code].
4417 **
4418 ** ^The [sqlite3_reset(S)] interface does not change the values
4419 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4420 */
4421 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4422 
4423 /*
4424 ** CAPI3REF: Create Or Redefine SQL Functions
4425 ** KEYWORDS: {function creation routines}
4426 ** KEYWORDS: {application-defined SQL function}
4427 ** KEYWORDS: {application-defined SQL functions}
4428 **
4429 ** ^These functions (collectively known as "function creation routines")
4430 ** are used to add SQL functions or aggregates or to redefine the behavior
4431 ** of existing SQL functions or aggregates.  The only differences between
4432 ** these routines are the text encoding expected for
4433 ** the second parameter (the name of the function being created)
4434 ** and the presence or absence of a destructor callback for
4435 ** the application data pointer.
4436 **
4437 ** ^The first parameter is the [database connection] to which the SQL
4438 ** function is to be added.  ^If an application uses more than one database
4439 ** connection then application-defined SQL functions must be added
4440 ** to each database connection separately.
4441 **
4442 ** ^The second parameter is the name of the SQL function to be created or
4443 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4444 ** representation, exclusive of the zero-terminator.  ^Note that the name
4445 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4446 ** ^Any attempt to create a function with a longer name
4447 ** will result in [SQLITE_MISUSE] being returned.
4448 **
4449 ** ^The third parameter (nArg)
4450 ** is the number of arguments that the SQL function or
4451 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4452 ** aggregate may take any number of arguments between 0 and the limit
4453 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4454 ** parameter is less than -1 or greater than 127 then the behavior is
4455 ** undefined.
4456 **
4457 ** ^The fourth parameter, eTextRep, specifies what
4458 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4459 ** its parameters.  Every SQL function implementation must be able to work
4460 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4461 ** more efficient with one encoding than another.  ^An application may
4462 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4463 ** times with the same function but with different values of eTextRep.
4464 ** ^When multiple implementations of the same function are available, SQLite
4465 ** will pick the one that involves the least amount of data conversion.
4466 ** If there is only a single implementation which does not care what text
4467 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4468 **
4469 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4470 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4471 **
4472 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4473 ** pointers to C-language functions that implement the SQL function or
4474 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4475 ** callback only; NULL pointers must be passed as the xStep and xFinal
4476 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4477 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4478 ** SQL function or aggregate, pass NULL pointers for all three function
4479 ** callbacks.
4480 **
4481 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4482 ** then it is destructor for the application data pointer.
4483 ** The destructor is invoked when the function is deleted, either by being
4484 ** overloaded or when the database connection closes.)^
4485 ** ^The destructor is also invoked if the call to
4486 ** sqlite3_create_function_v2() fails.
4487 ** ^When the destructor callback of the tenth parameter is invoked, it
4488 ** is passed a single argument which is a copy of the application data
4489 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4490 **
4491 ** ^It is permitted to register multiple implementations of the same
4492 ** functions with the same name but with either differing numbers of
4493 ** arguments or differing preferred text encodings.  ^SQLite will use
4494 ** the implementation that most closely matches the way in which the
4495 ** SQL function is used.  ^A function implementation with a non-negative
4496 ** nArg parameter is a better match than a function implementation with
4497 ** a negative nArg.  ^A function where the preferred text encoding
4498 ** matches the database encoding is a better
4499 ** match than a function where the encoding is different.
4500 ** ^A function where the encoding difference is between UTF16le and UTF16be
4501 ** is a closer match than a function where the encoding difference is
4502 ** between UTF8 and UTF16.
4503 **
4504 ** ^Built-in functions may be overloaded by new application-defined functions.
4505 **
4506 ** ^An application-defined function is permitted to call other
4507 ** SQLite interfaces.  However, such calls must not
4508 ** close the database connection nor finalize or reset the prepared
4509 ** statement in which the function is running.
4510 */
4511 SQLITE_API int sqlite3_create_function(
4512   sqlite3 *db,
4513   const char *zFunctionName,
4514   int nArg,
4515   int eTextRep,
4516   void *pApp,
4517   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4518   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4519   void (*xFinal)(sqlite3_context*)
4520 );
4521 SQLITE_API int sqlite3_create_function16(
4522   sqlite3 *db,
4523   const void *zFunctionName,
4524   int nArg,
4525   int eTextRep,
4526   void *pApp,
4527   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4528   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4529   void (*xFinal)(sqlite3_context*)
4530 );
4531 SQLITE_API int sqlite3_create_function_v2(
4532   sqlite3 *db,
4533   const char *zFunctionName,
4534   int nArg,
4535   int eTextRep,
4536   void *pApp,
4537   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4538   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4539   void (*xFinal)(sqlite3_context*),
4540   void(*xDestroy)(void*)
4541 );
4542 
4543 /*
4544 ** CAPI3REF: Text Encodings
4545 **
4546 ** These constant define integer codes that represent the various
4547 ** text encodings supported by SQLite.
4548 */
4549 #define SQLITE_UTF8           1
4550 #define SQLITE_UTF16LE        2
4551 #define SQLITE_UTF16BE        3
4552 #define SQLITE_UTF16          4    /* Use native byte order */
4553 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4554 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4555 
4556 /*
4557 ** CAPI3REF: Deprecated Functions
4558 ** DEPRECATED
4559 **
4560 ** These functions are [deprecated].  In order to maintain
4561 ** backwards compatibility with older code, these functions continue
4562 ** to be supported.  However, new applications should avoid
4563 ** the use of these functions.  To help encourage people to avoid
4564 ** using these functions, we are not going to tell you what they do.
4565 */
4566 #ifndef SQLITE_OMIT_DEPRECATED
4567 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4568 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4569 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4570 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4571 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4572 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4573                       void*,sqlite3_int64);
4574 #endif
4575 
4576 /*
4577 ** CAPI3REF: Obtaining SQL Function Parameter Values
4578 **
4579 ** The C-language implementation of SQL functions and aggregates uses
4580 ** this set of interface routines to access the parameter values on
4581 ** the function or aggregate.
4582 **
4583 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4584 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4585 ** define callbacks that implement the SQL functions and aggregates.
4586 ** The 3rd parameter to these callbacks is an array of pointers to
4587 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4588 ** each parameter to the SQL function.  These routines are used to
4589 ** extract values from the [sqlite3_value] objects.
4590 **
4591 ** These routines work only with [protected sqlite3_value] objects.
4592 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4593 ** object results in undefined behavior.
4594 **
4595 ** ^These routines work just like the corresponding [column access functions]
4596 ** except that  these routines take a single [protected sqlite3_value] object
4597 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4598 **
4599 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4600 ** in the native byte-order of the host machine.  ^The
4601 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4602 ** extract UTF-16 strings as big-endian and little-endian respectively.
4603 **
4604 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4605 ** numeric affinity to the value.  This means that an attempt is
4606 ** made to convert the value to an integer or floating point.  If
4607 ** such a conversion is possible without loss of information (in other
4608 ** words, if the value is a string that looks like a number)
4609 ** then the conversion is performed.  Otherwise no conversion occurs.
4610 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4611 **
4612 ** Please pay particular attention to the fact that the pointer returned
4613 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4614 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4615 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4616 ** or [sqlite3_value_text16()].
4617 **
4618 ** These routines must be called from the same thread as
4619 ** the SQL function that supplied the [sqlite3_value*] parameters.
4620 */
4621 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4622 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4623 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4624 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4625 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4626 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4627 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4628 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4629 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4630 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4631 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4632 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4633 
4634 /*
4635 ** CAPI3REF: Obtain Aggregate Function Context
4636 **
4637 ** Implementations of aggregate SQL functions use this
4638 ** routine to allocate memory for storing their state.
4639 **
4640 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4641 ** for a particular aggregate function, SQLite
4642 ** allocates N of memory, zeroes out that memory, and returns a pointer
4643 ** to the new memory. ^On second and subsequent calls to
4644 ** sqlite3_aggregate_context() for the same aggregate function instance,
4645 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4646 ** called once for each invocation of the xStep callback and then one
4647 ** last time when the xFinal callback is invoked.  ^(When no rows match
4648 ** an aggregate query, the xStep() callback of the aggregate function
4649 ** implementation is never called and xFinal() is called exactly once.
4650 ** In those cases, sqlite3_aggregate_context() might be called for the
4651 ** first time from within xFinal().)^
4652 **
4653 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4654 ** when first called if N is less than or equal to zero or if a memory
4655 ** allocate error occurs.
4656 **
4657 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4658 ** determined by the N parameter on first successful call.  Changing the
4659 ** value of N in subsequent call to sqlite3_aggregate_context() within
4660 ** the same aggregate function instance will not resize the memory
4661 ** allocation.)^  Within the xFinal callback, it is customary to set
4662 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4663 ** pointless memory allocations occur.
4664 **
4665 ** ^SQLite automatically frees the memory allocated by
4666 ** sqlite3_aggregate_context() when the aggregate query concludes.
4667 **
4668 ** The first parameter must be a copy of the
4669 ** [sqlite3_context | SQL function context] that is the first parameter
4670 ** to the xStep or xFinal callback routine that implements the aggregate
4671 ** function.
4672 **
4673 ** This routine must be called from the same thread in which
4674 ** the aggregate SQL function is running.
4675 */
4676 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4677 
4678 /*
4679 ** CAPI3REF: User Data For Functions
4680 **
4681 ** ^The sqlite3_user_data() interface returns a copy of
4682 ** the pointer that was the pUserData parameter (the 5th parameter)
4683 ** of the [sqlite3_create_function()]
4684 ** and [sqlite3_create_function16()] routines that originally
4685 ** registered the application defined function.
4686 **
4687 ** This routine must be called from the same thread in which
4688 ** the application-defined function is running.
4689 */
4690 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4691 
4692 /*
4693 ** CAPI3REF: Database Connection For Functions
4694 **
4695 ** ^The sqlite3_context_db_handle() interface returns a copy of
4696 ** the pointer to the [database connection] (the 1st parameter)
4697 ** of the [sqlite3_create_function()]
4698 ** and [sqlite3_create_function16()] routines that originally
4699 ** registered the application defined function.
4700 */
4701 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4702 
4703 /*
4704 ** CAPI3REF: Function Auxiliary Data
4705 **
4706 ** The following two functions may be used by scalar SQL functions to
4707 ** associate metadata with argument values. If the same value is passed to
4708 ** multiple invocations of the same SQL function during query execution, under
4709 ** some circumstances the associated metadata may be preserved. This may
4710 ** be used, for example, to add a regular-expression matching scalar
4711 ** function. The compiled version of the regular expression is stored as
4712 ** metadata associated with the SQL value passed as the regular expression
4713 ** pattern.  The compiled regular expression can be reused on multiple
4714 ** invocations of the same function so that the original pattern string
4715 ** does not need to be recompiled on each invocation.
4716 **
4717 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4718 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4719 ** value to the application-defined function. ^If no metadata has been ever
4720 ** been set for the Nth argument of the function, or if the corresponding
4721 ** function parameter has changed since the meta-data was set,
4722 ** then sqlite3_get_auxdata() returns a NULL pointer.
4723 **
4724 ** ^The sqlite3_set_auxdata() interface saves the metadata
4725 ** pointed to by its 3rd parameter as the metadata for the N-th
4726 ** argument of the application-defined function.  Subsequent
4727 ** calls to sqlite3_get_auxdata() might return this data, if it has
4728 ** not been destroyed.
4729 ** ^If it is not NULL, SQLite will invoke the destructor
4730 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4731 ** the metadata when the corresponding function parameter changes
4732 ** or when the SQL statement completes, whichever comes first.
4733 **
4734 ** SQLite is free to call the destructor and drop metadata on any
4735 ** parameter of any function at any time.  ^The only guarantee is that
4736 ** the destructor will be called before the metadata is dropped.
4737 **
4738 ** ^(In practice, metadata is preserved between function calls for
4739 ** expressions that are constant at compile time. This includes literal
4740 ** values and [parameters].)^
4741 **
4742 ** These routines must be called from the same thread in which
4743 ** the SQL function is running.
4744 */
4745 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4746 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4747 
4748 
4749 /*
4750 ** CAPI3REF: Constants Defining Special Destructor Behavior
4751 **
4752 ** These are special values for the destructor that is passed in as the
4753 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4754 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4755 ** and will never change.  It does not need to be destroyed.  ^The
4756 ** SQLITE_TRANSIENT value means that the content will likely change in
4757 ** the near future and that SQLite should make its own private copy of
4758 ** the content before returning.
4759 **
4760 ** The typedef is necessary to work around problems in certain
4761 ** C++ compilers.  See ticket #2191.
4762 */
4763 typedef void (*sqlite3_destructor_type)(void*);
4764 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4765 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4766 
4767 /*
4768 ** CAPI3REF: Setting The Result Of An SQL Function
4769 **
4770 ** These routines are used by the xFunc or xFinal callbacks that
4771 ** implement SQL functions and aggregates.  See
4772 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4773 ** for additional information.
4774 **
4775 ** These functions work very much like the [parameter binding] family of
4776 ** functions used to bind values to host parameters in prepared statements.
4777 ** Refer to the [SQL parameter] documentation for additional information.
4778 **
4779 ** ^The sqlite3_result_blob() interface sets the result from
4780 ** an application-defined function to be the BLOB whose content is pointed
4781 ** to by the second parameter and which is N bytes long where N is the
4782 ** third parameter.
4783 **
4784 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4785 ** the application-defined function to be a BLOB containing all zero
4786 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4787 **
4788 ** ^The sqlite3_result_double() interface sets the result from
4789 ** an application-defined function to be a floating point value specified
4790 ** by its 2nd argument.
4791 **
4792 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4793 ** cause the implemented SQL function to throw an exception.
4794 ** ^SQLite uses the string pointed to by the
4795 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4796 ** as the text of an error message.  ^SQLite interprets the error
4797 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4798 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4799 ** byte order.  ^If the third parameter to sqlite3_result_error()
4800 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4801 ** message all text up through the first zero character.
4802 ** ^If the third parameter to sqlite3_result_error() or
4803 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4804 ** bytes (not characters) from the 2nd parameter as the error message.
4805 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4806 ** routines make a private copy of the error message text before
4807 ** they return.  Hence, the calling function can deallocate or
4808 ** modify the text after they return without harm.
4809 ** ^The sqlite3_result_error_code() function changes the error code
4810 ** returned by SQLite as a result of an error in a function.  ^By default,
4811 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4812 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4813 **
4814 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4815 ** error indicating that a string or BLOB is too long to represent.
4816 **
4817 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4818 ** error indicating that a memory allocation failed.
4819 **
4820 ** ^The sqlite3_result_int() interface sets the return value
4821 ** of the application-defined function to be the 32-bit signed integer
4822 ** value given in the 2nd argument.
4823 ** ^The sqlite3_result_int64() interface sets the return value
4824 ** of the application-defined function to be the 64-bit signed integer
4825 ** value given in the 2nd argument.
4826 **
4827 ** ^The sqlite3_result_null() interface sets the return value
4828 ** of the application-defined function to be NULL.
4829 **
4830 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4831 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4832 ** set the return value of the application-defined function to be
4833 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4834 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4835 ** ^SQLite takes the text result from the application from
4836 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4837 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4838 ** is negative, then SQLite takes result text from the 2nd parameter
4839 ** through the first zero character.
4840 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4841 ** is non-negative, then as many bytes (not characters) of the text
4842 ** pointed to by the 2nd parameter are taken as the application-defined
4843 ** function result.  If the 3rd parameter is non-negative, then it
4844 ** must be the byte offset into the string where the NUL terminator would
4845 ** appear if the string where NUL terminated.  If any NUL characters occur
4846 ** in the string at a byte offset that is less than the value of the 3rd
4847 ** parameter, then the resulting string will contain embedded NULs and the
4848 ** result of expressions operating on strings with embedded NULs is undefined.
4849 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4850 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4851 ** function as the destructor on the text or BLOB result when it has
4852 ** finished using that result.
4853 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4854 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4855 ** assumes that the text or BLOB result is in constant space and does not
4856 ** copy the content of the parameter nor call a destructor on the content
4857 ** when it has finished using that result.
4858 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4859 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4860 ** then SQLite makes a copy of the result into space obtained from
4861 ** from [sqlite3_malloc()] before it returns.
4862 **
4863 ** ^The sqlite3_result_value() interface sets the result of
4864 ** the application-defined function to be a copy the
4865 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4866 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4867 ** so that the [sqlite3_value] specified in the parameter may change or
4868 ** be deallocated after sqlite3_result_value() returns without harm.
4869 ** ^A [protected sqlite3_value] object may always be used where an
4870 ** [unprotected sqlite3_value] object is required, so either
4871 ** kind of [sqlite3_value] object can be used with this interface.
4872 **
4873 ** If these routines are called from within the different thread
4874 ** than the one containing the application-defined function that received
4875 ** the [sqlite3_context] pointer, the results are undefined.
4876 */
4877 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4878 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4879 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4880 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4881 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4882 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4883 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4884 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4885 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4886 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4887 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4888 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4889 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4890 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4891 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4892 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4893 
4894 /*
4895 ** CAPI3REF: Define New Collating Sequences
4896 **
4897 ** ^These functions add, remove, or modify a [collation] associated
4898 ** with the [database connection] specified as the first argument.
4899 **
4900 ** ^The name of the collation is a UTF-8 string
4901 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4902 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4903 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4904 ** considered to be the same name.
4905 **
4906 ** ^(The third argument (eTextRep) must be one of the constants:
4907 ** <ul>
4908 ** <li> [SQLITE_UTF8],
4909 ** <li> [SQLITE_UTF16LE],
4910 ** <li> [SQLITE_UTF16BE],
4911 ** <li> [SQLITE_UTF16], or
4912 ** <li> [SQLITE_UTF16_ALIGNED].
4913 ** </ul>)^
4914 ** ^The eTextRep argument determines the encoding of strings passed
4915 ** to the collating function callback, xCallback.
4916 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4917 ** force strings to be UTF16 with native byte order.
4918 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4919 ** on an even byte address.
4920 **
4921 ** ^The fourth argument, pArg, is an application data pointer that is passed
4922 ** through as the first argument to the collating function callback.
4923 **
4924 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4925 ** ^Multiple collating functions can be registered using the same name but
4926 ** with different eTextRep parameters and SQLite will use whichever
4927 ** function requires the least amount of data transformation.
4928 ** ^If the xCallback argument is NULL then the collating function is
4929 ** deleted.  ^When all collating functions having the same name are deleted,
4930 ** that collation is no longer usable.
4931 **
4932 ** ^The collating function callback is invoked with a copy of the pArg
4933 ** application data pointer and with two strings in the encoding specified
4934 ** by the eTextRep argument.  The collating function must return an
4935 ** integer that is negative, zero, or positive
4936 ** if the first string is less than, equal to, or greater than the second,
4937 ** respectively.  A collating function must always return the same answer
4938 ** given the same inputs.  If two or more collating functions are registered
4939 ** to the same collation name (using different eTextRep values) then all
4940 ** must give an equivalent answer when invoked with equivalent strings.
4941 ** The collating function must obey the following properties for all
4942 ** strings A, B, and C:
4943 **
4944 ** <ol>
4945 ** <li> If A==B then B==A.
4946 ** <li> If A==B and B==C then A==C.
4947 ** <li> If A&lt;B THEN B&gt;A.
4948 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4949 ** </ol>
4950 **
4951 ** If a collating function fails any of the above constraints and that
4952 ** collating function is  registered and used, then the behavior of SQLite
4953 ** is undefined.
4954 **
4955 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4956 ** with the addition that the xDestroy callback is invoked on pArg when
4957 ** the collating function is deleted.
4958 ** ^Collating functions are deleted when they are overridden by later
4959 ** calls to the collation creation functions or when the
4960 ** [database connection] is closed using [sqlite3_close()].
4961 **
4962 ** ^The xDestroy callback is <u>not</u> called if the
4963 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4964 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4965 ** check the return code and dispose of the application data pointer
4966 ** themselves rather than expecting SQLite to deal with it for them.
4967 ** This is different from every other SQLite interface.  The inconsistency
4968 ** is unfortunate but cannot be changed without breaking backwards
4969 ** compatibility.
4970 **
4971 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4972 */
4973 SQLITE_API int sqlite3_create_collation(
4974   sqlite3*,
4975   const char *zName,
4976   int eTextRep,
4977   void *pArg,
4978   int(*xCompare)(void*,int,const void*,int,const void*)
4979 );
4980 SQLITE_API int sqlite3_create_collation_v2(
4981   sqlite3*,
4982   const char *zName,
4983   int eTextRep,
4984   void *pArg,
4985   int(*xCompare)(void*,int,const void*,int,const void*),
4986   void(*xDestroy)(void*)
4987 );
4988 SQLITE_API int sqlite3_create_collation16(
4989   sqlite3*,
4990   const void *zName,
4991   int eTextRep,
4992   void *pArg,
4993   int(*xCompare)(void*,int,const void*,int,const void*)
4994 );
4995 
4996 /*
4997 ** CAPI3REF: Collation Needed Callbacks
4998 **
4999 ** ^To avoid having to register all collation sequences before a database
5000 ** can be used, a single callback function may be registered with the
5001 ** [database connection] to be invoked whenever an undefined collation
5002 ** sequence is required.
5003 **
5004 ** ^If the function is registered using the sqlite3_collation_needed() API,
5005 ** then it is passed the names of undefined collation sequences as strings
5006 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5007 ** the names are passed as UTF-16 in machine native byte order.
5008 ** ^A call to either function replaces the existing collation-needed callback.
5009 **
5010 ** ^(When the callback is invoked, the first argument passed is a copy
5011 ** of the second argument to sqlite3_collation_needed() or
5012 ** sqlite3_collation_needed16().  The second argument is the database
5013 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5014 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5015 ** sequence function required.  The fourth parameter is the name of the
5016 ** required collation sequence.)^
5017 **
5018 ** The callback function should register the desired collation using
5019 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5020 ** [sqlite3_create_collation_v2()].
5021 */
5022 SQLITE_API int sqlite3_collation_needed(
5023   sqlite3*,
5024   void*,
5025   void(*)(void*,sqlite3*,int eTextRep,const char*)
5026 );
5027 SQLITE_API int sqlite3_collation_needed16(
5028   sqlite3*,
5029   void*,
5030   void(*)(void*,sqlite3*,int eTextRep,const void*)
5031 );
5032 
5033 #ifdef SQLITE_HAS_CODEC
5034 /*
5035 ** Specify the key for an encrypted database.  This routine should be
5036 ** called right after sqlite3_open().
5037 **
5038 ** The code to implement this API is not available in the public release
5039 ** of SQLite.
5040 */
5041 SQLITE_API int sqlite3_key(
5042   sqlite3 *db,                   /* Database to be rekeyed */
5043   const void *pKey, int nKey     /* The key */
5044 );
5045 
5046 /*
5047 ** Change the key on an open database.  If the current database is not
5048 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5049 ** database is decrypted.
5050 **
5051 ** The code to implement this API is not available in the public release
5052 ** of SQLite.
5053 */
5054 SQLITE_API int sqlite3_rekey(
5055   sqlite3 *db,                   /* Database to be rekeyed */
5056   const void *pKey, int nKey     /* The new key */
5057 );
5058 
5059 /*
5060 ** Specify the activation key for a SEE database.  Unless
5061 ** activated, none of the SEE routines will work.
5062 */
5063 SQLITE_API void sqlite3_activate_see(
5064   const char *zPassPhrase        /* Activation phrase */
5065 );
5066 #endif
5067 
5068 #ifdef SQLITE_ENABLE_CEROD
5069 /*
5070 ** Specify the activation key for a CEROD database.  Unless
5071 ** activated, none of the CEROD routines will work.
5072 */
5073 SQLITE_API void sqlite3_activate_cerod(
5074   const char *zPassPhrase        /* Activation phrase */
5075 );
5076 #endif
5077 
5078 /*
5079 ** CAPI3REF: Suspend Execution For A Short Time
5080 **
5081 ** The sqlite3_sleep() function causes the current thread to suspend execution
5082 ** for at least a number of milliseconds specified in its parameter.
5083 **
5084 ** If the operating system does not support sleep requests with
5085 ** millisecond time resolution, then the time will be rounded up to
5086 ** the nearest second. The number of milliseconds of sleep actually
5087 ** requested from the operating system is returned.
5088 **
5089 ** ^SQLite implements this interface by calling the xSleep()
5090 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5091 ** of the default VFS is not implemented correctly, or not implemented at
5092 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5093 ** in the previous paragraphs.
5094 */
5095 SQLITE_API int sqlite3_sleep(int);
5096 
5097 /*
5098 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5099 **
5100 ** ^(If this global variable is made to point to a string which is
5101 ** the name of a folder (a.k.a. directory), then all temporary files
5102 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5103 ** will be placed in that directory.)^  ^If this variable
5104 ** is a NULL pointer, then SQLite performs a search for an appropriate
5105 ** temporary file directory.
5106 **
5107 ** It is not safe to read or modify this variable in more than one
5108 ** thread at a time.  It is not safe to read or modify this variable
5109 ** if a [database connection] is being used at the same time in a separate
5110 ** thread.
5111 ** It is intended that this variable be set once
5112 ** as part of process initialization and before any SQLite interface
5113 ** routines have been called and that this variable remain unchanged
5114 ** thereafter.
5115 **
5116 ** ^The [temp_store_directory pragma] may modify this variable and cause
5117 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5118 ** the [temp_store_directory pragma] always assumes that any string
5119 ** that this variable points to is held in memory obtained from
5120 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5121 ** using [sqlite3_free].
5122 ** Hence, if this variable is modified directly, either it should be
5123 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5124 ** or else the use of the [temp_store_directory pragma] should be avoided.
5125 **
5126 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5127 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5128 ** features that require the use of temporary files may fail.  Here is an
5129 ** example of how to do this using C++ with the Windows Runtime:
5130 **
5131 ** <blockquote><pre>
5132 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5133 ** &nbsp;     TemporaryFolder->Path->Data();
5134 ** char zPathBuf[MAX_PATH + 1];
5135 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5136 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5137 ** &nbsp;     NULL, NULL);
5138 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5139 ** </pre></blockquote>
5140 */
5141 SQLITE_API char *sqlite3_temp_directory;
5142 
5143 /*
5144 ** CAPI3REF: Name Of The Folder Holding Database Files
5145 **
5146 ** ^(If this global variable is made to point to a string which is
5147 ** the name of a folder (a.k.a. directory), then all database files
5148 ** specified with a relative pathname and created or accessed by
5149 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5150 ** to be relative to that directory.)^ ^If this variable is a NULL
5151 ** pointer, then SQLite assumes that all database files specified
5152 ** with a relative pathname are relative to the current directory
5153 ** for the process.  Only the windows VFS makes use of this global
5154 ** variable; it is ignored by the unix VFS.
5155 **
5156 ** Changing the value of this variable while a database connection is
5157 ** open can result in a corrupt database.
5158 **
5159 ** It is not safe to read or modify this variable in more than one
5160 ** thread at a time.  It is not safe to read or modify this variable
5161 ** if a [database connection] is being used at the same time in a separate
5162 ** thread.
5163 ** It is intended that this variable be set once
5164 ** as part of process initialization and before any SQLite interface
5165 ** routines have been called and that this variable remain unchanged
5166 ** thereafter.
5167 **
5168 ** ^The [data_store_directory pragma] may modify this variable and cause
5169 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5170 ** the [data_store_directory pragma] always assumes that any string
5171 ** that this variable points to is held in memory obtained from
5172 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5173 ** using [sqlite3_free].
5174 ** Hence, if this variable is modified directly, either it should be
5175 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5176 ** or else the use of the [data_store_directory pragma] should be avoided.
5177 */
5178 SQLITE_API char *sqlite3_data_directory;
5179 
5180 /*
5181 ** CAPI3REF: Test For Auto-Commit Mode
5182 ** KEYWORDS: {autocommit mode}
5183 **
5184 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5185 ** zero if the given database connection is or is not in autocommit mode,
5186 ** respectively.  ^Autocommit mode is on by default.
5187 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5188 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5189 **
5190 ** If certain kinds of errors occur on a statement within a multi-statement
5191 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5192 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5193 ** transaction might be rolled back automatically.  The only way to
5194 ** find out whether SQLite automatically rolled back the transaction after
5195 ** an error is to use this function.
5196 **
5197 ** If another thread changes the autocommit status of the database
5198 ** connection while this routine is running, then the return value
5199 ** is undefined.
5200 */
5201 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5202 
5203 /*
5204 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5205 **
5206 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5207 ** to which a [prepared statement] belongs.  ^The [database connection]
5208 ** returned by sqlite3_db_handle is the same [database connection]
5209 ** that was the first argument
5210 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5211 ** create the statement in the first place.
5212 */
5213 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5214 
5215 /*
5216 ** CAPI3REF: Return The Filename For A Database Connection
5217 **
5218 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5219 ** associated with database N of connection D.  ^The main database file
5220 ** has the name "main".  If there is no attached database N on the database
5221 ** connection D, or if database N is a temporary or in-memory database, then
5222 ** a NULL pointer is returned.
5223 **
5224 ** ^The filename returned by this function is the output of the
5225 ** xFullPathname method of the [VFS].  ^In other words, the filename
5226 ** will be an absolute pathname, even if the filename used
5227 ** to open the database originally was a URI or relative pathname.
5228 */
5229 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5230 
5231 /*
5232 ** CAPI3REF: Determine if a database is read-only
5233 **
5234 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5235 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5236 ** the name of a database on connection D.
5237 */
5238 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5239 
5240 /*
5241 ** CAPI3REF: Find the next prepared statement
5242 **
5243 ** ^This interface returns a pointer to the next [prepared statement] after
5244 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5245 ** then this interface returns a pointer to the first prepared statement
5246 ** associated with the database connection pDb.  ^If no prepared statement
5247 ** satisfies the conditions of this routine, it returns NULL.
5248 **
5249 ** The [database connection] pointer D in a call to
5250 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5251 ** connection and in particular must not be a NULL pointer.
5252 */
5253 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5254 
5255 /*
5256 ** CAPI3REF: Commit And Rollback Notification Callbacks
5257 **
5258 ** ^The sqlite3_commit_hook() interface registers a callback
5259 ** function to be invoked whenever a transaction is [COMMIT | committed].
5260 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5261 ** for the same database connection is overridden.
5262 ** ^The sqlite3_rollback_hook() interface registers a callback
5263 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5264 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5265 ** for the same database connection is overridden.
5266 ** ^The pArg argument is passed through to the callback.
5267 ** ^If the callback on a commit hook function returns non-zero,
5268 ** then the commit is converted into a rollback.
5269 **
5270 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5271 ** return the P argument from the previous call of the same function
5272 ** on the same [database connection] D, or NULL for
5273 ** the first call for each function on D.
5274 **
5275 ** The commit and rollback hook callbacks are not reentrant.
5276 ** The callback implementation must not do anything that will modify
5277 ** the database connection that invoked the callback.  Any actions
5278 ** to modify the database connection must be deferred until after the
5279 ** completion of the [sqlite3_step()] call that triggered the commit
5280 ** or rollback hook in the first place.
5281 ** Note that running any other SQL statements, including SELECT statements,
5282 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5283 ** the database connections for the meaning of "modify" in this paragraph.
5284 **
5285 ** ^Registering a NULL function disables the callback.
5286 **
5287 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5288 ** operation is allowed to continue normally.  ^If the commit hook
5289 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5290 ** ^The rollback hook is invoked on a rollback that results from a commit
5291 ** hook returning non-zero, just as it would be with any other rollback.
5292 **
5293 ** ^For the purposes of this API, a transaction is said to have been
5294 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5295 ** an error or constraint causes an implicit rollback to occur.
5296 ** ^The rollback callback is not invoked if a transaction is
5297 ** automatically rolled back because the database connection is closed.
5298 **
5299 ** See also the [sqlite3_update_hook()] interface.
5300 */
5301 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5302 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5303 
5304 /*
5305 ** CAPI3REF: Data Change Notification Callbacks
5306 **
5307 ** ^The sqlite3_update_hook() interface registers a callback function
5308 ** with the [database connection] identified by the first argument
5309 ** to be invoked whenever a row is updated, inserted or deleted.
5310 ** ^Any callback set by a previous call to this function
5311 ** for the same database connection is overridden.
5312 **
5313 ** ^The second argument is a pointer to the function to invoke when a
5314 ** row is updated, inserted or deleted.
5315 ** ^The first argument to the callback is a copy of the third argument
5316 ** to sqlite3_update_hook().
5317 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5318 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5319 ** to be invoked.
5320 ** ^The third and fourth arguments to the callback contain pointers to the
5321 ** database and table name containing the affected row.
5322 ** ^The final callback parameter is the [rowid] of the row.
5323 ** ^In the case of an update, this is the [rowid] after the update takes place.
5324 **
5325 ** ^(The update hook is not invoked when internal system tables are
5326 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5327 **
5328 ** ^In the current implementation, the update hook
5329 ** is not invoked when duplication rows are deleted because of an
5330 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5331 ** invoked when rows are deleted using the [truncate optimization].
5332 ** The exceptions defined in this paragraph might change in a future
5333 ** release of SQLite.
5334 **
5335 ** The update hook implementation must not do anything that will modify
5336 ** the database connection that invoked the update hook.  Any actions
5337 ** to modify the database connection must be deferred until after the
5338 ** completion of the [sqlite3_step()] call that triggered the update hook.
5339 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5340 ** database connections for the meaning of "modify" in this paragraph.
5341 **
5342 ** ^The sqlite3_update_hook(D,C,P) function
5343 ** returns the P argument from the previous call
5344 ** on the same [database connection] D, or NULL for
5345 ** the first call on D.
5346 **
5347 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5348 ** interfaces.
5349 */
5350 SQLITE_API void *sqlite3_update_hook(
5351   sqlite3*,
5352   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5353   void*
5354 );
5355 
5356 /*
5357 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5358 **
5359 ** ^(This routine enables or disables the sharing of the database cache
5360 ** and schema data structures between [database connection | connections]
5361 ** to the same database. Sharing is enabled if the argument is true
5362 ** and disabled if the argument is false.)^
5363 **
5364 ** ^Cache sharing is enabled and disabled for an entire process.
5365 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5366 ** sharing was enabled or disabled for each thread separately.
5367 **
5368 ** ^(The cache sharing mode set by this interface effects all subsequent
5369 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5370 ** Existing database connections continue use the sharing mode
5371 ** that was in effect at the time they were opened.)^
5372 **
5373 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5374 ** successfully.  An [error code] is returned otherwise.)^
5375 **
5376 ** ^Shared cache is disabled by default. But this might change in
5377 ** future releases of SQLite.  Applications that care about shared
5378 ** cache setting should set it explicitly.
5379 **
5380 ** This interface is threadsafe on processors where writing a
5381 ** 32-bit integer is atomic.
5382 **
5383 ** See Also:  [SQLite Shared-Cache Mode]
5384 */
5385 SQLITE_API int sqlite3_enable_shared_cache(int);
5386 
5387 /*
5388 ** CAPI3REF: Attempt To Free Heap Memory
5389 **
5390 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5391 ** of heap memory by deallocating non-essential memory allocations
5392 ** held by the database library.   Memory used to cache database
5393 ** pages to improve performance is an example of non-essential memory.
5394 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5395 ** which might be more or less than the amount requested.
5396 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5397 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5398 **
5399 ** See also: [sqlite3_db_release_memory()]
5400 */
5401 SQLITE_API int sqlite3_release_memory(int);
5402 
5403 /*
5404 ** CAPI3REF: Free Memory Used By A Database Connection
5405 **
5406 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5407 ** memory as possible from database connection D. Unlike the
5408 ** [sqlite3_release_memory()] interface, this interface is effect even
5409 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5410 ** omitted.
5411 **
5412 ** See also: [sqlite3_release_memory()]
5413 */
5414 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5415 
5416 /*
5417 ** CAPI3REF: Impose A Limit On Heap Size
5418 **
5419 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5420 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5421 ** ^SQLite strives to keep heap memory utilization below the soft heap
5422 ** limit by reducing the number of pages held in the page cache
5423 ** as heap memory usages approaches the limit.
5424 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5425 ** below the limit, it will exceed the limit rather than generate
5426 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5427 ** is advisory only.
5428 **
5429 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5430 ** the soft heap limit prior to the call, or negative in the case of an
5431 ** error.  ^If the argument N is negative
5432 ** then no change is made to the soft heap limit.  Hence, the current
5433 ** size of the soft heap limit can be determined by invoking
5434 ** sqlite3_soft_heap_limit64() with a negative argument.
5435 **
5436 ** ^If the argument N is zero then the soft heap limit is disabled.
5437 **
5438 ** ^(The soft heap limit is not enforced in the current implementation
5439 ** if one or more of following conditions are true:
5440 **
5441 ** <ul>
5442 ** <li> The soft heap limit is set to zero.
5443 ** <li> Memory accounting is disabled using a combination of the
5444 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5445 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5446 ** <li> An alternative page cache implementation is specified using
5447 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5448 ** <li> The page cache allocates from its own memory pool supplied
5449 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5450 **      from the heap.
5451 ** </ul>)^
5452 **
5453 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5454 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5455 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5456 ** the soft heap limit is enforced on every memory allocation.  Without
5457 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5458 ** when memory is allocated by the page cache.  Testing suggests that because
5459 ** the page cache is the predominate memory user in SQLite, most
5460 ** applications will achieve adequate soft heap limit enforcement without
5461 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5462 **
5463 ** The circumstances under which SQLite will enforce the soft heap limit may
5464 ** changes in future releases of SQLite.
5465 */
5466 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5467 
5468 /*
5469 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5470 ** DEPRECATED
5471 **
5472 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5473 ** interface.  This routine is provided for historical compatibility
5474 ** only.  All new applications should use the
5475 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5476 */
5477 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5478 
5479 
5480 /*
5481 ** CAPI3REF: Extract Metadata About A Column Of A Table
5482 **
5483 ** ^This routine returns metadata about a specific column of a specific
5484 ** database table accessible using the [database connection] handle
5485 ** passed as the first function argument.
5486 **
5487 ** ^The column is identified by the second, third and fourth parameters to
5488 ** this function. ^The second parameter is either the name of the database
5489 ** (i.e. "main", "temp", or an attached database) containing the specified
5490 ** table or NULL. ^If it is NULL, then all attached databases are searched
5491 ** for the table using the same algorithm used by the database engine to
5492 ** resolve unqualified table references.
5493 **
5494 ** ^The third and fourth parameters to this function are the table and column
5495 ** name of the desired column, respectively. Neither of these parameters
5496 ** may be NULL.
5497 **
5498 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5499 ** and subsequent parameters to this function. ^Any of these arguments may be
5500 ** NULL, in which case the corresponding element of metadata is omitted.
5501 **
5502 ** ^(<blockquote>
5503 ** <table border="1">
5504 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5505 **
5506 ** <tr><td> 5th <td> const char* <td> Data type
5507 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5508 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5509 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5510 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5511 ** </table>
5512 ** </blockquote>)^
5513 **
5514 ** ^The memory pointed to by the character pointers returned for the
5515 ** declaration type and collation sequence is valid only until the next
5516 ** call to any SQLite API function.
5517 **
5518 ** ^If the specified table is actually a view, an [error code] is returned.
5519 **
5520 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5521 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5522 ** parameters are set for the explicitly declared column. ^(If there is no
5523 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5524 ** parameters are set as follows:
5525 **
5526 ** <pre>
5527 **     data type: "INTEGER"
5528 **     collation sequence: "BINARY"
5529 **     not null: 0
5530 **     primary key: 1
5531 **     auto increment: 0
5532 ** </pre>)^
5533 **
5534 ** ^(This function may load one or more schemas from database files. If an
5535 ** error occurs during this process, or if the requested table or column
5536 ** cannot be found, an [error code] is returned and an error message left
5537 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5538 **
5539 ** ^This API is only available if the library was compiled with the
5540 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5541 */
5542 SQLITE_API int sqlite3_table_column_metadata(
5543   sqlite3 *db,                /* Connection handle */
5544   const char *zDbName,        /* Database name or NULL */
5545   const char *zTableName,     /* Table name */
5546   const char *zColumnName,    /* Column name */
5547   char const **pzDataType,    /* OUTPUT: Declared data type */
5548   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5549   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5550   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5551   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5552 );
5553 
5554 /*
5555 ** CAPI3REF: Load An Extension
5556 **
5557 ** ^This interface loads an SQLite extension library from the named file.
5558 **
5559 ** ^The sqlite3_load_extension() interface attempts to load an
5560 ** SQLite extension library contained in the file zFile.
5561 **
5562 ** ^The entry point is zProc.
5563 ** ^zProc may be 0, in which case the name of the entry point
5564 ** defaults to "sqlite3_extension_init".
5565 ** ^The sqlite3_load_extension() interface returns
5566 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5567 ** ^If an error occurs and pzErrMsg is not 0, then the
5568 ** [sqlite3_load_extension()] interface shall attempt to
5569 ** fill *pzErrMsg with error message text stored in memory
5570 ** obtained from [sqlite3_malloc()]. The calling function
5571 ** should free this memory by calling [sqlite3_free()].
5572 **
5573 ** ^Extension loading must be enabled using
5574 ** [sqlite3_enable_load_extension()] prior to calling this API,
5575 ** otherwise an error will be returned.
5576 **
5577 ** See also the [load_extension() SQL function].
5578 */
5579 SQLITE_API int sqlite3_load_extension(
5580   sqlite3 *db,          /* Load the extension into this database connection */
5581   const char *zFile,    /* Name of the shared library containing extension */
5582   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5583   char **pzErrMsg       /* Put error message here if not 0 */
5584 );
5585 
5586 /*
5587 ** CAPI3REF: Enable Or Disable Extension Loading
5588 **
5589 ** ^So as not to open security holes in older applications that are
5590 ** unprepared to deal with extension loading, and as a means of disabling
5591 ** extension loading while evaluating user-entered SQL, the following API
5592 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5593 **
5594 ** ^Extension loading is off by default. See ticket #1863.
5595 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5596 ** to turn extension loading on and call it with onoff==0 to turn
5597 ** it back off again.
5598 */
5599 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5600 
5601 /*
5602 ** CAPI3REF: Automatically Load Statically Linked Extensions
5603 **
5604 ** ^This interface causes the xEntryPoint() function to be invoked for
5605 ** each new [database connection] that is created.  The idea here is that
5606 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5607 ** that is to be automatically loaded into all new database connections.
5608 **
5609 ** ^(Even though the function prototype shows that xEntryPoint() takes
5610 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5611 ** arguments and expects and integer result as if the signature of the
5612 ** entry point where as follows:
5613 **
5614 ** <blockquote><pre>
5615 ** &nbsp;  int xEntryPoint(
5616 ** &nbsp;    sqlite3 *db,
5617 ** &nbsp;    const char **pzErrMsg,
5618 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5619 ** &nbsp;  );
5620 ** </pre></blockquote>)^
5621 **
5622 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5623 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5624 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5625 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5626 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5627 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5628 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5629 **
5630 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5631 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5632 ** will be called more than once for each database connection that is opened.
5633 **
5634 ** See also: [sqlite3_reset_auto_extension()].
5635 */
5636 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5637 
5638 /*
5639 ** CAPI3REF: Reset Automatic Extension Loading
5640 **
5641 ** ^This interface disables all automatic extensions previously
5642 ** registered using [sqlite3_auto_extension()].
5643 */
5644 SQLITE_API void sqlite3_reset_auto_extension(void);
5645 
5646 /*
5647 ** The interface to the virtual-table mechanism is currently considered
5648 ** to be experimental.  The interface might change in incompatible ways.
5649 ** If this is a problem for you, do not use the interface at this time.
5650 **
5651 ** When the virtual-table mechanism stabilizes, we will declare the
5652 ** interface fixed, support it indefinitely, and remove this comment.
5653 */
5654 
5655 /*
5656 ** Structures used by the virtual table interface
5657 */
5658 typedef struct sqlite3_vtab sqlite3_vtab;
5659 typedef struct sqlite3_index_info sqlite3_index_info;
5660 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5661 typedef struct sqlite3_module sqlite3_module;
5662 
5663 /*
5664 ** CAPI3REF: Virtual Table Object
5665 ** KEYWORDS: sqlite3_module {virtual table module}
5666 **
5667 ** This structure, sometimes called a "virtual table module",
5668 ** defines the implementation of a [virtual tables].
5669 ** This structure consists mostly of methods for the module.
5670 **
5671 ** ^A virtual table module is created by filling in a persistent
5672 ** instance of this structure and passing a pointer to that instance
5673 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5674 ** ^The registration remains valid until it is replaced by a different
5675 ** module or until the [database connection] closes.  The content
5676 ** of this structure must not change while it is registered with
5677 ** any database connection.
5678 */
5679 struct sqlite3_module {
5680   int iVersion;
5681   int (*xCreate)(sqlite3*, void *pAux,
5682                int argc, const char *const*argv,
5683                sqlite3_vtab **ppVTab, char**);
5684   int (*xConnect)(sqlite3*, void *pAux,
5685                int argc, const char *const*argv,
5686                sqlite3_vtab **ppVTab, char**);
5687   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5688   int (*xDisconnect)(sqlite3_vtab *pVTab);
5689   int (*xDestroy)(sqlite3_vtab *pVTab);
5690   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5691   int (*xClose)(sqlite3_vtab_cursor*);
5692   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5693                 int argc, sqlite3_value **argv);
5694   int (*xNext)(sqlite3_vtab_cursor*);
5695   int (*xEof)(sqlite3_vtab_cursor*);
5696   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5697   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5698   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5699   int (*xBegin)(sqlite3_vtab *pVTab);
5700   int (*xSync)(sqlite3_vtab *pVTab);
5701   int (*xCommit)(sqlite3_vtab *pVTab);
5702   int (*xRollback)(sqlite3_vtab *pVTab);
5703   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5704                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5705                        void **ppArg);
5706   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5707   /* The methods above are in version 1 of the sqlite_module object. Those
5708   ** below are for version 2 and greater. */
5709   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5710   int (*xRelease)(sqlite3_vtab *pVTab, int);
5711   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5712 };
5713 
5714 /*
5715 ** CAPI3REF: Virtual Table Indexing Information
5716 ** KEYWORDS: sqlite3_index_info
5717 **
5718 ** The sqlite3_index_info structure and its substructures is used as part
5719 ** of the [virtual table] interface to
5720 ** pass information into and receive the reply from the [xBestIndex]
5721 ** method of a [virtual table module].  The fields under **Inputs** are the
5722 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5723 ** results into the **Outputs** fields.
5724 **
5725 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5726 **
5727 ** <blockquote>column OP expr</blockquote>
5728 **
5729 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5730 ** stored in aConstraint[].op using one of the
5731 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5732 ** ^(The index of the column is stored in
5733 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5734 ** expr on the right-hand side can be evaluated (and thus the constraint
5735 ** is usable) and false if it cannot.)^
5736 **
5737 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5738 ** and makes other simplifications to the WHERE clause in an attempt to
5739 ** get as many WHERE clause terms into the form shown above as possible.
5740 ** ^The aConstraint[] array only reports WHERE clause terms that are
5741 ** relevant to the particular virtual table being queried.
5742 **
5743 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5744 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5745 **
5746 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5747 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5748 ** the right-hand side of the corresponding aConstraint[] is evaluated
5749 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5750 ** is true, then the constraint is assumed to be fully handled by the
5751 ** virtual table and is not checked again by SQLite.)^
5752 **
5753 ** ^The idxNum and idxPtr values are recorded and passed into the
5754 ** [xFilter] method.
5755 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5756 ** needToFreeIdxPtr is true.
5757 **
5758 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5759 ** the correct order to satisfy the ORDER BY clause so that no separate
5760 ** sorting step is required.
5761 **
5762 ** ^The estimatedCost value is an estimate of the cost of doing the
5763 ** particular lookup.  A full scan of a table with N entries should have
5764 ** a cost of N.  A binary search of a table of N entries should have a
5765 ** cost of approximately log(N).
5766 */
5767 struct sqlite3_index_info {
5768   /* Inputs */
5769   int nConstraint;           /* Number of entries in aConstraint */
5770   struct sqlite3_index_constraint {
5771      int iColumn;              /* Column on left-hand side of constraint */
5772      unsigned char op;         /* Constraint operator */
5773      unsigned char usable;     /* True if this constraint is usable */
5774      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5775   } *aConstraint;            /* Table of WHERE clause constraints */
5776   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5777   struct sqlite3_index_orderby {
5778      int iColumn;              /* Column number */
5779      unsigned char desc;       /* True for DESC.  False for ASC. */
5780   } *aOrderBy;               /* The ORDER BY clause */
5781   /* Outputs */
5782   struct sqlite3_index_constraint_usage {
5783     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5784     unsigned char omit;      /* Do not code a test for this constraint */
5785   } *aConstraintUsage;
5786   int idxNum;                /* Number used to identify the index */
5787   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5788   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5789   int orderByConsumed;       /* True if output is already ordered */
5790   double estimatedCost;      /* Estimated cost of using this index */
5791 };
5792 
5793 /*
5794 ** CAPI3REF: Virtual Table Constraint Operator Codes
5795 **
5796 ** These macros defined the allowed values for the
5797 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5798 ** an operator that is part of a constraint term in the wHERE clause of
5799 ** a query that uses a [virtual table].
5800 */
5801 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5802 #define SQLITE_INDEX_CONSTRAINT_GT    4
5803 #define SQLITE_INDEX_CONSTRAINT_LE    8
5804 #define SQLITE_INDEX_CONSTRAINT_LT    16
5805 #define SQLITE_INDEX_CONSTRAINT_GE    32
5806 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5807 
5808 /*
5809 ** CAPI3REF: Register A Virtual Table Implementation
5810 **
5811 ** ^These routines are used to register a new [virtual table module] name.
5812 ** ^Module names must be registered before
5813 ** creating a new [virtual table] using the module and before using a
5814 ** preexisting [virtual table] for the module.
5815 **
5816 ** ^The module name is registered on the [database connection] specified
5817 ** by the first parameter.  ^The name of the module is given by the
5818 ** second parameter.  ^The third parameter is a pointer to
5819 ** the implementation of the [virtual table module].   ^The fourth
5820 ** parameter is an arbitrary client data pointer that is passed through
5821 ** into the [xCreate] and [xConnect] methods of the virtual table module
5822 ** when a new virtual table is be being created or reinitialized.
5823 **
5824 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5825 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5826 ** invoke the destructor function (if it is not NULL) when SQLite
5827 ** no longer needs the pClientData pointer.  ^The destructor will also
5828 ** be invoked if the call to sqlite3_create_module_v2() fails.
5829 ** ^The sqlite3_create_module()
5830 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5831 ** destructor.
5832 */
5833 SQLITE_API int sqlite3_create_module(
5834   sqlite3 *db,               /* SQLite connection to register module with */
5835   const char *zName,         /* Name of the module */
5836   const sqlite3_module *p,   /* Methods for the module */
5837   void *pClientData          /* Client data for xCreate/xConnect */
5838 );
5839 SQLITE_API int sqlite3_create_module_v2(
5840   sqlite3 *db,               /* SQLite connection to register module with */
5841   const char *zName,         /* Name of the module */
5842   const sqlite3_module *p,   /* Methods for the module */
5843   void *pClientData,         /* Client data for xCreate/xConnect */
5844   void(*xDestroy)(void*)     /* Module destructor function */
5845 );
5846 
5847 /*
5848 ** CAPI3REF: Virtual Table Instance Object
5849 ** KEYWORDS: sqlite3_vtab
5850 **
5851 ** Every [virtual table module] implementation uses a subclass
5852 ** of this object to describe a particular instance
5853 ** of the [virtual table].  Each subclass will
5854 ** be tailored to the specific needs of the module implementation.
5855 ** The purpose of this superclass is to define certain fields that are
5856 ** common to all module implementations.
5857 **
5858 ** ^Virtual tables methods can set an error message by assigning a
5859 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5860 ** take care that any prior string is freed by a call to [sqlite3_free()]
5861 ** prior to assigning a new string to zErrMsg.  ^After the error message
5862 ** is delivered up to the client application, the string will be automatically
5863 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5864 */
5865 struct sqlite3_vtab {
5866   const sqlite3_module *pModule;  /* The module for this virtual table */
5867   int nRef;                       /* NO LONGER USED */
5868   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5869   /* Virtual table implementations will typically add additional fields */
5870 };
5871 
5872 /*
5873 ** CAPI3REF: Virtual Table Cursor Object
5874 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5875 **
5876 ** Every [virtual table module] implementation uses a subclass of the
5877 ** following structure to describe cursors that point into the
5878 ** [virtual table] and are used
5879 ** to loop through the virtual table.  Cursors are created using the
5880 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5881 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5882 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5883 ** of the module.  Each module implementation will define
5884 ** the content of a cursor structure to suit its own needs.
5885 **
5886 ** This superclass exists in order to define fields of the cursor that
5887 ** are common to all implementations.
5888 */
5889 struct sqlite3_vtab_cursor {
5890   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5891   /* Virtual table implementations will typically add additional fields */
5892 };
5893 
5894 /*
5895 ** CAPI3REF: Declare The Schema Of A Virtual Table
5896 **
5897 ** ^The [xCreate] and [xConnect] methods of a
5898 ** [virtual table module] call this interface
5899 ** to declare the format (the names and datatypes of the columns) of
5900 ** the virtual tables they implement.
5901 */
5902 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5903 
5904 /*
5905 ** CAPI3REF: Overload A Function For A Virtual Table
5906 **
5907 ** ^(Virtual tables can provide alternative implementations of functions
5908 ** using the [xFindFunction] method of the [virtual table module].
5909 ** But global versions of those functions
5910 ** must exist in order to be overloaded.)^
5911 **
5912 ** ^(This API makes sure a global version of a function with a particular
5913 ** name and number of parameters exists.  If no such function exists
5914 ** before this API is called, a new function is created.)^  ^The implementation
5915 ** of the new function always causes an exception to be thrown.  So
5916 ** the new function is not good for anything by itself.  Its only
5917 ** purpose is to be a placeholder function that can be overloaded
5918 ** by a [virtual table].
5919 */
5920 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5921 
5922 /*
5923 ** The interface to the virtual-table mechanism defined above (back up
5924 ** to a comment remarkably similar to this one) is currently considered
5925 ** to be experimental.  The interface might change in incompatible ways.
5926 ** If this is a problem for you, do not use the interface at this time.
5927 **
5928 ** When the virtual-table mechanism stabilizes, we will declare the
5929 ** interface fixed, support it indefinitely, and remove this comment.
5930 */
5931 
5932 /*
5933 ** CAPI3REF: A Handle To An Open BLOB
5934 ** KEYWORDS: {BLOB handle} {BLOB handles}
5935 **
5936 ** An instance of this object represents an open BLOB on which
5937 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5938 ** ^Objects of this type are created by [sqlite3_blob_open()]
5939 ** and destroyed by [sqlite3_blob_close()].
5940 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5941 ** can be used to read or write small subsections of the BLOB.
5942 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5943 */
5944 typedef struct sqlite3_blob sqlite3_blob;
5945 
5946 /*
5947 ** CAPI3REF: Open A BLOB For Incremental I/O
5948 **
5949 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5950 ** in row iRow, column zColumn, table zTable in database zDb;
5951 ** in other words, the same BLOB that would be selected by:
5952 **
5953 ** <pre>
5954 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5955 ** </pre>)^
5956 **
5957 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5958 ** and write access. ^If it is zero, the BLOB is opened for read access.
5959 ** ^It is not possible to open a column that is part of an index or primary
5960 ** key for writing. ^If [foreign key constraints] are enabled, it is
5961 ** not possible to open a column that is part of a [child key] for writing.
5962 **
5963 ** ^Note that the database name is not the filename that contains
5964 ** the database but rather the symbolic name of the database that
5965 ** appears after the AS keyword when the database is connected using [ATTACH].
5966 ** ^For the main database file, the database name is "main".
5967 ** ^For TEMP tables, the database name is "temp".
5968 **
5969 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5970 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5971 ** to be a null pointer.)^
5972 ** ^This function sets the [database connection] error code and message
5973 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5974 ** functions. ^Note that the *ppBlob variable is always initialized in a
5975 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5976 ** regardless of the success or failure of this routine.
5977 **
5978 ** ^(If the row that a BLOB handle points to is modified by an
5979 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5980 ** then the BLOB handle is marked as "expired".
5981 ** This is true if any column of the row is changed, even a column
5982 ** other than the one the BLOB handle is open on.)^
5983 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5984 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5985 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5986 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5987 ** commit if the transaction continues to completion.)^
5988 **
5989 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5990 ** the opened blob.  ^The size of a blob may not be changed by this
5991 ** interface.  Use the [UPDATE] SQL command to change the size of a
5992 ** blob.
5993 **
5994 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5995 ** and the built-in [zeroblob] SQL function can be used, if desired,
5996 ** to create an empty, zero-filled blob in which to read or write using
5997 ** this interface.
5998 **
5999 ** To avoid a resource leak, every open [BLOB handle] should eventually
6000 ** be released by a call to [sqlite3_blob_close()].
6001 */
6002 SQLITE_API int sqlite3_blob_open(
6003   sqlite3*,
6004   const char *zDb,
6005   const char *zTable,
6006   const char *zColumn,
6007   sqlite3_int64 iRow,
6008   int flags,
6009   sqlite3_blob **ppBlob
6010 );
6011 
6012 /*
6013 ** CAPI3REF: Move a BLOB Handle to a New Row
6014 **
6015 ** ^This function is used to move an existing blob handle so that it points
6016 ** to a different row of the same database table. ^The new row is identified
6017 ** by the rowid value passed as the second argument. Only the row can be
6018 ** changed. ^The database, table and column on which the blob handle is open
6019 ** remain the same. Moving an existing blob handle to a new row can be
6020 ** faster than closing the existing handle and opening a new one.
6021 **
6022 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6023 ** it must exist and there must be either a blob or text value stored in
6024 ** the nominated column.)^ ^If the new row is not present in the table, or if
6025 ** it does not contain a blob or text value, or if another error occurs, an
6026 ** SQLite error code is returned and the blob handle is considered aborted.
6027 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6028 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6029 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6030 ** always returns zero.
6031 **
6032 ** ^This function sets the database handle error code and message.
6033 */
6034 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6035 
6036 /*
6037 ** CAPI3REF: Close A BLOB Handle
6038 **
6039 ** ^Closes an open [BLOB handle].
6040 **
6041 ** ^Closing a BLOB shall cause the current transaction to commit
6042 ** if there are no other BLOBs, no pending prepared statements, and the
6043 ** database connection is in [autocommit mode].
6044 ** ^If any writes were made to the BLOB, they might be held in cache
6045 ** until the close operation if they will fit.
6046 **
6047 ** ^(Closing the BLOB often forces the changes
6048 ** out to disk and so if any I/O errors occur, they will likely occur
6049 ** at the time when the BLOB is closed.  Any errors that occur during
6050 ** closing are reported as a non-zero return value.)^
6051 **
6052 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
6053 ** an error code, the BLOB is still closed.)^
6054 **
6055 ** ^Calling this routine with a null pointer (such as would be returned
6056 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
6057 */
6058 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6059 
6060 /*
6061 ** CAPI3REF: Return The Size Of An Open BLOB
6062 **
6063 ** ^Returns the size in bytes of the BLOB accessible via the
6064 ** successfully opened [BLOB handle] in its only argument.  ^The
6065 ** incremental blob I/O routines can only read or overwriting existing
6066 ** blob content; they cannot change the size of a blob.
6067 **
6068 ** This routine only works on a [BLOB handle] which has been created
6069 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6070 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6071 ** to this routine results in undefined and probably undesirable behavior.
6072 */
6073 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6074 
6075 /*
6076 ** CAPI3REF: Read Data From A BLOB Incrementally
6077 **
6078 ** ^(This function is used to read data from an open [BLOB handle] into a
6079 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6080 ** from the open BLOB, starting at offset iOffset.)^
6081 **
6082 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6083 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6084 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6085 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6086 ** can be determined using the [sqlite3_blob_bytes()] interface.
6087 **
6088 ** ^An attempt to read from an expired [BLOB handle] fails with an
6089 ** error code of [SQLITE_ABORT].
6090 **
6091 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6092 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6093 **
6094 ** This routine only works on a [BLOB handle] which has been created
6095 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6096 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6097 ** to this routine results in undefined and probably undesirable behavior.
6098 **
6099 ** See also: [sqlite3_blob_write()].
6100 */
6101 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6102 
6103 /*
6104 ** CAPI3REF: Write Data Into A BLOB Incrementally
6105 **
6106 ** ^This function is used to write data into an open [BLOB handle] from a
6107 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6108 ** into the open BLOB, starting at offset iOffset.
6109 **
6110 ** ^If the [BLOB handle] passed as the first argument was not opened for
6111 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6112 ** this function returns [SQLITE_READONLY].
6113 **
6114 ** ^This function may only modify the contents of the BLOB; it is
6115 ** not possible to increase the size of a BLOB using this API.
6116 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6117 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
6118 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6119 ** The size of the BLOB (and hence the maximum value of N+iOffset)
6120 ** can be determined using the [sqlite3_blob_bytes()] interface.
6121 **
6122 ** ^An attempt to write to an expired [BLOB handle] fails with an
6123 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6124 ** before the [BLOB handle] expired are not rolled back by the
6125 ** expiration of the handle, though of course those changes might
6126 ** have been overwritten by the statement that expired the BLOB handle
6127 ** or by other independent statements.
6128 **
6129 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6130 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6131 **
6132 ** This routine only works on a [BLOB handle] which has been created
6133 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6134 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6135 ** to this routine results in undefined and probably undesirable behavior.
6136 **
6137 ** See also: [sqlite3_blob_read()].
6138 */
6139 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6140 
6141 /*
6142 ** CAPI3REF: Virtual File System Objects
6143 **
6144 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6145 ** that SQLite uses to interact
6146 ** with the underlying operating system.  Most SQLite builds come with a
6147 ** single default VFS that is appropriate for the host computer.
6148 ** New VFSes can be registered and existing VFSes can be unregistered.
6149 ** The following interfaces are provided.
6150 **
6151 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6152 ** ^Names are case sensitive.
6153 ** ^Names are zero-terminated UTF-8 strings.
6154 ** ^If there is no match, a NULL pointer is returned.
6155 ** ^If zVfsName is NULL then the default VFS is returned.
6156 **
6157 ** ^New VFSes are registered with sqlite3_vfs_register().
6158 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6159 ** ^The same VFS can be registered multiple times without injury.
6160 ** ^To make an existing VFS into the default VFS, register it again
6161 ** with the makeDflt flag set.  If two different VFSes with the
6162 ** same name are registered, the behavior is undefined.  If a
6163 ** VFS is registered with a name that is NULL or an empty string,
6164 ** then the behavior is undefined.
6165 **
6166 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6167 ** ^(If the default VFS is unregistered, another VFS is chosen as
6168 ** the default.  The choice for the new VFS is arbitrary.)^
6169 */
6170 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6171 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6172 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6173 
6174 /*
6175 ** CAPI3REF: Mutexes
6176 **
6177 ** The SQLite core uses these routines for thread
6178 ** synchronization. Though they are intended for internal
6179 ** use by SQLite, code that links against SQLite is
6180 ** permitted to use any of these routines.
6181 **
6182 ** The SQLite source code contains multiple implementations
6183 ** of these mutex routines.  An appropriate implementation
6184 ** is selected automatically at compile-time.  ^(The following
6185 ** implementations are available in the SQLite core:
6186 **
6187 ** <ul>
6188 ** <li>   SQLITE_MUTEX_PTHREADS
6189 ** <li>   SQLITE_MUTEX_W32
6190 ** <li>   SQLITE_MUTEX_NOOP
6191 ** </ul>)^
6192 **
6193 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6194 ** that does no real locking and is appropriate for use in
6195 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6196 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6197 ** and Windows.
6198 **
6199 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6200 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6201 ** implementation is included with the library. In this case the
6202 ** application must supply a custom mutex implementation using the
6203 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6204 ** before calling sqlite3_initialize() or any other public sqlite3_
6205 ** function that calls sqlite3_initialize().)^
6206 **
6207 ** ^The sqlite3_mutex_alloc() routine allocates a new
6208 ** mutex and returns a pointer to it. ^If it returns NULL
6209 ** that means that a mutex could not be allocated.  ^SQLite
6210 ** will unwind its stack and return an error.  ^(The argument
6211 ** to sqlite3_mutex_alloc() is one of these integer constants:
6212 **
6213 ** <ul>
6214 ** <li>  SQLITE_MUTEX_FAST
6215 ** <li>  SQLITE_MUTEX_RECURSIVE
6216 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6217 ** <li>  SQLITE_MUTEX_STATIC_MEM
6218 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6219 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6220 ** <li>  SQLITE_MUTEX_STATIC_LRU
6221 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6222 ** </ul>)^
6223 **
6224 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6225 ** cause sqlite3_mutex_alloc() to create
6226 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6227 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6228 ** The mutex implementation does not need to make a distinction
6229 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6230 ** not want to.  ^SQLite will only request a recursive mutex in
6231 ** cases where it really needs one.  ^If a faster non-recursive mutex
6232 ** implementation is available on the host platform, the mutex subsystem
6233 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6234 **
6235 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6236 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6237 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6238 ** used by the current version of SQLite.  Future versions of SQLite
6239 ** may add additional static mutexes.  Static mutexes are for internal
6240 ** use by SQLite only.  Applications that use SQLite mutexes should
6241 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6242 ** SQLITE_MUTEX_RECURSIVE.
6243 **
6244 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6245 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6246 ** returns a different mutex on every call.  ^But for the static
6247 ** mutex types, the same mutex is returned on every call that has
6248 ** the same type number.
6249 **
6250 ** ^The sqlite3_mutex_free() routine deallocates a previously
6251 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6252 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6253 ** use when they are deallocated.  Attempting to deallocate a static
6254 ** mutex results in undefined behavior.  ^SQLite never deallocates
6255 ** a static mutex.
6256 **
6257 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6258 ** to enter a mutex.  ^If another thread is already within the mutex,
6259 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6260 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6261 ** upon successful entry.  ^(Mutexes created using
6262 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6263 ** In such cases the,
6264 ** mutex must be exited an equal number of times before another thread
6265 ** can enter.)^  ^(If the same thread tries to enter any other
6266 ** kind of mutex more than once, the behavior is undefined.
6267 ** SQLite will never exhibit
6268 ** such behavior in its own use of mutexes.)^
6269 **
6270 ** ^(Some systems (for example, Windows 95) do not support the operation
6271 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6272 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6273 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6274 **
6275 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6276 ** previously entered by the same thread.   ^(The behavior
6277 ** is undefined if the mutex is not currently entered by the
6278 ** calling thread or is not currently allocated.  SQLite will
6279 ** never do either.)^
6280 **
6281 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6282 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6283 ** behave as no-ops.
6284 **
6285 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6286 */
6287 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6288 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6289 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6290 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6291 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6292 
6293 /*
6294 ** CAPI3REF: Mutex Methods Object
6295 **
6296 ** An instance of this structure defines the low-level routines
6297 ** used to allocate and use mutexes.
6298 **
6299 ** Usually, the default mutex implementations provided by SQLite are
6300 ** sufficient, however the user has the option of substituting a custom
6301 ** implementation for specialized deployments or systems for which SQLite
6302 ** does not provide a suitable implementation. In this case, the user
6303 ** creates and populates an instance of this structure to pass
6304 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6305 ** Additionally, an instance of this structure can be used as an
6306 ** output variable when querying the system for the current mutex
6307 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6308 **
6309 ** ^The xMutexInit method defined by this structure is invoked as
6310 ** part of system initialization by the sqlite3_initialize() function.
6311 ** ^The xMutexInit routine is called by SQLite exactly once for each
6312 ** effective call to [sqlite3_initialize()].
6313 **
6314 ** ^The xMutexEnd method defined by this structure is invoked as
6315 ** part of system shutdown by the sqlite3_shutdown() function. The
6316 ** implementation of this method is expected to release all outstanding
6317 ** resources obtained by the mutex methods implementation, especially
6318 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6319 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6320 **
6321 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6322 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6323 ** xMutexNotheld) implement the following interfaces (respectively):
6324 **
6325 ** <ul>
6326 **   <li>  [sqlite3_mutex_alloc()] </li>
6327 **   <li>  [sqlite3_mutex_free()] </li>
6328 **   <li>  [sqlite3_mutex_enter()] </li>
6329 **   <li>  [sqlite3_mutex_try()] </li>
6330 **   <li>  [sqlite3_mutex_leave()] </li>
6331 **   <li>  [sqlite3_mutex_held()] </li>
6332 **   <li>  [sqlite3_mutex_notheld()] </li>
6333 ** </ul>)^
6334 **
6335 ** The only difference is that the public sqlite3_XXX functions enumerated
6336 ** above silently ignore any invocations that pass a NULL pointer instead
6337 ** of a valid mutex handle. The implementations of the methods defined
6338 ** by this structure are not required to handle this case, the results
6339 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6340 ** (i.e. it is acceptable to provide an implementation that segfaults if
6341 ** it is passed a NULL pointer).
6342 **
6343 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6344 ** invoke xMutexInit() multiple times within the same process and without
6345 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6346 ** xMutexInit() must be no-ops.
6347 **
6348 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6349 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6350 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6351 ** memory allocation for a fast or recursive mutex.
6352 **
6353 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6354 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6355 ** If xMutexInit fails in any way, it is expected to clean up after itself
6356 ** prior to returning.
6357 */
6358 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6359 struct sqlite3_mutex_methods {
6360   int (*xMutexInit)(void);
6361   int (*xMutexEnd)(void);
6362   sqlite3_mutex *(*xMutexAlloc)(int);
6363   void (*xMutexFree)(sqlite3_mutex *);
6364   void (*xMutexEnter)(sqlite3_mutex *);
6365   int (*xMutexTry)(sqlite3_mutex *);
6366   void (*xMutexLeave)(sqlite3_mutex *);
6367   int (*xMutexHeld)(sqlite3_mutex *);
6368   int (*xMutexNotheld)(sqlite3_mutex *);
6369 };
6370 
6371 /*
6372 ** CAPI3REF: Mutex Verification Routines
6373 **
6374 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6375 ** are intended for use inside assert() statements.  ^The SQLite core
6376 ** never uses these routines except inside an assert() and applications
6377 ** are advised to follow the lead of the core.  ^The SQLite core only
6378 ** provides implementations for these routines when it is compiled
6379 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6380 ** are only required to provide these routines if SQLITE_DEBUG is
6381 ** defined and if NDEBUG is not defined.
6382 **
6383 ** ^These routines should return true if the mutex in their argument
6384 ** is held or not held, respectively, by the calling thread.
6385 **
6386 ** ^The implementation is not required to provide versions of these
6387 ** routines that actually work. If the implementation does not provide working
6388 ** versions of these routines, it should at least provide stubs that always
6389 ** return true so that one does not get spurious assertion failures.
6390 **
6391 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6392 ** the routine should return 1.   This seems counter-intuitive since
6393 ** clearly the mutex cannot be held if it does not exist.  But
6394 ** the reason the mutex does not exist is because the build is not
6395 ** using mutexes.  And we do not want the assert() containing the
6396 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6397 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6398 ** interface should also return 1 when given a NULL pointer.
6399 */
6400 #ifndef NDEBUG
6401 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6402 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6403 #endif
6404 
6405 /*
6406 ** CAPI3REF: Mutex Types
6407 **
6408 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6409 ** which is one of these integer constants.
6410 **
6411 ** The set of static mutexes may change from one SQLite release to the
6412 ** next.  Applications that override the built-in mutex logic must be
6413 ** prepared to accommodate additional static mutexes.
6414 */
6415 #define SQLITE_MUTEX_FAST             0
6416 #define SQLITE_MUTEX_RECURSIVE        1
6417 #define SQLITE_MUTEX_STATIC_MASTER    2
6418 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6419 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6420 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6421 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6422 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6423 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6424 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6425 
6426 /*
6427 ** CAPI3REF: Retrieve the mutex for a database connection
6428 **
6429 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6430 ** serializes access to the [database connection] given in the argument
6431 ** when the [threading mode] is Serialized.
6432 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6433 ** routine returns a NULL pointer.
6434 */
6435 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6436 
6437 /*
6438 ** CAPI3REF: Low-Level Control Of Database Files
6439 **
6440 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6441 ** xFileControl method for the [sqlite3_io_methods] object associated
6442 ** with a particular database identified by the second argument. ^The
6443 ** name of the database is "main" for the main database or "temp" for the
6444 ** TEMP database, or the name that appears after the AS keyword for
6445 ** databases that are added using the [ATTACH] SQL command.
6446 ** ^A NULL pointer can be used in place of "main" to refer to the
6447 ** main database file.
6448 ** ^The third and fourth parameters to this routine
6449 ** are passed directly through to the second and third parameters of
6450 ** the xFileControl method.  ^The return value of the xFileControl
6451 ** method becomes the return value of this routine.
6452 **
6453 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6454 ** a pointer to the underlying [sqlite3_file] object to be written into
6455 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6456 ** case is a short-circuit path which does not actually invoke the
6457 ** underlying sqlite3_io_methods.xFileControl method.
6458 **
6459 ** ^If the second parameter (zDbName) does not match the name of any
6460 ** open database file, then SQLITE_ERROR is returned.  ^This error
6461 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6462 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6463 ** also return SQLITE_ERROR.  There is no way to distinguish between
6464 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6465 ** xFileControl method.
6466 **
6467 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6468 */
6469 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6470 
6471 /*
6472 ** CAPI3REF: Testing Interface
6473 **
6474 ** ^The sqlite3_test_control() interface is used to read out internal
6475 ** state of SQLite and to inject faults into SQLite for testing
6476 ** purposes.  ^The first parameter is an operation code that determines
6477 ** the number, meaning, and operation of all subsequent parameters.
6478 **
6479 ** This interface is not for use by applications.  It exists solely
6480 ** for verifying the correct operation of the SQLite library.  Depending
6481 ** on how the SQLite library is compiled, this interface might not exist.
6482 **
6483 ** The details of the operation codes, their meanings, the parameters
6484 ** they take, and what they do are all subject to change without notice.
6485 ** Unlike most of the SQLite API, this function is not guaranteed to
6486 ** operate consistently from one release to the next.
6487 */
6488 SQLITE_API int sqlite3_test_control(int op, ...);
6489 
6490 /*
6491 ** CAPI3REF: Testing Interface Operation Codes
6492 **
6493 ** These constants are the valid operation code parameters used
6494 ** as the first argument to [sqlite3_test_control()].
6495 **
6496 ** These parameters and their meanings are subject to change
6497 ** without notice.  These values are for testing purposes only.
6498 ** Applications should not use any of these parameters or the
6499 ** [sqlite3_test_control()] interface.
6500 */
6501 #define SQLITE_TESTCTRL_FIRST                    5
6502 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6503 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6504 #define SQLITE_TESTCTRL_PRNG_RESET               7
6505 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6506 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6507 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6508 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6509 #define SQLITE_TESTCTRL_ASSERT                  12
6510 #define SQLITE_TESTCTRL_ALWAYS                  13
6511 #define SQLITE_TESTCTRL_RESERVE                 14
6512 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6513 #define SQLITE_TESTCTRL_ISKEYWORD               16
6514 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6515 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6516 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6517 #define SQLITE_TESTCTRL_LAST                    19
6518 
6519 /*
6520 ** CAPI3REF: SQLite Runtime Status
6521 **
6522 ** ^This interface is used to retrieve runtime status information
6523 ** about the performance of SQLite, and optionally to reset various
6524 ** highwater marks.  ^The first argument is an integer code for
6525 ** the specific parameter to measure.  ^(Recognized integer codes
6526 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6527 ** ^The current value of the parameter is returned into *pCurrent.
6528 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6529 ** resetFlag is true, then the highest record value is reset after
6530 ** *pHighwater is written.  ^(Some parameters do not record the highest
6531 ** value.  For those parameters
6532 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6533 ** ^(Other parameters record only the highwater mark and not the current
6534 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6535 **
6536 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6537 ** non-zero [error code] on failure.
6538 **
6539 ** This routine is threadsafe but is not atomic.  This routine can be
6540 ** called while other threads are running the same or different SQLite
6541 ** interfaces.  However the values returned in *pCurrent and
6542 ** *pHighwater reflect the status of SQLite at different points in time
6543 ** and it is possible that another thread might change the parameter
6544 ** in between the times when *pCurrent and *pHighwater are written.
6545 **
6546 ** See also: [sqlite3_db_status()]
6547 */
6548 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6549 
6550 
6551 /*
6552 ** CAPI3REF: Status Parameters
6553 ** KEYWORDS: {status parameters}
6554 **
6555 ** These integer constants designate various run-time status parameters
6556 ** that can be returned by [sqlite3_status()].
6557 **
6558 ** <dl>
6559 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6560 ** <dd>This parameter is the current amount of memory checked out
6561 ** using [sqlite3_malloc()], either directly or indirectly.  The
6562 ** figure includes calls made to [sqlite3_malloc()] by the application
6563 ** and internal memory usage by the SQLite library.  Scratch memory
6564 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6565 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6566 ** this parameter.  The amount returned is the sum of the allocation
6567 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6568 **
6569 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6570 ** <dd>This parameter records the largest memory allocation request
6571 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6572 ** internal equivalents).  Only the value returned in the
6573 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6574 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6575 **
6576 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6577 ** <dd>This parameter records the number of separate memory allocations
6578 ** currently checked out.</dd>)^
6579 **
6580 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6581 ** <dd>This parameter returns the number of pages used out of the
6582 ** [pagecache memory allocator] that was configured using
6583 ** [SQLITE_CONFIG_PAGECACHE].  The
6584 ** value returned is in pages, not in bytes.</dd>)^
6585 **
6586 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6587 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6588 ** <dd>This parameter returns the number of bytes of page cache
6589 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6590 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6591 ** returned value includes allocations that overflowed because they
6592 ** where too large (they were larger than the "sz" parameter to
6593 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6594 ** no space was left in the page cache.</dd>)^
6595 **
6596 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6597 ** <dd>This parameter records the largest memory allocation request
6598 ** handed to [pagecache memory allocator].  Only the value returned in the
6599 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6600 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6601 **
6602 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6603 ** <dd>This parameter returns the number of allocations used out of the
6604 ** [scratch memory allocator] configured using
6605 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6606 ** in bytes.  Since a single thread may only have one scratch allocation
6607 ** outstanding at time, this parameter also reports the number of threads
6608 ** using scratch memory at the same time.</dd>)^
6609 **
6610 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6611 ** <dd>This parameter returns the number of bytes of scratch memory
6612 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6613 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6614 ** returned include overflows because the requested allocation was too
6615 ** larger (that is, because the requested allocation was larger than the
6616 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6617 ** slots were available.
6618 ** </dd>)^
6619 **
6620 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6621 ** <dd>This parameter records the largest memory allocation request
6622 ** handed to [scratch memory allocator].  Only the value returned in the
6623 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6624 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6625 **
6626 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6627 ** <dd>This parameter records the deepest parser stack.  It is only
6628 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6629 ** </dl>
6630 **
6631 ** New status parameters may be added from time to time.
6632 */
6633 #define SQLITE_STATUS_MEMORY_USED          0
6634 #define SQLITE_STATUS_PAGECACHE_USED       1
6635 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6636 #define SQLITE_STATUS_SCRATCH_USED         3
6637 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6638 #define SQLITE_STATUS_MALLOC_SIZE          5
6639 #define SQLITE_STATUS_PARSER_STACK         6
6640 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6641 #define SQLITE_STATUS_SCRATCH_SIZE         8
6642 #define SQLITE_STATUS_MALLOC_COUNT         9
6643 
6644 /*
6645 ** CAPI3REF: Database Connection Status
6646 **
6647 ** ^This interface is used to retrieve runtime status information
6648 ** about a single [database connection].  ^The first argument is the
6649 ** database connection object to be interrogated.  ^The second argument
6650 ** is an integer constant, taken from the set of
6651 ** [SQLITE_DBSTATUS options], that
6652 ** determines the parameter to interrogate.  The set of
6653 ** [SQLITE_DBSTATUS options] is likely
6654 ** to grow in future releases of SQLite.
6655 **
6656 ** ^The current value of the requested parameter is written into *pCur
6657 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6658 ** the resetFlg is true, then the highest instantaneous value is
6659 ** reset back down to the current value.
6660 **
6661 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6662 ** non-zero [error code] on failure.
6663 **
6664 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6665 */
6666 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6667 
6668 /*
6669 ** CAPI3REF: Status Parameters for database connections
6670 ** KEYWORDS: {SQLITE_DBSTATUS options}
6671 **
6672 ** These constants are the available integer "verbs" that can be passed as
6673 ** the second argument to the [sqlite3_db_status()] interface.
6674 **
6675 ** New verbs may be added in future releases of SQLite. Existing verbs
6676 ** might be discontinued. Applications should check the return code from
6677 ** [sqlite3_db_status()] to make sure that the call worked.
6678 ** The [sqlite3_db_status()] interface will return a non-zero error code
6679 ** if a discontinued or unsupported verb is invoked.
6680 **
6681 ** <dl>
6682 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6683 ** <dd>This parameter returns the number of lookaside memory slots currently
6684 ** checked out.</dd>)^
6685 **
6686 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6687 ** <dd>This parameter returns the number malloc attempts that were
6688 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6689 ** the current value is always zero.)^
6690 **
6691 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6692 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6693 ** <dd>This parameter returns the number malloc attempts that might have
6694 ** been satisfied using lookaside memory but failed due to the amount of
6695 ** memory requested being larger than the lookaside slot size.
6696 ** Only the high-water value is meaningful;
6697 ** the current value is always zero.)^
6698 **
6699 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6700 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6701 ** <dd>This parameter returns the number malloc attempts that might have
6702 ** been satisfied using lookaside memory but failed due to all lookaside
6703 ** memory already being in use.
6704 ** Only the high-water value is meaningful;
6705 ** the current value is always zero.)^
6706 **
6707 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6708 ** <dd>This parameter returns the approximate number of of bytes of heap
6709 ** memory used by all pager caches associated with the database connection.)^
6710 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6711 **
6712 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6713 ** <dd>This parameter returns the approximate number of of bytes of heap
6714 ** memory used to store the schema for all databases associated
6715 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6716 ** ^The full amount of memory used by the schemas is reported, even if the
6717 ** schema memory is shared with other database connections due to
6718 ** [shared cache mode] being enabled.
6719 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6720 **
6721 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6722 ** <dd>This parameter returns the approximate number of of bytes of heap
6723 ** and lookaside memory used by all prepared statements associated with
6724 ** the database connection.)^
6725 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6726 ** </dd>
6727 **
6728 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6729 ** <dd>This parameter returns the number of pager cache hits that have
6730 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6731 ** is always 0.
6732 ** </dd>
6733 **
6734 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6735 ** <dd>This parameter returns the number of pager cache misses that have
6736 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6737 ** is always 0.
6738 ** </dd>
6739 **
6740 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6741 ** <dd>This parameter returns the number of dirty cache entries that have
6742 ** been written to disk. Specifically, the number of pages written to the
6743 ** wal file in wal mode databases, or the number of pages written to the
6744 ** database file in rollback mode databases. Any pages written as part of
6745 ** transaction rollback or database recovery operations are not included.
6746 ** If an IO or other error occurs while writing a page to disk, the effect
6747 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6748 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6749 ** </dd>
6750 ** </dl>
6751 */
6752 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6753 #define SQLITE_DBSTATUS_CACHE_USED           1
6754 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6755 #define SQLITE_DBSTATUS_STMT_USED            3
6756 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6757 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6758 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6759 #define SQLITE_DBSTATUS_CACHE_HIT            7
6760 #define SQLITE_DBSTATUS_CACHE_MISS           8
6761 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6762 #define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6763 
6764 
6765 /*
6766 ** CAPI3REF: Prepared Statement Status
6767 **
6768 ** ^(Each prepared statement maintains various
6769 ** [SQLITE_STMTSTATUS counters] that measure the number
6770 ** of times it has performed specific operations.)^  These counters can
6771 ** be used to monitor the performance characteristics of the prepared
6772 ** statements.  For example, if the number of table steps greatly exceeds
6773 ** the number of table searches or result rows, that would tend to indicate
6774 ** that the prepared statement is using a full table scan rather than
6775 ** an index.
6776 **
6777 ** ^(This interface is used to retrieve and reset counter values from
6778 ** a [prepared statement].  The first argument is the prepared statement
6779 ** object to be interrogated.  The second argument
6780 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6781 ** to be interrogated.)^
6782 ** ^The current value of the requested counter is returned.
6783 ** ^If the resetFlg is true, then the counter is reset to zero after this
6784 ** interface call returns.
6785 **
6786 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6787 */
6788 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6789 
6790 /*
6791 ** CAPI3REF: Status Parameters for prepared statements
6792 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6793 **
6794 ** These preprocessor macros define integer codes that name counter
6795 ** values associated with the [sqlite3_stmt_status()] interface.
6796 ** The meanings of the various counters are as follows:
6797 **
6798 ** <dl>
6799 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6800 ** <dd>^This is the number of times that SQLite has stepped forward in
6801 ** a table as part of a full table scan.  Large numbers for this counter
6802 ** may indicate opportunities for performance improvement through
6803 ** careful use of indices.</dd>
6804 **
6805 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6806 ** <dd>^This is the number of sort operations that have occurred.
6807 ** A non-zero value in this counter may indicate an opportunity to
6808 ** improvement performance through careful use of indices.</dd>
6809 **
6810 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6811 ** <dd>^This is the number of rows inserted into transient indices that
6812 ** were created automatically in order to help joins run faster.
6813 ** A non-zero value in this counter may indicate an opportunity to
6814 ** improvement performance by adding permanent indices that do not
6815 ** need to be reinitialized each time the statement is run.</dd>
6816 ** </dl>
6817 */
6818 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6819 #define SQLITE_STMTSTATUS_SORT              2
6820 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6821 
6822 /*
6823 ** CAPI3REF: Custom Page Cache Object
6824 **
6825 ** The sqlite3_pcache type is opaque.  It is implemented by
6826 ** the pluggable module.  The SQLite core has no knowledge of
6827 ** its size or internal structure and never deals with the
6828 ** sqlite3_pcache object except by holding and passing pointers
6829 ** to the object.
6830 **
6831 ** See [sqlite3_pcache_methods2] for additional information.
6832 */
6833 typedef struct sqlite3_pcache sqlite3_pcache;
6834 
6835 /*
6836 ** CAPI3REF: Custom Page Cache Object
6837 **
6838 ** The sqlite3_pcache_page object represents a single page in the
6839 ** page cache.  The page cache will allocate instances of this
6840 ** object.  Various methods of the page cache use pointers to instances
6841 ** of this object as parameters or as their return value.
6842 **
6843 ** See [sqlite3_pcache_methods2] for additional information.
6844 */
6845 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6846 struct sqlite3_pcache_page {
6847   void *pBuf;        /* The content of the page */
6848   void *pExtra;      /* Extra information associated with the page */
6849 };
6850 
6851 /*
6852 ** CAPI3REF: Application Defined Page Cache.
6853 ** KEYWORDS: {page cache}
6854 **
6855 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6856 ** register an alternative page cache implementation by passing in an
6857 ** instance of the sqlite3_pcache_methods2 structure.)^
6858 ** In many applications, most of the heap memory allocated by
6859 ** SQLite is used for the page cache.
6860 ** By implementing a
6861 ** custom page cache using this API, an application can better control
6862 ** the amount of memory consumed by SQLite, the way in which
6863 ** that memory is allocated and released, and the policies used to
6864 ** determine exactly which parts of a database file are cached and for
6865 ** how long.
6866 **
6867 ** The alternative page cache mechanism is an
6868 ** extreme measure that is only needed by the most demanding applications.
6869 ** The built-in page cache is recommended for most uses.
6870 **
6871 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6872 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6873 ** the application may discard the parameter after the call to
6874 ** [sqlite3_config()] returns.)^
6875 **
6876 ** [[the xInit() page cache method]]
6877 ** ^(The xInit() method is called once for each effective
6878 ** call to [sqlite3_initialize()])^
6879 ** (usually only once during the lifetime of the process). ^(The xInit()
6880 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6881 ** The intent of the xInit() method is to set up global data structures
6882 ** required by the custom page cache implementation.
6883 ** ^(If the xInit() method is NULL, then the
6884 ** built-in default page cache is used instead of the application defined
6885 ** page cache.)^
6886 **
6887 ** [[the xShutdown() page cache method]]
6888 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6889 ** It can be used to clean up
6890 ** any outstanding resources before process shutdown, if required.
6891 ** ^The xShutdown() method may be NULL.
6892 **
6893 ** ^SQLite automatically serializes calls to the xInit method,
6894 ** so the xInit method need not be threadsafe.  ^The
6895 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6896 ** not need to be threadsafe either.  All other methods must be threadsafe
6897 ** in multithreaded applications.
6898 **
6899 ** ^SQLite will never invoke xInit() more than once without an intervening
6900 ** call to xShutdown().
6901 **
6902 ** [[the xCreate() page cache methods]]
6903 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6904 ** SQLite will typically create one cache instance for each open database file,
6905 ** though this is not guaranteed. ^The
6906 ** first parameter, szPage, is the size in bytes of the pages that must
6907 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6908 ** second parameter szExtra is a number of bytes of extra storage
6909 ** associated with each page cache entry.  ^The szExtra parameter will
6910 ** a number less than 250.  SQLite will use the
6911 ** extra szExtra bytes on each page to store metadata about the underlying
6912 ** database page on disk.  The value passed into szExtra depends
6913 ** on the SQLite version, the target platform, and how SQLite was compiled.
6914 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6915 ** created will be used to cache database pages of a file stored on disk, or
6916 ** false if it is used for an in-memory database. The cache implementation
6917 ** does not have to do anything special based with the value of bPurgeable;
6918 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6919 ** never invoke xUnpin() except to deliberately delete a page.
6920 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6921 ** false will always have the "discard" flag set to true.
6922 ** ^Hence, a cache created with bPurgeable false will
6923 ** never contain any unpinned pages.
6924 **
6925 ** [[the xCachesize() page cache method]]
6926 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6927 ** suggested maximum cache-size (number of pages stored by) the cache
6928 ** instance passed as the first argument. This is the value configured using
6929 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6930 ** parameter, the implementation is not required to do anything with this
6931 ** value; it is advisory only.
6932 **
6933 ** [[the xPagecount() page cache methods]]
6934 ** The xPagecount() method must return the number of pages currently
6935 ** stored in the cache, both pinned and unpinned.
6936 **
6937 ** [[the xFetch() page cache methods]]
6938 ** The xFetch() method locates a page in the cache and returns a pointer to
6939 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6940 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6941 ** pointer to a buffer of szPage bytes used to store the content of a
6942 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6943 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6944 ** for each entry in the page cache.
6945 **
6946 ** The page to be fetched is determined by the key. ^The minimum key value
6947 ** is 1.  After it has been retrieved using xFetch, the page is considered
6948 ** to be "pinned".
6949 **
6950 ** If the requested page is already in the page cache, then the page cache
6951 ** implementation must return a pointer to the page buffer with its content
6952 ** intact.  If the requested page is not already in the cache, then the
6953 ** cache implementation should use the value of the createFlag
6954 ** parameter to help it determined what action to take:
6955 **
6956 ** <table border=1 width=85% align=center>
6957 ** <tr><th> createFlag <th> Behavior when page is not already in cache
6958 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6959 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6960 **                 Otherwise return NULL.
6961 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6962 **                 NULL if allocating a new page is effectively impossible.
6963 ** </table>
6964 **
6965 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6966 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6967 ** failed.)^  In between the to xFetch() calls, SQLite may
6968 ** attempt to unpin one or more cache pages by spilling the content of
6969 ** pinned pages to disk and synching the operating system disk cache.
6970 **
6971 ** [[the xUnpin() page cache method]]
6972 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6973 ** as its second argument.  If the third parameter, discard, is non-zero,
6974 ** then the page must be evicted from the cache.
6975 ** ^If the discard parameter is
6976 ** zero, then the page may be discarded or retained at the discretion of
6977 ** page cache implementation. ^The page cache implementation
6978 ** may choose to evict unpinned pages at any time.
6979 **
6980 ** The cache must not perform any reference counting. A single
6981 ** call to xUnpin() unpins the page regardless of the number of prior calls
6982 ** to xFetch().
6983 **
6984 ** [[the xRekey() page cache methods]]
6985 ** The xRekey() method is used to change the key value associated with the
6986 ** page passed as the second argument. If the cache
6987 ** previously contains an entry associated with newKey, it must be
6988 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6989 ** to be pinned.
6990 **
6991 ** When SQLite calls the xTruncate() method, the cache must discard all
6992 ** existing cache entries with page numbers (keys) greater than or equal
6993 ** to the value of the iLimit parameter passed to xTruncate(). If any
6994 ** of these pages are pinned, they are implicitly unpinned, meaning that
6995 ** they can be safely discarded.
6996 **
6997 ** [[the xDestroy() page cache method]]
6998 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6999 ** All resources associated with the specified cache should be freed. ^After
7000 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7001 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7002 ** functions.
7003 **
7004 ** [[the xShrink() page cache method]]
7005 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7006 ** free up as much of heap memory as possible.  The page cache implementation
7007 ** is not obligated to free any memory, but well-behaved implementations should
7008 ** do their best.
7009 */
7010 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7011 struct sqlite3_pcache_methods2 {
7012   int iVersion;
7013   void *pArg;
7014   int (*xInit)(void*);
7015   void (*xShutdown)(void*);
7016   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7017   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7018   int (*xPagecount)(sqlite3_pcache*);
7019   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7020   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7021   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7022       unsigned oldKey, unsigned newKey);
7023   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7024   void (*xDestroy)(sqlite3_pcache*);
7025   void (*xShrink)(sqlite3_pcache*);
7026 };
7027 
7028 /*
7029 ** This is the obsolete pcache_methods object that has now been replaced
7030 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7031 ** retained in the header file for backwards compatibility only.
7032 */
7033 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7034 struct sqlite3_pcache_methods {
7035   void *pArg;
7036   int (*xInit)(void*);
7037   void (*xShutdown)(void*);
7038   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7039   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7040   int (*xPagecount)(sqlite3_pcache*);
7041   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7042   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7043   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7044   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7045   void (*xDestroy)(sqlite3_pcache*);
7046 };
7047 
7048 
7049 /*
7050 ** CAPI3REF: Online Backup Object
7051 **
7052 ** The sqlite3_backup object records state information about an ongoing
7053 ** online backup operation.  ^The sqlite3_backup object is created by
7054 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7055 ** [sqlite3_backup_finish()].
7056 **
7057 ** See Also: [Using the SQLite Online Backup API]
7058 */
7059 typedef struct sqlite3_backup sqlite3_backup;
7060 
7061 /*
7062 ** CAPI3REF: Online Backup API.
7063 **
7064 ** The backup API copies the content of one database into another.
7065 ** It is useful either for creating backups of databases or
7066 ** for copying in-memory databases to or from persistent files.
7067 **
7068 ** See Also: [Using the SQLite Online Backup API]
7069 **
7070 ** ^SQLite holds a write transaction open on the destination database file
7071 ** for the duration of the backup operation.
7072 ** ^The source database is read-locked only while it is being read;
7073 ** it is not locked continuously for the entire backup operation.
7074 ** ^Thus, the backup may be performed on a live source database without
7075 ** preventing other database connections from
7076 ** reading or writing to the source database while the backup is underway.
7077 **
7078 ** ^(To perform a backup operation:
7079 **   <ol>
7080 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7081 **         backup,
7082 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7083 **         the data between the two databases, and finally
7084 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7085 **         associated with the backup operation.
7086 **   </ol>)^
7087 ** There should be exactly one call to sqlite3_backup_finish() for each
7088 ** successful call to sqlite3_backup_init().
7089 **
7090 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7091 **
7092 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7093 ** [database connection] associated with the destination database
7094 ** and the database name, respectively.
7095 ** ^The database name is "main" for the main database, "temp" for the
7096 ** temporary database, or the name specified after the AS keyword in
7097 ** an [ATTACH] statement for an attached database.
7098 ** ^The S and M arguments passed to
7099 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7100 ** and database name of the source database, respectively.
7101 ** ^The source and destination [database connections] (parameters S and D)
7102 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7103 ** an error.
7104 **
7105 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7106 ** returned and an error code and error message are stored in the
7107 ** destination [database connection] D.
7108 ** ^The error code and message for the failed call to sqlite3_backup_init()
7109 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7110 ** [sqlite3_errmsg16()] functions.
7111 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7112 ** [sqlite3_backup] object.
7113 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7114 ** sqlite3_backup_finish() functions to perform the specified backup
7115 ** operation.
7116 **
7117 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7118 **
7119 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7120 ** the source and destination databases specified by [sqlite3_backup] object B.
7121 ** ^If N is negative, all remaining source pages are copied.
7122 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7123 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7124 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7125 ** from source to destination, then it returns [SQLITE_DONE].
7126 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7127 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7128 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7129 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7130 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7131 **
7132 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7133 ** <ol>
7134 ** <li> the destination database was opened read-only, or
7135 ** <li> the destination database is using write-ahead-log journaling
7136 ** and the destination and source page sizes differ, or
7137 ** <li> the destination database is an in-memory database and the
7138 ** destination and source page sizes differ.
7139 ** </ol>)^
7140 **
7141 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7142 ** the [sqlite3_busy_handler | busy-handler function]
7143 ** is invoked (if one is specified). ^If the
7144 ** busy-handler returns non-zero before the lock is available, then
7145 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7146 ** sqlite3_backup_step() can be retried later. ^If the source
7147 ** [database connection]
7148 ** is being used to write to the source database when sqlite3_backup_step()
7149 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7150 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7151 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7152 ** [SQLITE_READONLY] is returned, then
7153 ** there is no point in retrying the call to sqlite3_backup_step(). These
7154 ** errors are considered fatal.)^  The application must accept
7155 ** that the backup operation has failed and pass the backup operation handle
7156 ** to the sqlite3_backup_finish() to release associated resources.
7157 **
7158 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7159 ** on the destination file. ^The exclusive lock is not released until either
7160 ** sqlite3_backup_finish() is called or the backup operation is complete
7161 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7162 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7163 ** lasts for the duration of the sqlite3_backup_step() call.
7164 ** ^Because the source database is not locked between calls to
7165 ** sqlite3_backup_step(), the source database may be modified mid-way
7166 ** through the backup process.  ^If the source database is modified by an
7167 ** external process or via a database connection other than the one being
7168 ** used by the backup operation, then the backup will be automatically
7169 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7170 ** database is modified by the using the same database connection as is used
7171 ** by the backup operation, then the backup database is automatically
7172 ** updated at the same time.
7173 **
7174 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7175 **
7176 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7177 ** application wishes to abandon the backup operation, the application
7178 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7179 ** ^The sqlite3_backup_finish() interfaces releases all
7180 ** resources associated with the [sqlite3_backup] object.
7181 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7182 ** active write-transaction on the destination database is rolled back.
7183 ** The [sqlite3_backup] object is invalid
7184 ** and may not be used following a call to sqlite3_backup_finish().
7185 **
7186 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7187 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7188 ** sqlite3_backup_step() completed.
7189 ** ^If an out-of-memory condition or IO error occurred during any prior
7190 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7191 ** sqlite3_backup_finish() returns the corresponding [error code].
7192 **
7193 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7194 ** is not a permanent error and does not affect the return value of
7195 ** sqlite3_backup_finish().
7196 **
7197 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7198 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7199 **
7200 ** ^Each call to sqlite3_backup_step() sets two values inside
7201 ** the [sqlite3_backup] object: the number of pages still to be backed
7202 ** up and the total number of pages in the source database file.
7203 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7204 ** retrieve these two values, respectively.
7205 **
7206 ** ^The values returned by these functions are only updated by
7207 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7208 ** operation, then the values are not updated to account for any extra
7209 ** pages that need to be updated or the size of the source database file
7210 ** changing.
7211 **
7212 ** <b>Concurrent Usage of Database Handles</b>
7213 **
7214 ** ^The source [database connection] may be used by the application for other
7215 ** purposes while a backup operation is underway or being initialized.
7216 ** ^If SQLite is compiled and configured to support threadsafe database
7217 ** connections, then the source database connection may be used concurrently
7218 ** from within other threads.
7219 **
7220 ** However, the application must guarantee that the destination
7221 ** [database connection] is not passed to any other API (by any thread) after
7222 ** sqlite3_backup_init() is called and before the corresponding call to
7223 ** sqlite3_backup_finish().  SQLite does not currently check to see
7224 ** if the application incorrectly accesses the destination [database connection]
7225 ** and so no error code is reported, but the operations may malfunction
7226 ** nevertheless.  Use of the destination database connection while a
7227 ** backup is in progress might also also cause a mutex deadlock.
7228 **
7229 ** If running in [shared cache mode], the application must
7230 ** guarantee that the shared cache used by the destination database
7231 ** is not accessed while the backup is running. In practice this means
7232 ** that the application must guarantee that the disk file being
7233 ** backed up to is not accessed by any connection within the process,
7234 ** not just the specific connection that was passed to sqlite3_backup_init().
7235 **
7236 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7237 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7238 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7239 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7240 ** same time as another thread is invoking sqlite3_backup_step() it is
7241 ** possible that they return invalid values.
7242 */
7243 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7244   sqlite3 *pDest,                        /* Destination database handle */
7245   const char *zDestName,                 /* Destination database name */
7246   sqlite3 *pSource,                      /* Source database handle */
7247   const char *zSourceName                /* Source database name */
7248 );
7249 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7250 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7251 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7252 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7253 
7254 /*
7255 ** CAPI3REF: Unlock Notification
7256 **
7257 ** ^When running in shared-cache mode, a database operation may fail with
7258 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7259 ** individual tables within the shared-cache cannot be obtained. See
7260 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7261 ** ^This API may be used to register a callback that SQLite will invoke
7262 ** when the connection currently holding the required lock relinquishes it.
7263 ** ^This API is only available if the library was compiled with the
7264 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7265 **
7266 ** See Also: [Using the SQLite Unlock Notification Feature].
7267 **
7268 ** ^Shared-cache locks are released when a database connection concludes
7269 ** its current transaction, either by committing it or rolling it back.
7270 **
7271 ** ^When a connection (known as the blocked connection) fails to obtain a
7272 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7273 ** identity of the database connection (the blocking connection) that
7274 ** has locked the required resource is stored internally. ^After an
7275 ** application receives an SQLITE_LOCKED error, it may call the
7276 ** sqlite3_unlock_notify() method with the blocked connection handle as
7277 ** the first argument to register for a callback that will be invoked
7278 ** when the blocking connections current transaction is concluded. ^The
7279 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7280 ** call that concludes the blocking connections transaction.
7281 **
7282 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7283 ** there is a chance that the blocking connection will have already
7284 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7285 ** If this happens, then the specified callback is invoked immediately,
7286 ** from within the call to sqlite3_unlock_notify().)^
7287 **
7288 ** ^If the blocked connection is attempting to obtain a write-lock on a
7289 ** shared-cache table, and more than one other connection currently holds
7290 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7291 ** the other connections to use as the blocking connection.
7292 **
7293 ** ^(There may be at most one unlock-notify callback registered by a
7294 ** blocked connection. If sqlite3_unlock_notify() is called when the
7295 ** blocked connection already has a registered unlock-notify callback,
7296 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7297 ** called with a NULL pointer as its second argument, then any existing
7298 ** unlock-notify callback is canceled. ^The blocked connections
7299 ** unlock-notify callback may also be canceled by closing the blocked
7300 ** connection using [sqlite3_close()].
7301 **
7302 ** The unlock-notify callback is not reentrant. If an application invokes
7303 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7304 ** crash or deadlock may be the result.
7305 **
7306 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7307 ** returns SQLITE_OK.
7308 **
7309 ** <b>Callback Invocation Details</b>
7310 **
7311 ** When an unlock-notify callback is registered, the application provides a
7312 ** single void* pointer that is passed to the callback when it is invoked.
7313 ** However, the signature of the callback function allows SQLite to pass
7314 ** it an array of void* context pointers. The first argument passed to
7315 ** an unlock-notify callback is a pointer to an array of void* pointers,
7316 ** and the second is the number of entries in the array.
7317 **
7318 ** When a blocking connections transaction is concluded, there may be
7319 ** more than one blocked connection that has registered for an unlock-notify
7320 ** callback. ^If two or more such blocked connections have specified the
7321 ** same callback function, then instead of invoking the callback function
7322 ** multiple times, it is invoked once with the set of void* context pointers
7323 ** specified by the blocked connections bundled together into an array.
7324 ** This gives the application an opportunity to prioritize any actions
7325 ** related to the set of unblocked database connections.
7326 **
7327 ** <b>Deadlock Detection</b>
7328 **
7329 ** Assuming that after registering for an unlock-notify callback a
7330 ** database waits for the callback to be issued before taking any further
7331 ** action (a reasonable assumption), then using this API may cause the
7332 ** application to deadlock. For example, if connection X is waiting for
7333 ** connection Y's transaction to be concluded, and similarly connection
7334 ** Y is waiting on connection X's transaction, then neither connection
7335 ** will proceed and the system may remain deadlocked indefinitely.
7336 **
7337 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7338 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7339 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7340 ** unlock-notify callback is registered. The system is said to be in
7341 ** a deadlocked state if connection A has registered for an unlock-notify
7342 ** callback on the conclusion of connection B's transaction, and connection
7343 ** B has itself registered for an unlock-notify callback when connection
7344 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7345 ** the system is also considered to be deadlocked if connection B has
7346 ** registered for an unlock-notify callback on the conclusion of connection
7347 ** C's transaction, where connection C is waiting on connection A. ^Any
7348 ** number of levels of indirection are allowed.
7349 **
7350 ** <b>The "DROP TABLE" Exception</b>
7351 **
7352 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7353 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7354 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7355 ** SQLite checks if there are any currently executing SELECT statements
7356 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7357 ** returned. In this case there is no "blocking connection", so invoking
7358 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7359 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7360 ** or "DROP INDEX" query, an infinite loop might be the result.
7361 **
7362 ** One way around this problem is to check the extended error code returned
7363 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7364 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7365 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7366 ** SQLITE_LOCKED.)^
7367 */
7368 SQLITE_API int sqlite3_unlock_notify(
7369   sqlite3 *pBlocked,                          /* Waiting connection */
7370   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7371   void *pNotifyArg                            /* Argument to pass to xNotify */
7372 );
7373 
7374 
7375 /*
7376 ** CAPI3REF: String Comparison
7377 **
7378 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7379 ** and extensions to compare the contents of two buffers containing UTF-8
7380 ** strings in a case-independent fashion, using the same definition of "case
7381 ** independence" that SQLite uses internally when comparing identifiers.
7382 */
7383 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7384 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7385 
7386 /*
7387 ** CAPI3REF: Error Logging Interface
7388 **
7389 ** ^The [sqlite3_log()] interface writes a message into the error log
7390 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7391 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7392 ** used with [sqlite3_snprintf()] to generate the final output string.
7393 **
7394 ** The sqlite3_log() interface is intended for use by extensions such as
7395 ** virtual tables, collating functions, and SQL functions.  While there is
7396 ** nothing to prevent an application from calling sqlite3_log(), doing so
7397 ** is considered bad form.
7398 **
7399 ** The zFormat string must not be NULL.
7400 **
7401 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7402 ** will not use dynamically allocated memory.  The log message is stored in
7403 ** a fixed-length buffer on the stack.  If the log message is longer than
7404 ** a few hundred characters, it will be truncated to the length of the
7405 ** buffer.
7406 */
7407 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7408 
7409 /*
7410 ** CAPI3REF: Write-Ahead Log Commit Hook
7411 **
7412 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7413 ** will be invoked each time a database connection commits data to a
7414 ** [write-ahead log] (i.e. whenever a transaction is committed in
7415 ** [journal_mode | journal_mode=WAL mode]).
7416 **
7417 ** ^The callback is invoked by SQLite after the commit has taken place and
7418 ** the associated write-lock on the database released, so the implementation
7419 ** may read, write or [checkpoint] the database as required.
7420 **
7421 ** ^The first parameter passed to the callback function when it is invoked
7422 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7423 ** registering the callback. ^The second is a copy of the database handle.
7424 ** ^The third parameter is the name of the database that was written to -
7425 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7426 ** is the number of pages currently in the write-ahead log file,
7427 ** including those that were just committed.
7428 **
7429 ** The callback function should normally return [SQLITE_OK].  ^If an error
7430 ** code is returned, that error will propagate back up through the
7431 ** SQLite code base to cause the statement that provoked the callback
7432 ** to report an error, though the commit will have still occurred. If the
7433 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7434 ** that does not correspond to any valid SQLite error code, the results
7435 ** are undefined.
7436 **
7437 ** A single database handle may have at most a single write-ahead log callback
7438 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7439 ** previously registered write-ahead log callback. ^Note that the
7440 ** [sqlite3_wal_autocheckpoint()] interface and the
7441 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7442 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7443 */
7444 SQLITE_API void *sqlite3_wal_hook(
7445   sqlite3*,
7446   int(*)(void *,sqlite3*,const char*,int),
7447   void*
7448 );
7449 
7450 /*
7451 ** CAPI3REF: Configure an auto-checkpoint
7452 **
7453 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7454 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7455 ** to automatically [checkpoint]
7456 ** after committing a transaction if there are N or
7457 ** more frames in the [write-ahead log] file.  ^Passing zero or
7458 ** a negative value as the nFrame parameter disables automatic
7459 ** checkpoints entirely.
7460 **
7461 ** ^The callback registered by this function replaces any existing callback
7462 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7463 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7464 ** configured by this function.
7465 **
7466 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7467 ** from SQL.
7468 **
7469 ** ^Every new [database connection] defaults to having the auto-checkpoint
7470 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7471 ** pages.  The use of this interface
7472 ** is only necessary if the default setting is found to be suboptimal
7473 ** for a particular application.
7474 */
7475 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7476 
7477 /*
7478 ** CAPI3REF: Checkpoint a database
7479 **
7480 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7481 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7482 ** empty string, then a checkpoint is run on all databases of
7483 ** connection D.  ^If the database connection D is not in
7484 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7485 **
7486 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7487 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7488 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7489 ** run whenever the WAL reaches a certain size threshold.
7490 **
7491 ** See also: [sqlite3_wal_checkpoint_v2()]
7492 */
7493 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7494 
7495 /*
7496 ** CAPI3REF: Checkpoint a database
7497 **
7498 ** Run a checkpoint operation on WAL database zDb attached to database
7499 ** handle db. The specific operation is determined by the value of the
7500 ** eMode parameter:
7501 **
7502 ** <dl>
7503 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7504 **   Checkpoint as many frames as possible without waiting for any database
7505 **   readers or writers to finish. Sync the db file if all frames in the log
7506 **   are checkpointed. This mode is the same as calling
7507 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7508 **
7509 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7510 **   This mode blocks (calls the busy-handler callback) until there is no
7511 **   database writer and all readers are reading from the most recent database
7512 **   snapshot. It then checkpoints all frames in the log file and syncs the
7513 **   database file. This call blocks database writers while it is running,
7514 **   but not database readers.
7515 **
7516 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7517 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7518 **   checkpointing the log file it blocks (calls the busy-handler callback)
7519 **   until all readers are reading from the database file only. This ensures
7520 **   that the next client to write to the database file restarts the log file
7521 **   from the beginning. This call blocks database writers while it is running,
7522 **   but not database readers.
7523 ** </dl>
7524 **
7525 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7526 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7527 ** the total number of checkpointed frames (including any that were already
7528 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7529 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7530 ** If no values are available because of an error, they are both set to -1
7531 ** before returning to communicate this to the caller.
7532 **
7533 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7534 ** any other process is running a checkpoint operation at the same time, the
7535 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7536 ** busy-handler configured, it will not be invoked in this case.
7537 **
7538 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7539 ** "writer" lock on the database file. If the writer lock cannot be obtained
7540 ** immediately, and a busy-handler is configured, it is invoked and the writer
7541 ** lock retried until either the busy-handler returns 0 or the lock is
7542 ** successfully obtained. The busy-handler is also invoked while waiting for
7543 ** database readers as described above. If the busy-handler returns 0 before
7544 ** the writer lock is obtained or while waiting for database readers, the
7545 ** checkpoint operation proceeds from that point in the same way as
7546 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7547 ** without blocking any further. SQLITE_BUSY is returned in this case.
7548 **
7549 ** If parameter zDb is NULL or points to a zero length string, then the
7550 ** specified operation is attempted on all WAL databases. In this case the
7551 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7552 ** an SQLITE_BUSY error is encountered when processing one or more of the
7553 ** attached WAL databases, the operation is still attempted on any remaining
7554 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7555 ** error occurs while processing an attached database, processing is abandoned
7556 ** and the error code returned to the caller immediately. If no error
7557 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7558 ** databases, SQLITE_OK is returned.
7559 **
7560 ** If database zDb is the name of an attached database that is not in WAL
7561 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7562 ** zDb is not NULL (or a zero length string) and is not the name of any
7563 ** attached database, SQLITE_ERROR is returned to the caller.
7564 */
7565 SQLITE_API int sqlite3_wal_checkpoint_v2(
7566   sqlite3 *db,                    /* Database handle */
7567   const char *zDb,                /* Name of attached database (or NULL) */
7568   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7569   int *pnLog,                     /* OUT: Size of WAL log in frames */
7570   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7571 );
7572 
7573 /*
7574 ** CAPI3REF: Checkpoint operation parameters
7575 **
7576 ** These constants can be used as the 3rd parameter to
7577 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7578 ** documentation for additional information about the meaning and use of
7579 ** each of these values.
7580 */
7581 #define SQLITE_CHECKPOINT_PASSIVE 0
7582 #define SQLITE_CHECKPOINT_FULL    1
7583 #define SQLITE_CHECKPOINT_RESTART 2
7584 
7585 /*
7586 ** CAPI3REF: Virtual Table Interface Configuration
7587 **
7588 ** This function may be called by either the [xConnect] or [xCreate] method
7589 ** of a [virtual table] implementation to configure
7590 ** various facets of the virtual table interface.
7591 **
7592 ** If this interface is invoked outside the context of an xConnect or
7593 ** xCreate virtual table method then the behavior is undefined.
7594 **
7595 ** At present, there is only one option that may be configured using
7596 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7597 ** may be added in the future.
7598 */
7599 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7600 
7601 /*
7602 ** CAPI3REF: Virtual Table Configuration Options
7603 **
7604 ** These macros define the various options to the
7605 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7606 ** can use to customize and optimize their behavior.
7607 **
7608 ** <dl>
7609 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7610 ** <dd>Calls of the form
7611 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7612 ** where X is an integer.  If X is zero, then the [virtual table] whose
7613 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7614 ** support constraints.  In this configuration (which is the default) if
7615 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7616 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7617 ** specified as part of the users SQL statement, regardless of the actual
7618 ** ON CONFLICT mode specified.
7619 **
7620 ** If X is non-zero, then the virtual table implementation guarantees
7621 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7622 ** any modifications to internal or persistent data structures have been made.
7623 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7624 ** is able to roll back a statement or database transaction, and abandon
7625 ** or continue processing the current SQL statement as appropriate.
7626 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7627 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7628 ** had been ABORT.
7629 **
7630 ** Virtual table implementations that are required to handle OR REPLACE
7631 ** must do so within the [xUpdate] method. If a call to the
7632 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7633 ** CONFLICT policy is REPLACE, the virtual table implementation should
7634 ** silently replace the appropriate rows within the xUpdate callback and
7635 ** return SQLITE_OK. Or, if this is not possible, it may return
7636 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7637 ** constraint handling.
7638 ** </dl>
7639 */
7640 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7641 
7642 /*
7643 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7644 **
7645 ** This function may only be called from within a call to the [xUpdate] method
7646 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7647 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7648 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7649 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7650 ** [virtual table].
7651 */
7652 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7653 
7654 /*
7655 ** CAPI3REF: Conflict resolution modes
7656 **
7657 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7658 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7659 ** is for the SQL statement being evaluated.
7660 **
7661 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7662 ** return value from the [sqlite3_set_authorizer()] callback and that
7663 ** [SQLITE_ABORT] is also a [result code].
7664 */
7665 #define SQLITE_ROLLBACK 1
7666 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7667 #define SQLITE_FAIL     3
7668 /* #define SQLITE_ABORT 4  // Also an error code */
7669 #define SQLITE_REPLACE  5
7670 
7671 
7672 
7673 /*
7674 ** Undo the hack that converts floating point types to integer for
7675 ** builds on processors without floating point support.
7676 */
7677 #ifdef SQLITE_OMIT_FLOATING_POINT
7678 # undef double
7679 #endif
7680 
7681 #if 0
7682 }  /* End of the 'extern "C"' block */
7683 #endif
7684 #endif
7685 
7686 /*
7687 ** 2010 August 30
7688 **
7689 ** The author disclaims copyright to this source code.  In place of
7690 ** a legal notice, here is a blessing:
7691 **
7692 **    May you do good and not evil.
7693 **    May you find forgiveness for yourself and forgive others.
7694 **    May you share freely, never taking more than you give.
7695 **
7696 *************************************************************************
7697 */
7698 
7699 #ifndef _SQLITE3RTREE_H_
7700 #define _SQLITE3RTREE_H_
7701 
7702 
7703 #if 0
7704 extern "C" {
7705 #endif
7706 
7707 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7708 
7709 /*
7710 ** Register a geometry callback named zGeom that can be used as part of an
7711 ** R-Tree geometry query as follows:
7712 **
7713 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7714 */
7715 SQLITE_API int sqlite3_rtree_geometry_callback(
7716   sqlite3 *db,
7717   const char *zGeom,
7718 #ifdef SQLITE_RTREE_INT_ONLY
7719   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7720 #else
7721   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7722 #endif
7723   void *pContext
7724 );
7725 
7726 
7727 /*
7728 ** A pointer to a structure of the following type is passed as the first
7729 ** argument to callbacks registered using rtree_geometry_callback().
7730 */
7731 struct sqlite3_rtree_geometry {
7732   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7733   int nParam;                     /* Size of array aParam[] */
7734   double *aParam;                 /* Parameters passed to SQL geom function */
7735   void *pUser;                    /* Callback implementation user data */
7736   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7737 };
7738 
7739 
7740 #if 0
7741 }  /* end of the 'extern "C"' block */
7742 #endif
7743 
7744 #endif  /* ifndef _SQLITE3RTREE_H_ */
7745 
7746 
7747 /************** End of sqlite3.h *********************************************/
7748 /************** Continuing where we left off in sqliteInt.h ******************/
7749 /************** Include hash.h in the middle of sqliteInt.h ******************/
7750 /************** Begin file hash.h ********************************************/
7751 /*
7752 ** 2001 September 22
7753 **
7754 ** The author disclaims copyright to this source code.  In place of
7755 ** a legal notice, here is a blessing:
7756 **
7757 **    May you do good and not evil.
7758 **    May you find forgiveness for yourself and forgive others.
7759 **    May you share freely, never taking more than you give.
7760 **
7761 *************************************************************************
7762 ** This is the header file for the generic hash-table implementation
7763 ** used in SQLite.
7764 */
7765 #ifndef _SQLITE_HASH_H_
7766 #define _SQLITE_HASH_H_
7767 
7768 /* Forward declarations of structures. */
7769 typedef struct Hash Hash;
7770 typedef struct HashElem HashElem;
7771 
7772 /* A complete hash table is an instance of the following structure.
7773 ** The internals of this structure are intended to be opaque -- client
7774 ** code should not attempt to access or modify the fields of this structure
7775 ** directly.  Change this structure only by using the routines below.
7776 ** However, some of the "procedures" and "functions" for modifying and
7777 ** accessing this structure are really macros, so we can't really make
7778 ** this structure opaque.
7779 **
7780 ** All elements of the hash table are on a single doubly-linked list.
7781 ** Hash.first points to the head of this list.
7782 **
7783 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7784 ** the global doubly-linked list.  The contents of the bucket are the
7785 ** element pointed to plus the next _ht.count-1 elements in the list.
7786 **
7787 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7788 ** by a linear search of the global list.  For small tables, the
7789 ** Hash.ht table is never allocated because if there are few elements
7790 ** in the table, it is faster to do a linear search than to manage
7791 ** the hash table.
7792 */
7793 struct Hash {
7794   unsigned int htsize;      /* Number of buckets in the hash table */
7795   unsigned int count;       /* Number of entries in this table */
7796   HashElem *first;          /* The first element of the array */
7797   struct _ht {              /* the hash table */
7798     int count;                 /* Number of entries with this hash */
7799     HashElem *chain;           /* Pointer to first entry with this hash */
7800   } *ht;
7801 };
7802 
7803 /* Each element in the hash table is an instance of the following
7804 ** structure.  All elements are stored on a single doubly-linked list.
7805 **
7806 ** Again, this structure is intended to be opaque, but it can't really
7807 ** be opaque because it is used by macros.
7808 */
7809 struct HashElem {
7810   HashElem *next, *prev;       /* Next and previous elements in the table */
7811   void *data;                  /* Data associated with this element */
7812   const char *pKey; int nKey;  /* Key associated with this element */
7813 };
7814 
7815 /*
7816 ** Access routines.  To delete, insert a NULL pointer.
7817 */
7818 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7819 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7820 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7821 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7822 
7823 /*
7824 ** Macros for looping over all elements of a hash table.  The idiom is
7825 ** like this:
7826 **
7827 **   Hash h;
7828 **   HashElem *p;
7829 **   ...
7830 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7831 **     SomeStructure *pData = sqliteHashData(p);
7832 **     // do something with pData
7833 **   }
7834 */
7835 #define sqliteHashFirst(H)  ((H)->first)
7836 #define sqliteHashNext(E)   ((E)->next)
7837 #define sqliteHashData(E)   ((E)->data)
7838 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7839 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7840 
7841 /*
7842 ** Number of entries in a hash table
7843 */
7844 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7845 
7846 #endif /* _SQLITE_HASH_H_ */
7847 
7848 /************** End of hash.h ************************************************/
7849 /************** Continuing where we left off in sqliteInt.h ******************/
7850 /************** Include parse.h in the middle of sqliteInt.h *****************/
7851 /************** Begin file parse.h *******************************************/
7852 #define TK_SEMI                            1
7853 #define TK_EXPLAIN                         2
7854 #define TK_QUERY                           3
7855 #define TK_PLAN                            4
7856 #define TK_BEGIN                           5
7857 #define TK_TRANSACTION                     6
7858 #define TK_DEFERRED                        7
7859 #define TK_IMMEDIATE                       8
7860 #define TK_EXCLUSIVE                       9
7861 #define TK_COMMIT                         10
7862 #define TK_END                            11
7863 #define TK_ROLLBACK                       12
7864 #define TK_SAVEPOINT                      13
7865 #define TK_RELEASE                        14
7866 #define TK_TO                             15
7867 #define TK_TABLE                          16
7868 #define TK_CREATE                         17
7869 #define TK_IF                             18
7870 #define TK_NOT                            19
7871 #define TK_EXISTS                         20
7872 #define TK_TEMP                           21
7873 #define TK_LP                             22
7874 #define TK_RP                             23
7875 #define TK_AS                             24
7876 #define TK_COMMA                          25
7877 #define TK_ID                             26
7878 #define TK_INDEXED                        27
7879 #define TK_ABORT                          28
7880 #define TK_ACTION                         29
7881 #define TK_AFTER                          30
7882 #define TK_ANALYZE                        31
7883 #define TK_ASC                            32
7884 #define TK_ATTACH                         33
7885 #define TK_BEFORE                         34
7886 #define TK_BY                             35
7887 #define TK_CASCADE                        36
7888 #define TK_CAST                           37
7889 #define TK_COLUMNKW                       38
7890 #define TK_CONFLICT                       39
7891 #define TK_DATABASE                       40
7892 #define TK_DESC                           41
7893 #define TK_DETACH                         42
7894 #define TK_EACH                           43
7895 #define TK_FAIL                           44
7896 #define TK_FOR                            45
7897 #define TK_IGNORE                         46
7898 #define TK_INITIALLY                      47
7899 #define TK_INSTEAD                        48
7900 #define TK_LIKE_KW                        49
7901 #define TK_MATCH                          50
7902 #define TK_NO                             51
7903 #define TK_KEY                            52
7904 #define TK_OF                             53
7905 #define TK_OFFSET                         54
7906 #define TK_PRAGMA                         55
7907 #define TK_RAISE                          56
7908 #define TK_REPLACE                        57
7909 #define TK_RESTRICT                       58
7910 #define TK_ROW                            59
7911 #define TK_TRIGGER                        60
7912 #define TK_VACUUM                         61
7913 #define TK_VIEW                           62
7914 #define TK_VIRTUAL                        63
7915 #define TK_REINDEX                        64
7916 #define TK_RENAME                         65
7917 #define TK_CTIME_KW                       66
7918 #define TK_ANY                            67
7919 #define TK_OR                             68
7920 #define TK_AND                            69
7921 #define TK_IS                             70
7922 #define TK_BETWEEN                        71
7923 #define TK_IN                             72
7924 #define TK_ISNULL                         73
7925 #define TK_NOTNULL                        74
7926 #define TK_NE                             75
7927 #define TK_EQ                             76
7928 #define TK_GT                             77
7929 #define TK_LE                             78
7930 #define TK_LT                             79
7931 #define TK_GE                             80
7932 #define TK_ESCAPE                         81
7933 #define TK_BITAND                         82
7934 #define TK_BITOR                          83
7935 #define TK_LSHIFT                         84
7936 #define TK_RSHIFT                         85
7937 #define TK_PLUS                           86
7938 #define TK_MINUS                          87
7939 #define TK_STAR                           88
7940 #define TK_SLASH                          89
7941 #define TK_REM                            90
7942 #define TK_CONCAT                         91
7943 #define TK_COLLATE                        92
7944 #define TK_BITNOT                         93
7945 #define TK_STRING                         94
7946 #define TK_JOIN_KW                        95
7947 #define TK_CONSTRAINT                     96
7948 #define TK_DEFAULT                        97
7949 #define TK_NULL                           98
7950 #define TK_PRIMARY                        99
7951 #define TK_UNIQUE                         100
7952 #define TK_CHECK                          101
7953 #define TK_REFERENCES                     102
7954 #define TK_AUTOINCR                       103
7955 #define TK_ON                             104
7956 #define TK_INSERT                         105
7957 #define TK_DELETE                         106
7958 #define TK_UPDATE                         107
7959 #define TK_SET                            108
7960 #define TK_DEFERRABLE                     109
7961 #define TK_FOREIGN                        110
7962 #define TK_DROP                           111
7963 #define TK_UNION                          112
7964 #define TK_ALL                            113
7965 #define TK_EXCEPT                         114
7966 #define TK_INTERSECT                      115
7967 #define TK_SELECT                         116
7968 #define TK_DISTINCT                       117
7969 #define TK_DOT                            118
7970 #define TK_FROM                           119
7971 #define TK_JOIN                           120
7972 #define TK_USING                          121
7973 #define TK_ORDER                          122
7974 #define TK_GROUP                          123
7975 #define TK_HAVING                         124
7976 #define TK_LIMIT                          125
7977 #define TK_WHERE                          126
7978 #define TK_INTO                           127
7979 #define TK_VALUES                         128
7980 #define TK_INTEGER                        129
7981 #define TK_FLOAT                          130
7982 #define TK_BLOB                           131
7983 #define TK_REGISTER                       132
7984 #define TK_VARIABLE                       133
7985 #define TK_CASE                           134
7986 #define TK_WHEN                           135
7987 #define TK_THEN                           136
7988 #define TK_ELSE                           137
7989 #define TK_INDEX                          138
7990 #define TK_ALTER                          139
7991 #define TK_ADD                            140
7992 #define TK_TO_TEXT                        141
7993 #define TK_TO_BLOB                        142
7994 #define TK_TO_NUMERIC                     143
7995 #define TK_TO_INT                         144
7996 #define TK_TO_REAL                        145
7997 #define TK_ISNOT                          146
7998 #define TK_END_OF_FILE                    147
7999 #define TK_ILLEGAL                        148
8000 #define TK_SPACE                          149
8001 #define TK_UNCLOSED_STRING                150
8002 #define TK_FUNCTION                       151
8003 #define TK_COLUMN                         152
8004 #define TK_AGG_FUNCTION                   153
8005 #define TK_AGG_COLUMN                     154
8006 #define TK_CONST_FUNC                     155
8007 #define TK_UMINUS                         156
8008 #define TK_UPLUS                          157
8009 
8010 /************** End of parse.h ***********************************************/
8011 /************** Continuing where we left off in sqliteInt.h ******************/
8012 #include <stdio.h>
8013 #include <stdlib.h>
8014 #include <string.h>
8015 #include <assert.h>
8016 #include <stddef.h>
8017 
8018 /*
8019 ** If compiling for a processor that lacks floating point support,
8020 ** substitute integer for floating-point
8021 */
8022 #ifdef SQLITE_OMIT_FLOATING_POINT
8023 # define double sqlite_int64
8024 # define float sqlite_int64
8025 # define LONGDOUBLE_TYPE sqlite_int64
8026 # ifndef SQLITE_BIG_DBL
8027 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8028 # endif
8029 # define SQLITE_OMIT_DATETIME_FUNCS 1
8030 # define SQLITE_OMIT_TRACE 1
8031 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8032 # undef SQLITE_HAVE_ISNAN
8033 #endif
8034 #ifndef SQLITE_BIG_DBL
8035 # define SQLITE_BIG_DBL (1e99)
8036 #endif
8037 
8038 /*
8039 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8040 ** afterward. Having this macro allows us to cause the C compiler
8041 ** to omit code used by TEMP tables without messy #ifndef statements.
8042 */
8043 #ifdef SQLITE_OMIT_TEMPDB
8044 #define OMIT_TEMPDB 1
8045 #else
8046 #define OMIT_TEMPDB 0
8047 #endif
8048 
8049 /*
8050 ** The "file format" number is an integer that is incremented whenever
8051 ** the VDBE-level file format changes.  The following macros define the
8052 ** the default file format for new databases and the maximum file format
8053 ** that the library can read.
8054 */
8055 #define SQLITE_MAX_FILE_FORMAT 4
8056 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8057 # define SQLITE_DEFAULT_FILE_FORMAT 4
8058 #endif
8059 
8060 /*
8061 ** Determine whether triggers are recursive by default.  This can be
8062 ** changed at run-time using a pragma.
8063 */
8064 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8065 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8066 #endif
8067 
8068 /*
8069 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8070 ** on the command-line
8071 */
8072 #ifndef SQLITE_TEMP_STORE
8073 # define SQLITE_TEMP_STORE 1
8074 #endif
8075 
8076 /*
8077 ** GCC does not define the offsetof() macro so we'll have to do it
8078 ** ourselves.
8079 */
8080 #ifndef offsetof
8081 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8082 #endif
8083 
8084 /*
8085 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8086 ** not, there are still machines out there that use EBCDIC.)
8087 */
8088 #if 'A' == '\301'
8089 # define SQLITE_EBCDIC 1
8090 #else
8091 # define SQLITE_ASCII 1
8092 #endif
8093 
8094 /*
8095 ** Integers of known sizes.  These typedefs might change for architectures
8096 ** where the sizes very.  Preprocessor macros are available so that the
8097 ** types can be conveniently redefined at compile-type.  Like this:
8098 **
8099 **         cc '-DUINTPTR_TYPE=long long int' ...
8100 */
8101 #ifndef UINT32_TYPE
8102 # ifdef HAVE_UINT32_T
8103 #  define UINT32_TYPE uint32_t
8104 # else
8105 #  define UINT32_TYPE unsigned int
8106 # endif
8107 #endif
8108 #ifndef UINT16_TYPE
8109 # ifdef HAVE_UINT16_T
8110 #  define UINT16_TYPE uint16_t
8111 # else
8112 #  define UINT16_TYPE unsigned short int
8113 # endif
8114 #endif
8115 #ifndef INT16_TYPE
8116 # ifdef HAVE_INT16_T
8117 #  define INT16_TYPE int16_t
8118 # else
8119 #  define INT16_TYPE short int
8120 # endif
8121 #endif
8122 #ifndef UINT8_TYPE
8123 # ifdef HAVE_UINT8_T
8124 #  define UINT8_TYPE uint8_t
8125 # else
8126 #  define UINT8_TYPE unsigned char
8127 # endif
8128 #endif
8129 #ifndef INT8_TYPE
8130 # ifdef HAVE_INT8_T
8131 #  define INT8_TYPE int8_t
8132 # else
8133 #  define INT8_TYPE signed char
8134 # endif
8135 #endif
8136 #ifndef LONGDOUBLE_TYPE
8137 # define LONGDOUBLE_TYPE long double
8138 #endif
8139 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8140 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8141 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8142 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8143 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8144 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8145 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8146 
8147 /*
8148 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8149 ** that can be stored in a u32 without loss of data.  The value
8150 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8151 ** have to specify the value in the less intuitive manner shown:
8152 */
8153 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8154 
8155 /*
8156 ** The datatype used to store estimates of the number of rows in a
8157 ** table or index.  This is an unsigned integer type.  For 99.9% of
8158 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8159 ** can be used at compile-time if desired.
8160 */
8161 #ifdef SQLITE_64BIT_STATS
8162  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8163 #else
8164  typedef u32 tRowcnt;    /* 32-bit is the default */
8165 #endif
8166 
8167 /*
8168 ** Macros to determine whether the machine is big or little endian,
8169 ** evaluated at runtime.
8170 */
8171 #ifdef SQLITE_AMALGAMATION
8172 SQLITE_PRIVATE const int sqlite3one = 1;
8173 #else
8174 SQLITE_PRIVATE const int sqlite3one;
8175 #endif
8176 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8177                              || defined(__x86_64) || defined(__x86_64__)
8178 # define SQLITE_BIGENDIAN    0
8179 # define SQLITE_LITTLEENDIAN 1
8180 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8181 #else
8182 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8183 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8184 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8185 #endif
8186 
8187 /*
8188 ** Constants for the largest and smallest possible 64-bit signed integers.
8189 ** These macros are designed to work correctly on both 32-bit and 64-bit
8190 ** compilers.
8191 */
8192 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8193 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8194 
8195 /*
8196 ** Round up a number to the next larger multiple of 8.  This is used
8197 ** to force 8-byte alignment on 64-bit architectures.
8198 */
8199 #define ROUND8(x)     (((x)+7)&~7)
8200 
8201 /*
8202 ** Round down to the nearest multiple of 8
8203 */
8204 #define ROUNDDOWN8(x) ((x)&~7)
8205 
8206 /*
8207 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8208 ** macro is used only within assert() to verify that the code gets
8209 ** all alignment restrictions correct.
8210 **
8211 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8212 ** underlying malloc() implemention might return us 4-byte aligned
8213 ** pointers.  In that case, only verify 4-byte alignment.
8214 */
8215 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8216 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8217 #else
8218 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8219 #endif
8220 
8221 
8222 /*
8223 ** An instance of the following structure is used to store the busy-handler
8224 ** callback for a given sqlite handle.
8225 **
8226 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8227 ** callback for the database handle. Each pager opened via the sqlite
8228 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8229 ** callback is currently invoked only from within pager.c.
8230 */
8231 typedef struct BusyHandler BusyHandler;
8232 struct BusyHandler {
8233   int (*xFunc)(void *,int);  /* The busy callback */
8234   void *pArg;                /* First arg to busy callback */
8235   int nBusy;                 /* Incremented with each busy call */
8236 };
8237 
8238 /*
8239 ** Name of the master database table.  The master database table
8240 ** is a special table that holds the names and attributes of all
8241 ** user tables and indices.
8242 */
8243 #define MASTER_NAME       "sqlite_master"
8244 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8245 
8246 /*
8247 ** The root-page of the master database table.
8248 */
8249 #define MASTER_ROOT       1
8250 
8251 /*
8252 ** The name of the schema table.
8253 */
8254 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8255 
8256 /*
8257 ** A convenience macro that returns the number of elements in
8258 ** an array.
8259 */
8260 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8261 
8262 /*
8263 ** Determine if the argument is a power of two
8264 */
8265 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8266 
8267 /*
8268 ** The following value as a destructor means to use sqlite3DbFree().
8269 ** The sqlite3DbFree() routine requires two parameters instead of the
8270 ** one parameter that destructors normally want.  So we have to introduce
8271 ** this magic value that the code knows to handle differently.  Any
8272 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8273 ** and SQLITE_TRANSIENT.
8274 */
8275 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8276 
8277 /*
8278 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8279 ** not support Writable Static Data (WSD) such as global and static variables.
8280 ** All variables must either be on the stack or dynamically allocated from
8281 ** the heap.  When WSD is unsupported, the variable declarations scattered
8282 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8283 ** macro is used for this purpose.  And instead of referencing the variable
8284 ** directly, we use its constant as a key to lookup the run-time allocated
8285 ** buffer that holds real variable.  The constant is also the initializer
8286 ** for the run-time allocated buffer.
8287 **
8288 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8289 ** macros become no-ops and have zero performance impact.
8290 */
8291 #ifdef SQLITE_OMIT_WSD
8292   #define SQLITE_WSD const
8293   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8294   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8295 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8296 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8297 #else
8298   #define SQLITE_WSD
8299   #define GLOBAL(t,v) v
8300   #define sqlite3GlobalConfig sqlite3Config
8301 #endif
8302 
8303 /*
8304 ** The following macros are used to suppress compiler warnings and to
8305 ** make it clear to human readers when a function parameter is deliberately
8306 ** left unused within the body of a function. This usually happens when
8307 ** a function is called via a function pointer. For example the
8308 ** implementation of an SQL aggregate step callback may not use the
8309 ** parameter indicating the number of arguments passed to the aggregate,
8310 ** if it knows that this is enforced elsewhere.
8311 **
8312 ** When a function parameter is not used at all within the body of a function,
8313 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8314 ** However, these macros may also be used to suppress warnings related to
8315 ** parameters that may or may not be used depending on compilation options.
8316 ** For example those parameters only used in assert() statements. In these
8317 ** cases the parameters are named as per the usual conventions.
8318 */
8319 #define UNUSED_PARAMETER(x) (void)(x)
8320 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8321 
8322 /*
8323 ** Forward references to structures
8324 */
8325 typedef struct AggInfo AggInfo;
8326 typedef struct AuthContext AuthContext;
8327 typedef struct AutoincInfo AutoincInfo;
8328 typedef struct Bitvec Bitvec;
8329 typedef struct CollSeq CollSeq;
8330 typedef struct Column Column;
8331 typedef struct Db Db;
8332 typedef struct Schema Schema;
8333 typedef struct Expr Expr;
8334 typedef struct ExprList ExprList;
8335 typedef struct ExprSpan ExprSpan;
8336 typedef struct FKey FKey;
8337 typedef struct FuncDestructor FuncDestructor;
8338 typedef struct FuncDef FuncDef;
8339 typedef struct FuncDefHash FuncDefHash;
8340 typedef struct IdList IdList;
8341 typedef struct Index Index;
8342 typedef struct IndexSample IndexSample;
8343 typedef struct KeyClass KeyClass;
8344 typedef struct KeyInfo KeyInfo;
8345 typedef struct Lookaside Lookaside;
8346 typedef struct LookasideSlot LookasideSlot;
8347 typedef struct Module Module;
8348 typedef struct NameContext NameContext;
8349 typedef struct Parse Parse;
8350 typedef struct RowSet RowSet;
8351 typedef struct Savepoint Savepoint;
8352 typedef struct Select Select;
8353 typedef struct SelectDest SelectDest;
8354 typedef struct SrcList SrcList;
8355 typedef struct StrAccum StrAccum;
8356 typedef struct Table Table;
8357 typedef struct TableLock TableLock;
8358 typedef struct Token Token;
8359 typedef struct Trigger Trigger;
8360 typedef struct TriggerPrg TriggerPrg;
8361 typedef struct TriggerStep TriggerStep;
8362 typedef struct UnpackedRecord UnpackedRecord;
8363 typedef struct VTable VTable;
8364 typedef struct VtabCtx VtabCtx;
8365 typedef struct Walker Walker;
8366 typedef struct WherePlan WherePlan;
8367 typedef struct WhereInfo WhereInfo;
8368 typedef struct WhereLevel WhereLevel;
8369 
8370 /*
8371 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8372 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8373 ** pointer types (i.e. FuncDef) defined above.
8374 */
8375 /************** Include btree.h in the middle of sqliteInt.h *****************/
8376 /************** Begin file btree.h *******************************************/
8377 /*
8378 ** 2001 September 15
8379 **
8380 ** The author disclaims copyright to this source code.  In place of
8381 ** a legal notice, here is a blessing:
8382 **
8383 **    May you do good and not evil.
8384 **    May you find forgiveness for yourself and forgive others.
8385 **    May you share freely, never taking more than you give.
8386 **
8387 *************************************************************************
8388 ** This header file defines the interface that the sqlite B-Tree file
8389 ** subsystem.  See comments in the source code for a detailed description
8390 ** of what each interface routine does.
8391 */
8392 #ifndef _BTREE_H_
8393 #define _BTREE_H_
8394 
8395 /* TODO: This definition is just included so other modules compile. It
8396 ** needs to be revisited.
8397 */
8398 #define SQLITE_N_BTREE_META 10
8399 
8400 /*
8401 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8402 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8403 */
8404 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8405   #define SQLITE_DEFAULT_AUTOVACUUM 0
8406 #endif
8407 
8408 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8409 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8410 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8411 
8412 /*
8413 ** Forward declarations of structure
8414 */
8415 typedef struct Btree Btree;
8416 typedef struct BtCursor BtCursor;
8417 typedef struct BtShared BtShared;
8418 
8419 
8420 SQLITE_PRIVATE int sqlite3BtreeOpen(
8421   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8422   const char *zFilename,   /* Name of database file to open */
8423   sqlite3 *db,             /* Associated database connection */
8424   Btree **ppBtree,         /* Return open Btree* here */
8425   int flags,               /* Flags */
8426   int vfsFlags             /* Flags passed through to VFS open */
8427 );
8428 
8429 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8430 ** following values.
8431 **
8432 ** NOTE:  These values must match the corresponding PAGER_ values in
8433 ** pager.h.
8434 */
8435 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8436 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8437 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8438 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8439 
8440 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8441 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8442 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8443 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8444 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8445 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8446 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8447 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8448 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8449 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8450 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8451 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8452 #endif
8453 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8454 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8455 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8456 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8457 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8458 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8459 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8460 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8461 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8462 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8463 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8464 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8465 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8466 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8467 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8468 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8469 
8470 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8471 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8472 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8473 
8474 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8475 
8476 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8477 ** of the flags shown below.
8478 **
8479 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8480 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8481 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8482 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8483 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8484 ** indices.)
8485 */
8486 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8487 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8488 
8489 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8490 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8491 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8492 
8493 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8494 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8495 
8496 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8497 
8498 /*
8499 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8500 ** should be one of the following values. The integer values are assigned
8501 ** to constants so that the offset of the corresponding field in an
8502 ** SQLite database header may be found using the following formula:
8503 **
8504 **   offset = 36 + (idx * 4)
8505 **
8506 ** For example, the free-page-count field is located at byte offset 36 of
8507 ** the database file header. The incr-vacuum-flag field is located at
8508 ** byte offset 64 (== 36+4*7).
8509 */
8510 #define BTREE_FREE_PAGE_COUNT     0
8511 #define BTREE_SCHEMA_VERSION      1
8512 #define BTREE_FILE_FORMAT         2
8513 #define BTREE_DEFAULT_CACHE_SIZE  3
8514 #define BTREE_LARGEST_ROOT_PAGE   4
8515 #define BTREE_TEXT_ENCODING       5
8516 #define BTREE_USER_VERSION        6
8517 #define BTREE_INCR_VACUUM         7
8518 
8519 /*
8520 ** Values that may be OR'd together to form the second argument of an
8521 ** sqlite3BtreeCursorHints() call.
8522 */
8523 #define BTREE_BULKLOAD 0x00000001
8524 
8525 SQLITE_PRIVATE int sqlite3BtreeCursor(
8526   Btree*,                              /* BTree containing table to open */
8527   int iTable,                          /* Index of root page */
8528   int wrFlag,                          /* 1 for writing.  0 for read-only */
8529   struct KeyInfo*,                     /* First argument to compare function */
8530   BtCursor *pCursor                    /* Space to write cursor structure */
8531 );
8532 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8533 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8534 
8535 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8536 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8537   BtCursor*,
8538   UnpackedRecord *pUnKey,
8539   i64 intKey,
8540   int bias,
8541   int *pRes
8542 );
8543 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8544 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8545 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8546                                   const void *pData, int nData,
8547                                   int nZero, int bias, int seekResult);
8548 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8549 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8550 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8551 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8552 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8553 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8554 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8555 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8556 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8557 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8558 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8559 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8560 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8561 
8562 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8563 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8564 
8565 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8566 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8567 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8568 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8569 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8570 
8571 #ifndef NDEBUG
8572 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8573 #endif
8574 
8575 #ifndef SQLITE_OMIT_BTREECOUNT
8576 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8577 #endif
8578 
8579 #ifdef SQLITE_TEST
8580 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8581 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8582 #endif
8583 
8584 #ifndef SQLITE_OMIT_WAL
8585 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8586 #endif
8587 
8588 /*
8589 ** If we are not using shared cache, then there is no need to
8590 ** use mutexes to access the BtShared structures.  So make the
8591 ** Enter and Leave procedures no-ops.
8592 */
8593 #ifndef SQLITE_OMIT_SHARED_CACHE
8594 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8595 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8596 #else
8597 # define sqlite3BtreeEnter(X)
8598 # define sqlite3BtreeEnterAll(X)
8599 #endif
8600 
8601 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8602 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8603 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8604 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8605 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8606 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8607 #ifndef NDEBUG
8608   /* These routines are used inside assert() statements only. */
8609 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8610 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8611 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8612 #endif
8613 #else
8614 
8615 # define sqlite3BtreeSharable(X) 0
8616 # define sqlite3BtreeLeave(X)
8617 # define sqlite3BtreeEnterCursor(X)
8618 # define sqlite3BtreeLeaveCursor(X)
8619 # define sqlite3BtreeLeaveAll(X)
8620 
8621 # define sqlite3BtreeHoldsMutex(X) 1
8622 # define sqlite3BtreeHoldsAllMutexes(X) 1
8623 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8624 #endif
8625 
8626 
8627 #endif /* _BTREE_H_ */
8628 
8629 /************** End of btree.h ***********************************************/
8630 /************** Continuing where we left off in sqliteInt.h ******************/
8631 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8632 /************** Begin file vdbe.h ********************************************/
8633 /*
8634 ** 2001 September 15
8635 **
8636 ** The author disclaims copyright to this source code.  In place of
8637 ** a legal notice, here is a blessing:
8638 **
8639 **    May you do good and not evil.
8640 **    May you find forgiveness for yourself and forgive others.
8641 **    May you share freely, never taking more than you give.
8642 **
8643 *************************************************************************
8644 ** Header file for the Virtual DataBase Engine (VDBE)
8645 **
8646 ** This header defines the interface to the virtual database engine
8647 ** or VDBE.  The VDBE implements an abstract machine that runs a
8648 ** simple program to access and modify the underlying database.
8649 */
8650 #ifndef _SQLITE_VDBE_H_
8651 #define _SQLITE_VDBE_H_
8652 /* #include <stdio.h> */
8653 
8654 /*
8655 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8656 ** in the source file sqliteVdbe.c are allowed to see the insides
8657 ** of this structure.
8658 */
8659 typedef struct Vdbe Vdbe;
8660 
8661 /*
8662 ** The names of the following types declared in vdbeInt.h are required
8663 ** for the VdbeOp definition.
8664 */
8665 typedef struct VdbeFunc VdbeFunc;
8666 typedef struct Mem Mem;
8667 typedef struct SubProgram SubProgram;
8668 
8669 /*
8670 ** A single instruction of the virtual machine has an opcode
8671 ** and as many as three operands.  The instruction is recorded
8672 ** as an instance of the following structure:
8673 */
8674 struct VdbeOp {
8675   u8 opcode;          /* What operation to perform */
8676   signed char p4type; /* One of the P4_xxx constants for p4 */
8677   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8678   u8 p5;              /* Fifth parameter is an unsigned character */
8679   int p1;             /* First operand */
8680   int p2;             /* Second parameter (often the jump destination) */
8681   int p3;             /* The third parameter */
8682   union {             /* fourth parameter */
8683     int i;                 /* Integer value if p4type==P4_INT32 */
8684     void *p;               /* Generic pointer */
8685     char *z;               /* Pointer to data for string (char array) types */
8686     i64 *pI64;             /* Used when p4type is P4_INT64 */
8687     double *pReal;         /* Used when p4type is P4_REAL */
8688     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8689     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8690     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8691     Mem *pMem;             /* Used when p4type is P4_MEM */
8692     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8693     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8694     int *ai;               /* Used when p4type is P4_INTARRAY */
8695     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8696     int (*xAdvance)(BtCursor *, int *);
8697   } p4;
8698 #ifdef SQLITE_DEBUG
8699   char *zComment;          /* Comment to improve readability */
8700 #endif
8701 #ifdef VDBE_PROFILE
8702   int cnt;                 /* Number of times this instruction was executed */
8703   u64 cycles;              /* Total time spent executing this instruction */
8704 #endif
8705 };
8706 typedef struct VdbeOp VdbeOp;
8707 
8708 
8709 /*
8710 ** A sub-routine used to implement a trigger program.
8711 */
8712 struct SubProgram {
8713   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8714   int nOp;                      /* Elements in aOp[] */
8715   int nMem;                     /* Number of memory cells required */
8716   int nCsr;                     /* Number of cursors required */
8717   int nOnce;                    /* Number of OP_Once instructions */
8718   void *token;                  /* id that may be used to recursive triggers */
8719   SubProgram *pNext;            /* Next sub-program already visited */
8720 };
8721 
8722 /*
8723 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8724 ** it takes up less space.
8725 */
8726 struct VdbeOpList {
8727   u8 opcode;          /* What operation to perform */
8728   signed char p1;     /* First operand */
8729   signed char p2;     /* Second parameter (often the jump destination) */
8730   signed char p3;     /* Third parameter */
8731 };
8732 typedef struct VdbeOpList VdbeOpList;
8733 
8734 /*
8735 ** Allowed values of VdbeOp.p4type
8736 */
8737 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8738 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8739 #define P4_STATIC   (-2)  /* Pointer to a static string */
8740 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8741 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8742 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8743 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8744 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8745 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8746 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8747 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8748 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8749 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8750 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8751 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8752 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8753 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8754 
8755 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8756 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8757 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8758 ** gets freed when the Vdbe is finalized so it still should be obtained
8759 ** from a single sqliteMalloc().  But no copy is made and the calling
8760 ** function should *not* try to free the KeyInfo.
8761 */
8762 #define P4_KEYINFO_HANDOFF (-16)
8763 #define P4_KEYINFO_STATIC  (-17)
8764 
8765 /*
8766 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8767 ** number of columns of data returned by the statement.
8768 */
8769 #define COLNAME_NAME     0
8770 #define COLNAME_DECLTYPE 1
8771 #define COLNAME_DATABASE 2
8772 #define COLNAME_TABLE    3
8773 #define COLNAME_COLUMN   4
8774 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8775 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8776 #else
8777 # ifdef SQLITE_OMIT_DECLTYPE
8778 #   define COLNAME_N      1      /* Store only the name */
8779 # else
8780 #   define COLNAME_N      2      /* Store the name and decltype */
8781 # endif
8782 #endif
8783 
8784 /*
8785 ** The following macro converts a relative address in the p2 field
8786 ** of a VdbeOp structure into a negative number so that
8787 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8788 ** the macro again restores the address.
8789 */
8790 #define ADDR(X)  (-1-(X))
8791 
8792 /*
8793 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8794 ** header file that defines a number for each opcode used by the VDBE.
8795 */
8796 /************** Include opcodes.h in the middle of vdbe.h ********************/
8797 /************** Begin file opcodes.h *****************************************/
8798 /* Automatically generated.  Do not edit */
8799 /* See the mkopcodeh.awk script for details */
8800 #define OP_Goto                                 1
8801 #define OP_Gosub                                2
8802 #define OP_Return                               3
8803 #define OP_Yield                                4
8804 #define OP_HaltIfNull                           5
8805 #define OP_Halt                                 6
8806 #define OP_Integer                              7
8807 #define OP_Int64                                8
8808 #define OP_Real                               130   /* same as TK_FLOAT    */
8809 #define OP_String8                             94   /* same as TK_STRING   */
8810 #define OP_String                               9
8811 #define OP_Null                                10
8812 #define OP_Blob                                11
8813 #define OP_Variable                            12
8814 #define OP_Move                                13
8815 #define OP_Copy                                14
8816 #define OP_SCopy                               15
8817 #define OP_ResultRow                           16
8818 #define OP_Concat                              91   /* same as TK_CONCAT   */
8819 #define OP_Add                                 86   /* same as TK_PLUS     */
8820 #define OP_Subtract                            87   /* same as TK_MINUS    */
8821 #define OP_Multiply                            88   /* same as TK_STAR     */
8822 #define OP_Divide                              89   /* same as TK_SLASH    */
8823 #define OP_Remainder                           90   /* same as TK_REM      */
8824 #define OP_CollSeq                             17
8825 #define OP_Function                            18
8826 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8827 #define OP_BitOr                               83   /* same as TK_BITOR    */
8828 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8829 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8830 #define OP_AddImm                              20
8831 #define OP_MustBeInt                           21
8832 #define OP_RealAffinity                        22
8833 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8834 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8835 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8836 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8837 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8838 #define OP_Eq                                  76   /* same as TK_EQ       */
8839 #define OP_Ne                                  75   /* same as TK_NE       */
8840 #define OP_Lt                                  79   /* same as TK_LT       */
8841 #define OP_Le                                  78   /* same as TK_LE       */
8842 #define OP_Gt                                  77   /* same as TK_GT       */
8843 #define OP_Ge                                  80   /* same as TK_GE       */
8844 #define OP_Permutation                         23
8845 #define OP_Compare                             24
8846 #define OP_Jump                                25
8847 #define OP_And                                 69   /* same as TK_AND      */
8848 #define OP_Or                                  68   /* same as TK_OR       */
8849 #define OP_Not                                 19   /* same as TK_NOT      */
8850 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8851 #define OP_Once                                26
8852 #define OP_If                                  27
8853 #define OP_IfNot                               28
8854 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8855 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8856 #define OP_Column                              29
8857 #define OP_Affinity                            30
8858 #define OP_MakeRecord                          31
8859 #define OP_Count                               32
8860 #define OP_Savepoint                           33
8861 #define OP_AutoCommit                          34
8862 #define OP_Transaction                         35
8863 #define OP_ReadCookie                          36
8864 #define OP_SetCookie                           37
8865 #define OP_VerifyCookie                        38
8866 #define OP_OpenRead                            39
8867 #define OP_OpenWrite                           40
8868 #define OP_OpenAutoindex                       41
8869 #define OP_OpenEphemeral                       42
8870 #define OP_SorterOpen                          43
8871 #define OP_OpenPseudo                          44
8872 #define OP_Close                               45
8873 #define OP_SeekLt                              46
8874 #define OP_SeekLe                              47
8875 #define OP_SeekGe                              48
8876 #define OP_SeekGt                              49
8877 #define OP_Seek                                50
8878 #define OP_NotFound                            51
8879 #define OP_Found                               52
8880 #define OP_IsUnique                            53
8881 #define OP_NotExists                           54
8882 #define OP_Sequence                            55
8883 #define OP_NewRowid                            56
8884 #define OP_Insert                              57
8885 #define OP_InsertInt                           58
8886 #define OP_Delete                              59
8887 #define OP_ResetCount                          60
8888 #define OP_SorterCompare                       61
8889 #define OP_SorterData                          62
8890 #define OP_RowKey                              63
8891 #define OP_RowData                             64
8892 #define OP_Rowid                               65
8893 #define OP_NullRow                             66
8894 #define OP_Last                                67
8895 #define OP_SorterSort                          70
8896 #define OP_Sort                                71
8897 #define OP_Rewind                              72
8898 #define OP_SorterNext                          81
8899 #define OP_Prev                                92
8900 #define OP_Next                                95
8901 #define OP_SorterInsert                        96
8902 #define OP_IdxInsert                           97
8903 #define OP_IdxDelete                           98
8904 #define OP_IdxRowid                            99
8905 #define OP_IdxLT                              100
8906 #define OP_IdxGE                              101
8907 #define OP_Destroy                            102
8908 #define OP_Clear                              103
8909 #define OP_CreateIndex                        104
8910 #define OP_CreateTable                        105
8911 #define OP_ParseSchema                        106
8912 #define OP_LoadAnalysis                       107
8913 #define OP_DropTable                          108
8914 #define OP_DropIndex                          109
8915 #define OP_DropTrigger                        110
8916 #define OP_IntegrityCk                        111
8917 #define OP_RowSetAdd                          112
8918 #define OP_RowSetRead                         113
8919 #define OP_RowSetTest                         114
8920 #define OP_Program                            115
8921 #define OP_Param                              116
8922 #define OP_FkCounter                          117
8923 #define OP_FkIfZero                           118
8924 #define OP_MemMax                             119
8925 #define OP_IfPos                              120
8926 #define OP_IfNeg                              121
8927 #define OP_IfZero                             122
8928 #define OP_AggStep                            123
8929 #define OP_AggFinal                           124
8930 #define OP_Checkpoint                         125
8931 #define OP_JournalMode                        126
8932 #define OP_Vacuum                             127
8933 #define OP_IncrVacuum                         128
8934 #define OP_Expire                             129
8935 #define OP_TableLock                          131
8936 #define OP_VBegin                             132
8937 #define OP_VCreate                            133
8938 #define OP_VDestroy                           134
8939 #define OP_VOpen                              135
8940 #define OP_VFilter                            136
8941 #define OP_VColumn                            137
8942 #define OP_VNext                              138
8943 #define OP_VRename                            139
8944 #define OP_VUpdate                            140
8945 #define OP_Pagecount                          146
8946 #define OP_MaxPgcnt                           147
8947 #define OP_Trace                              148
8948 #define OP_Noop                               149
8949 #define OP_Explain                            150
8950 
8951 
8952 /* Properties such as "out2" or "jump" that are specified in
8953 ** comments following the "case" for each opcode in the vdbe.c
8954 ** are encoded into bitvectors as follows:
8955 */
8956 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8957 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8958 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8959 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8960 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8961 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8962 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8963 #define OPFLG_INITIALIZER {\
8964 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8965 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
8966 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8967 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8968 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8969 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8970 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8971 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8972 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8973 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8974 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8975 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8976 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8977 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8978 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8979 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8980 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8981 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8982 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8983 
8984 /************** End of opcodes.h *********************************************/
8985 /************** Continuing where we left off in vdbe.h ***********************/
8986 
8987 /*
8988 ** Prototypes for the VDBE interface.  See comments on the implementation
8989 ** for a description of what each of these routines does.
8990 */
8991 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8992 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8993 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8994 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8995 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8996 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8997 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8998 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8999 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9000 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9001 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9002 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9003 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9004 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9005 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9006 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9007 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9008 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9009 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9010 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9011 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9012 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9013 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9014 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9015 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9016 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9017 #ifdef SQLITE_DEBUG
9018 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9019 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
9020 #endif
9021 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9022 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9023 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9024 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9025 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9026 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9027 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9028 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9029 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9030 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9031 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
9032 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9033 #ifndef SQLITE_OMIT_TRACE
9034 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9035 #endif
9036 
9037 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9038 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9039 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9040 
9041 #ifndef SQLITE_OMIT_TRIGGER
9042 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9043 #endif
9044 
9045 
9046 #ifndef NDEBUG
9047 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9048 # define VdbeComment(X)  sqlite3VdbeComment X
9049 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9050 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9051 #else
9052 # define VdbeComment(X)
9053 # define VdbeNoopComment(X)
9054 #endif
9055 
9056 #endif
9057 
9058 /************** End of vdbe.h ************************************************/
9059 /************** Continuing where we left off in sqliteInt.h ******************/
9060 /************** Include pager.h in the middle of sqliteInt.h *****************/
9061 /************** Begin file pager.h *******************************************/
9062 /*
9063 ** 2001 September 15
9064 **
9065 ** The author disclaims copyright to this source code.  In place of
9066 ** a legal notice, here is a blessing:
9067 **
9068 **    May you do good and not evil.
9069 **    May you find forgiveness for yourself and forgive others.
9070 **    May you share freely, never taking more than you give.
9071 **
9072 *************************************************************************
9073 ** This header file defines the interface that the sqlite page cache
9074 ** subsystem.  The page cache subsystem reads and writes a file a page
9075 ** at a time and provides a journal for rollback.
9076 */
9077 
9078 #ifndef _PAGER_H_
9079 #define _PAGER_H_
9080 
9081 /*
9082 ** Default maximum size for persistent journal files. A negative
9083 ** value means no limit. This value may be overridden using the
9084 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9085 */
9086 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9087   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9088 #endif
9089 
9090 /*
9091 ** The type used to represent a page number.  The first page in a file
9092 ** is called page 1.  0 is used to represent "not a page".
9093 */
9094 typedef u32 Pgno;
9095 
9096 /*
9097 ** Each open file is managed by a separate instance of the "Pager" structure.
9098 */
9099 typedef struct Pager Pager;
9100 
9101 /*
9102 ** Handle type for pages.
9103 */
9104 typedef struct PgHdr DbPage;
9105 
9106 /*
9107 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9108 ** reserved for working around a windows/posix incompatibility). It is
9109 ** used in the journal to signify that the remainder of the journal file
9110 ** is devoted to storing a master journal name - there are no more pages to
9111 ** roll back. See comments for function writeMasterJournal() in pager.c
9112 ** for details.
9113 */
9114 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9115 
9116 /*
9117 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9118 **
9119 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9120 */
9121 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9122 #define PAGER_MEMORY        0x0002    /* In-memory database */
9123 
9124 /*
9125 ** Valid values for the second argument to sqlite3PagerLockingMode().
9126 */
9127 #define PAGER_LOCKINGMODE_QUERY      -1
9128 #define PAGER_LOCKINGMODE_NORMAL      0
9129 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
9130 
9131 /*
9132 ** Numeric constants that encode the journalmode.
9133 */
9134 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9135 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9136 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9137 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9138 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9139 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9140 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9141 
9142 /*
9143 ** The remainder of this file contains the declarations of the functions
9144 ** that make up the Pager sub-system API. See source code comments for
9145 ** a detailed description of each routine.
9146 */
9147 
9148 /* Open and close a Pager connection. */
9149 SQLITE_PRIVATE int sqlite3PagerOpen(
9150   sqlite3_vfs*,
9151   Pager **ppPager,
9152   const char*,
9153   int,
9154   int,
9155   int,
9156   void(*)(DbPage*)
9157 );
9158 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9159 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9160 
9161 /* Functions used to configure a Pager object. */
9162 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9163 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9164 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9165 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9166 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9167 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9168 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9169 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9170 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9171 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9172 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9173 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9174 
9175 /* Functions used to obtain and release page references. */
9176 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9177 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9178 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9179 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9180 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9181 
9182 /* Operations on page references. */
9183 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9184 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9185 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9186 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9187 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9188 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9189 
9190 /* Functions used to manage pager transactions and savepoints. */
9191 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9192 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9193 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9194 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9195 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9196 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9197 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9198 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9199 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9200 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9201 
9202 #ifndef SQLITE_OMIT_WAL
9203 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9204 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9205 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9206 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9207 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9208 #endif
9209 
9210 #ifdef SQLITE_ENABLE_ZIPVFS
9211 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9212 #endif
9213 
9214 /* Functions used to query pager state and configuration. */
9215 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9216 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9217 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9218 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9219 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9220 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9221 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9222 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9223 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9224 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9225 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9226 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9227 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9228 
9229 /* Functions used to truncate the database file. */
9230 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9231 
9232 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9233 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9234 #endif
9235 
9236 /* Functions to support testing and debugging. */
9237 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9238 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9239 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9240 #endif
9241 #ifdef SQLITE_TEST
9242 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9243 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9244   void disable_simulated_io_errors(void);
9245   void enable_simulated_io_errors(void);
9246 #else
9247 # define disable_simulated_io_errors()
9248 # define enable_simulated_io_errors()
9249 #endif
9250 
9251 #endif /* _PAGER_H_ */
9252 
9253 /************** End of pager.h ***********************************************/
9254 /************** Continuing where we left off in sqliteInt.h ******************/
9255 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9256 /************** Begin file pcache.h ******************************************/
9257 /*
9258 ** 2008 August 05
9259 **
9260 ** The author disclaims copyright to this source code.  In place of
9261 ** a legal notice, here is a blessing:
9262 **
9263 **    May you do good and not evil.
9264 **    May you find forgiveness for yourself and forgive others.
9265 **    May you share freely, never taking more than you give.
9266 **
9267 *************************************************************************
9268 ** This header file defines the interface that the sqlite page cache
9269 ** subsystem.
9270 */
9271 
9272 #ifndef _PCACHE_H_
9273 
9274 typedef struct PgHdr PgHdr;
9275 typedef struct PCache PCache;
9276 
9277 /*
9278 ** Every page in the cache is controlled by an instance of the following
9279 ** structure.
9280 */
9281 struct PgHdr {
9282   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9283   void *pData;                   /* Page data */
9284   void *pExtra;                  /* Extra content */
9285   PgHdr *pDirty;                 /* Transient list of dirty pages */
9286   Pager *pPager;                 /* The pager this page is part of */
9287   Pgno pgno;                     /* Page number for this page */
9288 #ifdef SQLITE_CHECK_PAGES
9289   u32 pageHash;                  /* Hash of page content */
9290 #endif
9291   u16 flags;                     /* PGHDR flags defined below */
9292 
9293   /**********************************************************************
9294   ** Elements above are public.  All that follows is private to pcache.c
9295   ** and should not be accessed by other modules.
9296   */
9297   i16 nRef;                      /* Number of users of this page */
9298   PCache *pCache;                /* Cache that owns this page */
9299 
9300   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9301   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9302 };
9303 
9304 /* Bit values for PgHdr.flags */
9305 #define PGHDR_DIRTY             0x002  /* Page has changed */
9306 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9307                                        ** writing this page to the database */
9308 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9309 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9310 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9311 
9312 /* Initialize and shutdown the page cache subsystem */
9313 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9314 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9315 
9316 /* Page cache buffer management:
9317 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9318 */
9319 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9320 
9321 /* Create a new pager cache.
9322 ** Under memory stress, invoke xStress to try to make pages clean.
9323 ** Only clean and unpinned pages can be reclaimed.
9324 */
9325 SQLITE_PRIVATE void sqlite3PcacheOpen(
9326   int szPage,                    /* Size of every page */
9327   int szExtra,                   /* Extra space associated with each page */
9328   int bPurgeable,                /* True if pages are on backing store */
9329   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9330   void *pStress,                 /* Argument to xStress */
9331   PCache *pToInit                /* Preallocated space for the PCache */
9332 );
9333 
9334 /* Modify the page-size after the cache has been created. */
9335 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9336 
9337 /* Return the size in bytes of a PCache object.  Used to preallocate
9338 ** storage space.
9339 */
9340 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9341 
9342 /* One release per successful fetch.  Page is pinned until released.
9343 ** Reference counted.
9344 */
9345 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9346 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9347 
9348 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9349 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9350 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9351 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9352 
9353 /* Change a page number.  Used by incr-vacuum. */
9354 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9355 
9356 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9357 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9358 
9359 /* Get a list of all dirty pages in the cache, sorted by page number */
9360 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9361 
9362 /* Reset and close the cache object */
9363 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9364 
9365 /* Clear flags from pages of the page cache */
9366 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9367 
9368 /* Discard the contents of the cache */
9369 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9370 
9371 /* Return the total number of outstanding page references */
9372 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9373 
9374 /* Increment the reference count of an existing page */
9375 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9376 
9377 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9378 
9379 /* Return the total number of pages stored in the cache */
9380 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9381 
9382 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9383 /* Iterate through all dirty pages currently stored in the cache. This
9384 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
9385 ** library is built.
9386 */
9387 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9388 #endif
9389 
9390 /* Set and get the suggested cache-size for the specified pager-cache.
9391 **
9392 ** If no global maximum is configured, then the system attempts to limit
9393 ** the total number of pages cached by purgeable pager-caches to the sum
9394 ** of the suggested cache-sizes.
9395 */
9396 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9397 #ifdef SQLITE_TEST
9398 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9399 #endif
9400 
9401 /* Free up as much memory as possible from the page cache */
9402 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9403 
9404 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9405 /* Try to return memory used by the pcache module to the main memory heap */
9406 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9407 #endif
9408 
9409 #ifdef SQLITE_TEST
9410 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9411 #endif
9412 
9413 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9414 
9415 #endif /* _PCACHE_H_ */
9416 
9417 /************** End of pcache.h **********************************************/
9418 /************** Continuing where we left off in sqliteInt.h ******************/
9419 
9420 /************** Include os.h in the middle of sqliteInt.h ********************/
9421 /************** Begin file os.h **********************************************/
9422 /*
9423 ** 2001 September 16
9424 **
9425 ** The author disclaims copyright to this source code.  In place of
9426 ** a legal notice, here is a blessing:
9427 **
9428 **    May you do good and not evil.
9429 **    May you find forgiveness for yourself and forgive others.
9430 **    May you share freely, never taking more than you give.
9431 **
9432 ******************************************************************************
9433 **
9434 ** This header file (together with is companion C source-code file
9435 ** "os.c") attempt to abstract the underlying operating system so that
9436 ** the SQLite library will work on both POSIX and windows systems.
9437 **
9438 ** This header file is #include-ed by sqliteInt.h and thus ends up
9439 ** being included by every source file.
9440 */
9441 #ifndef _SQLITE_OS_H_
9442 #define _SQLITE_OS_H_
9443 
9444 /*
9445 ** Figure out if we are dealing with Unix, Windows, or some other
9446 ** operating system.  After the following block of preprocess macros,
9447 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
9448 ** will defined to either 1 or 0.  One of the four will be 1.  The other
9449 ** three will be 0.
9450 */
9451 #if defined(SQLITE_OS_OTHER)
9452 # if SQLITE_OS_OTHER==1
9453 #   undef SQLITE_OS_UNIX
9454 #   define SQLITE_OS_UNIX 0
9455 #   undef SQLITE_OS_WIN
9456 #   define SQLITE_OS_WIN 0
9457 # else
9458 #   undef SQLITE_OS_OTHER
9459 # endif
9460 #endif
9461 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9462 # define SQLITE_OS_OTHER 0
9463 # ifndef SQLITE_OS_WIN
9464 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9465 #     define SQLITE_OS_WIN 1
9466 #     define SQLITE_OS_UNIX 0
9467 #   else
9468 #     define SQLITE_OS_WIN 0
9469 #     define SQLITE_OS_UNIX 1
9470 #  endif
9471 # else
9472 #  define SQLITE_OS_UNIX 0
9473 # endif
9474 #else
9475 # ifndef SQLITE_OS_WIN
9476 #  define SQLITE_OS_WIN 0
9477 # endif
9478 #endif
9479 
9480 #if SQLITE_OS_WIN
9481 # include <windows.h>
9482 #endif
9483 
9484 /*
9485 ** Determine if we are dealing with Windows NT.
9486 **
9487 ** We ought to be able to determine if we are compiling for win98 or winNT
9488 ** using the _WIN32_WINNT macro as follows:
9489 **
9490 ** #if defined(_WIN32_WINNT)
9491 ** # define SQLITE_OS_WINNT 1
9492 ** #else
9493 ** # define SQLITE_OS_WINNT 0
9494 ** #endif
9495 **
9496 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9497 ** so the above test does not work.  We'll just assume that everything is
9498 ** winNT unless the programmer explicitly says otherwise by setting
9499 ** SQLITE_OS_WINNT to 0.
9500 */
9501 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9502 # define SQLITE_OS_WINNT 1
9503 #endif
9504 
9505 /*
9506 ** Determine if we are dealing with WindowsCE - which has a much
9507 ** reduced API.
9508 */
9509 #if defined(_WIN32_WCE)
9510 # define SQLITE_OS_WINCE 1
9511 #else
9512 # define SQLITE_OS_WINCE 0
9513 #endif
9514 
9515 /*
9516 ** Determine if we are dealing with WinRT, which provides only a subset of
9517 ** the full Win32 API.
9518 */
9519 #if !defined(SQLITE_OS_WINRT)
9520 # define SQLITE_OS_WINRT 0
9521 #endif
9522 
9523 /*
9524 ** When compiled for WinCE or WinRT, there is no concept of the current
9525 ** directory.
9526  */
9527 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
9528 # define SQLITE_CURDIR 1
9529 #endif
9530 
9531 /* If the SET_FULLSYNC macro is not defined above, then make it
9532 ** a no-op
9533 */
9534 #ifndef SET_FULLSYNC
9535 # define SET_FULLSYNC(x,y)
9536 #endif
9537 
9538 /*
9539 ** The default size of a disk sector
9540 */
9541 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9542 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9543 #endif
9544 
9545 /*
9546 ** Temporary files are named starting with this prefix followed by 16 random
9547 ** alphanumeric characters, and no file extension. They are stored in the
9548 ** OS's standard temporary file directory, and are deleted prior to exit.
9549 ** If sqlite is being embedded in another program, you may wish to change the
9550 ** prefix to reflect your program's name, so that if your program exits
9551 ** prematurely, old temporary files can be easily identified. This can be done
9552 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9553 **
9554 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9555 ** Mcafee started using SQLite in their anti-virus product and it
9556 ** started putting files with the "sqlite" name in the c:/temp folder.
9557 ** This annoyed many windows users.  Those users would then do a
9558 ** Google search for "sqlite", find the telephone numbers of the
9559 ** developers and call to wake them up at night and complain.
9560 ** For this reason, the default name prefix is changed to be "sqlite"
9561 ** spelled backwards.  So the temp files are still identified, but
9562 ** anybody smart enough to figure out the code is also likely smart
9563 ** enough to know that calling the developer will not help get rid
9564 ** of the file.
9565 */
9566 #ifndef SQLITE_TEMP_FILE_PREFIX
9567 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9568 #endif
9569 
9570 /*
9571 ** The following values may be passed as the second argument to
9572 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9573 **
9574 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9575 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9576 **            any time. Other processes may hold and obtain new SHARED locks.
9577 ** PENDING:   A single process may hold a PENDING lock on a file at
9578 **            any one time. Existing SHARED locks may persist, but no new
9579 **            SHARED locks may be obtained by other processes.
9580 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9581 **
9582 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9583 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9584 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9585 ** sqlite3OsLock().
9586 */
9587 #define NO_LOCK         0
9588 #define SHARED_LOCK     1
9589 #define RESERVED_LOCK   2
9590 #define PENDING_LOCK    3
9591 #define EXCLUSIVE_LOCK  4
9592 
9593 /*
9594 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9595 **
9596 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9597 ** those functions are not available.  So we use only LockFile() and
9598 ** UnlockFile().
9599 **
9600 ** LockFile() prevents not just writing but also reading by other processes.
9601 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
9602 ** byte out of a specific range of bytes. The lock byte is obtained at
9603 ** random so two separate readers can probably access the file at the
9604 ** same time, unless they are unlucky and choose the same lock byte.
9605 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9606 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9607 ** a single byte of the file that is designated as the reserved lock byte.
9608 ** A PENDING_LOCK is obtained by locking a designated byte different from
9609 ** the RESERVED_LOCK byte.
9610 **
9611 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9612 ** which means we can use reader/writer locks.  When reader/writer locks
9613 ** are used, the lock is placed on the same range of bytes that is used
9614 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9615 ** will support two or more Win95 readers or two or more WinNT readers.
9616 ** But a single Win95 reader will lock out all WinNT readers and a single
9617 ** WinNT reader will lock out all other Win95 readers.
9618 **
9619 ** The following #defines specify the range of bytes used for locking.
9620 ** SHARED_SIZE is the number of bytes available in the pool from which
9621 ** a random byte is selected for a shared lock.  The pool of bytes for
9622 ** shared locks begins at SHARED_FIRST.
9623 **
9624 ** The same locking strategy and
9625 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9626 ** clients on win95, winNT, and unix all talking to the same shared file
9627 ** and all locking correctly.  To do so would require that samba (or whatever
9628 ** tool is being used for file sharing) implements locks correctly between
9629 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9630 ** using the same locking range we are at least open to the possibility.
9631 **
9632 ** Locking in windows is manditory.  For this reason, we cannot store
9633 ** actual data in the bytes used for locking.  The pager never allocates
9634 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9635 ** that all locks will fit on a single page even at the minimum page size.
9636 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9637 ** is set high so that we don't have to allocate an unused page except
9638 ** for very large databases.  But one should test the page skipping logic
9639 ** by setting PENDING_BYTE low and running the entire regression suite.
9640 **
9641 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9642 ** file format.  Depending on how it is changed, you might not notice
9643 ** the incompatibility right away, even running a full regression test.
9644 ** The default location of PENDING_BYTE is the first byte past the
9645 ** 1GB boundary.
9646 **
9647 */
9648 #ifdef SQLITE_OMIT_WSD
9649 # define PENDING_BYTE     (0x40000000)
9650 #else
9651 # define PENDING_BYTE      sqlite3PendingByte
9652 #endif
9653 #define RESERVED_BYTE     (PENDING_BYTE+1)
9654 #define SHARED_FIRST      (PENDING_BYTE+2)
9655 #define SHARED_SIZE       510
9656 
9657 /*
9658 ** Wrapper around OS specific sqlite3_os_init() function.
9659 */
9660 SQLITE_PRIVATE int sqlite3OsInit(void);
9661 
9662 /*
9663 ** Functions for accessing sqlite3_file methods
9664 */
9665 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9666 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9667 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9668 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9669 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9670 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9671 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9672 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9673 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9674 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9675 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9676 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9677 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9678 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9679 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9680 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9681 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9682 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9683 
9684 
9685 /*
9686 ** Functions for accessing sqlite3_vfs methods
9687 */
9688 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9689 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9690 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9691 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9692 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9693 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9694 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9695 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9696 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9697 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9698 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9699 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9700 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9701 
9702 /*
9703 ** Convenience functions for opening and closing files using
9704 ** sqlite3_malloc() to obtain space for the file-handle structure.
9705 */
9706 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9707 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9708 
9709 #endif /* _SQLITE_OS_H_ */
9710 
9711 /************** End of os.h **************************************************/
9712 /************** Continuing where we left off in sqliteInt.h ******************/
9713 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9714 /************** Begin file mutex.h *******************************************/
9715 /*
9716 ** 2007 August 28
9717 **
9718 ** The author disclaims copyright to this source code.  In place of
9719 ** a legal notice, here is a blessing:
9720 **
9721 **    May you do good and not evil.
9722 **    May you find forgiveness for yourself and forgive others.
9723 **    May you share freely, never taking more than you give.
9724 **
9725 *************************************************************************
9726 **
9727 ** This file contains the common header for all mutex implementations.
9728 ** The sqliteInt.h header #includes this file so that it is available
9729 ** to all source files.  We break it out in an effort to keep the code
9730 ** better organized.
9731 **
9732 ** NOTE:  source files should *not* #include this header file directly.
9733 ** Source files should #include the sqliteInt.h file and let that file
9734 ** include this one indirectly.
9735 */
9736 
9737 
9738 /*
9739 ** Figure out what version of the code to use.  The choices are
9740 **
9741 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9742 **                             mutexes implemention cannot be overridden
9743 **                             at start-time.
9744 **
9745 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9746 **                             mutual exclusion is provided.  But this
9747 **                             implementation can be overridden at
9748 **                             start-time.
9749 **
9750 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9751 **
9752 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9753 */
9754 #if !SQLITE_THREADSAFE
9755 # define SQLITE_MUTEX_OMIT
9756 #endif
9757 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9758 #  if SQLITE_OS_UNIX
9759 #    define SQLITE_MUTEX_PTHREADS
9760 #  elif SQLITE_OS_WIN
9761 #    define SQLITE_MUTEX_W32
9762 #  else
9763 #    define SQLITE_MUTEX_NOOP
9764 #  endif
9765 #endif
9766 
9767 #ifdef SQLITE_MUTEX_OMIT
9768 /*
9769 ** If this is a no-op implementation, implement everything as macros.
9770 */
9771 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9772 #define sqlite3_mutex_free(X)
9773 #define sqlite3_mutex_enter(X)
9774 #define sqlite3_mutex_try(X)      SQLITE_OK
9775 #define sqlite3_mutex_leave(X)
9776 #define sqlite3_mutex_held(X)     ((void)(X),1)
9777 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9778 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9779 #define sqlite3MutexInit()        SQLITE_OK
9780 #define sqlite3MutexEnd()
9781 #define MUTEX_LOGIC(X)
9782 #else
9783 #define MUTEX_LOGIC(X)            X
9784 #endif /* defined(SQLITE_MUTEX_OMIT) */
9785 
9786 /************** End of mutex.h ***********************************************/
9787 /************** Continuing where we left off in sqliteInt.h ******************/
9788 
9789 
9790 /*
9791 ** Each database file to be accessed by the system is an instance
9792 ** of the following structure.  There are normally two of these structures
9793 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9794 ** aDb[1] is the database file used to hold temporary tables.  Additional
9795 ** databases may be attached.
9796 */
9797 struct Db {
9798   char *zName;         /* Name of this database */
9799   Btree *pBt;          /* The B*Tree structure for this database file */
9800   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9801   u8 safety_level;     /* How aggressive at syncing data to disk */
9802   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9803 };
9804 
9805 /*
9806 ** An instance of the following structure stores a database schema.
9807 **
9808 ** Most Schema objects are associated with a Btree.  The exception is
9809 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9810 ** In shared cache mode, a single Schema object can be shared by multiple
9811 ** Btrees that refer to the same underlying BtShared object.
9812 **
9813 ** Schema objects are automatically deallocated when the last Btree that
9814 ** references them is destroyed.   The TEMP Schema is manually freed by
9815 ** sqlite3_close().
9816 *
9817 ** A thread must be holding a mutex on the corresponding Btree in order
9818 ** to access Schema content.  This implies that the thread must also be
9819 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9820 ** For a TEMP Schema, only the connection mutex is required.
9821 */
9822 struct Schema {
9823   int schema_cookie;   /* Database schema version number for this file */
9824   int iGeneration;     /* Generation counter.  Incremented with each change */
9825   Hash tblHash;        /* All tables indexed by name */
9826   Hash idxHash;        /* All (named) indices indexed by name */
9827   Hash trigHash;       /* All triggers indexed by name */
9828   Hash fkeyHash;       /* All foreign keys by referenced table name */
9829   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9830   u8 file_format;      /* Schema format version for this file */
9831   u8 enc;              /* Text encoding used by this database */
9832   u16 flags;           /* Flags associated with this schema */
9833   int cache_size;      /* Number of pages to use in the cache */
9834 };
9835 
9836 /*
9837 ** These macros can be used to test, set, or clear bits in the
9838 ** Db.pSchema->flags field.
9839 */
9840 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9841 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9842 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9843 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9844 
9845 /*
9846 ** Allowed values for the DB.pSchema->flags field.
9847 **
9848 ** The DB_SchemaLoaded flag is set after the database schema has been
9849 ** read into internal hash tables.
9850 **
9851 ** DB_UnresetViews means that one or more views have column names that
9852 ** have been filled out.  If the schema changes, these column names might
9853 ** changes and so the view will need to be reset.
9854 */
9855 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9856 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9857 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9858 
9859 /*
9860 ** The number of different kinds of things that can be limited
9861 ** using the sqlite3_limit() interface.
9862 */
9863 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9864 
9865 /*
9866 ** Lookaside malloc is a set of fixed-size buffers that can be used
9867 ** to satisfy small transient memory allocation requests for objects
9868 ** associated with a particular database connection.  The use of
9869 ** lookaside malloc provides a significant performance enhancement
9870 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9871 ** SQL statements.
9872 **
9873 ** The Lookaside structure holds configuration information about the
9874 ** lookaside malloc subsystem.  Each available memory allocation in
9875 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9876 ** objects.
9877 **
9878 ** Lookaside allocations are only allowed for objects that are associated
9879 ** with a particular database connection.  Hence, schema information cannot
9880 ** be stored in lookaside because in shared cache mode the schema information
9881 ** is shared by multiple database connections.  Therefore, while parsing
9882 ** schema information, the Lookaside.bEnabled flag is cleared so that
9883 ** lookaside allocations are not used to construct the schema objects.
9884 */
9885 struct Lookaside {
9886   u16 sz;                 /* Size of each buffer in bytes */
9887   u8 bEnabled;            /* False to disable new lookaside allocations */
9888   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9889   int nOut;               /* Number of buffers currently checked out */
9890   int mxOut;              /* Highwater mark for nOut */
9891   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9892   LookasideSlot *pFree;   /* List of available buffers */
9893   void *pStart;           /* First byte of available memory space */
9894   void *pEnd;             /* First byte past end of available space */
9895 };
9896 struct LookasideSlot {
9897   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9898 };
9899 
9900 /*
9901 ** A hash table for function definitions.
9902 **
9903 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9904 ** Collisions are on the FuncDef.pHash chain.
9905 */
9906 struct FuncDefHash {
9907   FuncDef *a[23];       /* Hash table for functions */
9908 };
9909 
9910 /*
9911 ** Each database connection is an instance of the following structure.
9912 */
9913 struct sqlite3 {
9914   sqlite3_vfs *pVfs;            /* OS Interface */
9915   struct Vdbe *pVdbe;           /* List of active virtual machines */
9916   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9917   sqlite3_mutex *mutex;         /* Connection mutex */
9918   Db *aDb;                      /* All backends */
9919   int nDb;                      /* Number of backends currently in use */
9920   int flags;                    /* Miscellaneous flags. See below */
9921   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9922   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9923   int errCode;                  /* Most recent error code (SQLITE_*) */
9924   int errMask;                  /* & result codes with this before returning */
9925   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
9926   u8 autoCommit;                /* The auto-commit flag. */
9927   u8 temp_store;                /* 1: file 2: memory 0: default */
9928   u8 mallocFailed;              /* True if we have seen a malloc failure */
9929   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9930   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9931   u8 suppressErr;               /* Do not issue error messages if true */
9932   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9933   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9934   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9935   u32 magic;                    /* Magic number for detect library misuse */
9936   int nChange;                  /* Value returned by sqlite3_changes() */
9937   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9938   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9939   struct sqlite3InitInfo {      /* Information used during initialization */
9940     int newTnum;                /* Rootpage of table being initialized */
9941     u8 iDb;                     /* Which db file is being initialized */
9942     u8 busy;                    /* TRUE if currently initializing */
9943     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9944   } init;
9945   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9946   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9947   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9948   int nExtension;               /* Number of loaded extensions */
9949   void **aExtension;            /* Array of shared library handles */
9950   void (*xTrace)(void*,const char*);        /* Trace function */
9951   void *pTraceArg;                          /* Argument to the trace function */
9952   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9953   void *pProfileArg;                        /* Argument to profile function */
9954   void *pCommitArg;                 /* Argument to xCommitCallback() */
9955   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9956   void *pRollbackArg;               /* Argument to xRollbackCallback() */
9957   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9958   void *pUpdateArg;
9959   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9960 #ifndef SQLITE_OMIT_WAL
9961   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9962   void *pWalArg;
9963 #endif
9964   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9965   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9966   void *pCollNeededArg;
9967   sqlite3_value *pErr;          /* Most recent error message */
9968   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9969   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9970   union {
9971     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9972     double notUsed1;            /* Spacer */
9973   } u1;
9974   Lookaside lookaside;          /* Lookaside malloc configuration */
9975 #ifndef SQLITE_OMIT_AUTHORIZATION
9976   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9977                                 /* Access authorization function */
9978   void *pAuthArg;               /* 1st argument to the access auth function */
9979 #endif
9980 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9981   int (*xProgress)(void *);     /* The progress callback */
9982   void *pProgressArg;           /* Argument to the progress callback */
9983   int nProgressOps;             /* Number of opcodes for progress callback */
9984 #endif
9985 #ifndef SQLITE_OMIT_VIRTUALTABLE
9986   int nVTrans;                  /* Allocated size of aVTrans */
9987   Hash aModule;                 /* populated by sqlite3_create_module() */
9988   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9989   VTable **aVTrans;             /* Virtual tables with open transactions */
9990   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9991 #endif
9992   FuncDefHash aFunc;            /* Hash table of connection functions */
9993   Hash aCollSeq;                /* All collating sequences */
9994   BusyHandler busyHandler;      /* Busy callback */
9995   Db aDbStatic[2];              /* Static space for the 2 default backends */
9996   Savepoint *pSavepoint;        /* List of active savepoints */
9997   int busyTimeout;              /* Busy handler timeout, in msec */
9998   int nSavepoint;               /* Number of non-transaction savepoints */
9999   int nStatement;               /* Number of nested statement-transactions  */
10000   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10001   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10002 
10003 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10004   /* The following variables are all protected by the STATIC_MASTER
10005   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10006   **
10007   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10008   ** unlock so that it can proceed.
10009   **
10010   ** When X.pBlockingConnection==Y, that means that something that X tried
10011   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10012   ** held by Y.
10013   */
10014   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10015   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10016   void *pUnlockArg;                     /* Argument to xUnlockNotify */
10017   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10018   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10019 #endif
10020 };
10021 
10022 /*
10023 ** A macro to discover the encoding of a database.
10024 */
10025 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10026 
10027 /*
10028 ** Possible values for the sqlite3.flags.
10029 */
10030 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10031 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10032 #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
10033 #define SQLITE_ShortColNames  0x00000008  /* Show short columns names */
10034 #define SQLITE_CountRows      0x00000010  /* Count rows changed by INSERT, */
10035                                           /*   DELETE, or UPDATE and return */
10036                                           /*   the count using a callback. */
10037 #define SQLITE_NullCallback   0x00000020  /* Invoke the callback once if the */
10038                                           /*   result set is empty */
10039 #define SQLITE_SqlTrace       0x00000040  /* Debug print SQL as it executes */
10040 #define SQLITE_VdbeListing    0x00000080  /* Debug listings of VDBE programs */
10041 #define SQLITE_WriteSchema    0x00000100  /* OK to update SQLITE_MASTER */
10042 #define SQLITE_VdbeAddopTrace 0x00000200  /* Trace sqlite3VdbeAddOp() calls */
10043 #define SQLITE_IgnoreChecks   0x00000400  /* Do not enforce check constraints */
10044 #define SQLITE_ReadUncommitted 0x0000800  /* For shared-cache mode */
10045 #define SQLITE_LegacyFileFmt  0x00001000  /* Create new databases in format 1 */
10046 #define SQLITE_FullFSync      0x00002000  /* Use full fsync on the backend */
10047 #define SQLITE_CkptFullFSync  0x00004000  /* Use full fsync for checkpoint */
10048 #define SQLITE_RecoveryMode   0x00008000  /* Ignore schema errors */
10049 #define SQLITE_ReverseOrder   0x00010000  /* Reverse unordered SELECTs */
10050 #define SQLITE_RecTriggers    0x00020000  /* Enable recursive triggers */
10051 #define SQLITE_ForeignKeys    0x00040000  /* Enforce foreign key constraints  */
10052 #define SQLITE_AutoIndex      0x00080000  /* Enable automatic indexes */
10053 #define SQLITE_PreferBuiltin  0x00100000  /* Preference to built-in funcs */
10054 #define SQLITE_LoadExtension  0x00200000  /* Enable load_extension */
10055 #define SQLITE_EnableTrigger  0x00400000  /* True to enable triggers */
10056 
10057 /*
10058 ** Bits of the sqlite3.dbOptFlags field that are used by the
10059 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10060 ** selectively disable various optimizations.
10061 */
10062 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10063 #define SQLITE_ColumnCache    0x0002   /* Column cache */
10064 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10065 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10066 #define SQLITE_IdxRealAsInt   0x0010   /* Store REAL as INT in indices */
10067 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10068 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10069 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10070 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10071 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
10072 #define SQLITE_AllOpts        0xffff   /* All optimizations */
10073 
10074 /*
10075 ** Macros for testing whether or not optimizations are enabled or disabled.
10076 */
10077 #ifndef SQLITE_OMIT_BUILTIN_TEST
10078 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10079 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10080 #else
10081 #define OptimizationDisabled(db, mask)  0
10082 #define OptimizationEnabled(db, mask)   1
10083 #endif
10084 
10085 /*
10086 ** Possible values for the sqlite.magic field.
10087 ** The numbers are obtained at random and have no special meaning, other
10088 ** than being distinct from one another.
10089 */
10090 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10091 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10092 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10093 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10094 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10095 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10096 
10097 /*
10098 ** Each SQL function is defined by an instance of the following
10099 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
10100 ** hash table.  When multiple functions have the same name, the hash table
10101 ** points to a linked list of these structures.
10102 */
10103 struct FuncDef {
10104   i16 nArg;            /* Number of arguments.  -1 means unlimited */
10105   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
10106   u8 flags;            /* Some combination of SQLITE_FUNC_* */
10107   void *pUserData;     /* User data parameter */
10108   FuncDef *pNext;      /* Next function with same name */
10109   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10110   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10111   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10112   char *zName;         /* SQL name of the function. */
10113   FuncDef *pHash;      /* Next with a different name but the same hash */
10114   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10115 };
10116 
10117 /*
10118 ** This structure encapsulates a user-function destructor callback (as
10119 ** configured using create_function_v2()) and a reference counter. When
10120 ** create_function_v2() is called to create a function with a destructor,
10121 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10122 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10123 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10124 ** member of each of the new FuncDef objects is set to point to the allocated
10125 ** FuncDestructor.
10126 **
10127 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10128 ** count on this object is decremented. When it reaches 0, the destructor
10129 ** is invoked and the FuncDestructor structure freed.
10130 */
10131 struct FuncDestructor {
10132   int nRef;
10133   void (*xDestroy)(void *);
10134   void *pUserData;
10135 };
10136 
10137 /*
10138 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10139 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10140 ** are assert() statements in the code to verify this.
10141 */
10142 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10143 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10144 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10145 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10146 #define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10147 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10148 #define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10149 #define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10150 
10151 /*
10152 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10153 ** used to create the initializers for the FuncDef structures.
10154 **
10155 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10156 **     Used to create a scalar function definition of a function zName
10157 **     implemented by C function xFunc that accepts nArg arguments. The
10158 **     value passed as iArg is cast to a (void*) and made available
10159 **     as the user-data (sqlite3_user_data()) for the function. If
10160 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10161 **
10162 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10163 **     Used to create an aggregate function definition implemented by
10164 **     the C functions xStep and xFinal. The first four parameters
10165 **     are interpreted in the same way as the first 4 parameters to
10166 **     FUNCTION().
10167 **
10168 **   LIKEFUNC(zName, nArg, pArg, flags)
10169 **     Used to create a scalar function definition of a function zName
10170 **     that accepts nArg arguments and is implemented by a call to C
10171 **     function likeFunc. Argument pArg is cast to a (void *) and made
10172 **     available as the function user-data (sqlite3_user_data()). The
10173 **     FuncDef.flags variable is set to the value passed as the flags
10174 **     parameter.
10175 */
10176 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10177   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10178    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10179 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10180   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10181    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10182 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10183   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10184    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10185 #define LIKEFUNC(zName, nArg, arg, flags) \
10186   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10187 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10188   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10189    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10190 
10191 /*
10192 ** All current savepoints are stored in a linked list starting at
10193 ** sqlite3.pSavepoint. The first element in the list is the most recently
10194 ** opened savepoint. Savepoints are added to the list by the vdbe
10195 ** OP_Savepoint instruction.
10196 */
10197 struct Savepoint {
10198   char *zName;                        /* Savepoint name (nul-terminated) */
10199   i64 nDeferredCons;                  /* Number of deferred fk violations */
10200   Savepoint *pNext;                   /* Parent savepoint (if any) */
10201 };
10202 
10203 /*
10204 ** The following are used as the second parameter to sqlite3Savepoint(),
10205 ** and as the P1 argument to the OP_Savepoint instruction.
10206 */
10207 #define SAVEPOINT_BEGIN      0
10208 #define SAVEPOINT_RELEASE    1
10209 #define SAVEPOINT_ROLLBACK   2
10210 
10211 
10212 /*
10213 ** Each SQLite module (virtual table definition) is defined by an
10214 ** instance of the following structure, stored in the sqlite3.aModule
10215 ** hash table.
10216 */
10217 struct Module {
10218   const sqlite3_module *pModule;       /* Callback pointers */
10219   const char *zName;                   /* Name passed to create_module() */
10220   void *pAux;                          /* pAux passed to create_module() */
10221   void (*xDestroy)(void *);            /* Module destructor function */
10222 };
10223 
10224 /*
10225 ** information about each column of an SQL table is held in an instance
10226 ** of this structure.
10227 */
10228 struct Column {
10229   char *zName;     /* Name of this column */
10230   Expr *pDflt;     /* Default value of this column */
10231   char *zDflt;     /* Original text of the default value */
10232   char *zType;     /* Data type for this column */
10233   char *zColl;     /* Collating sequence.  If NULL, use the default */
10234   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10235   char affinity;   /* One of the SQLITE_AFF_... values */
10236   u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
10237 };
10238 
10239 /* Allowed values for Column.colFlags:
10240 */
10241 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10242 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10243 
10244 /*
10245 ** A "Collating Sequence" is defined by an instance of the following
10246 ** structure. Conceptually, a collating sequence consists of a name and
10247 ** a comparison routine that defines the order of that sequence.
10248 **
10249 ** If CollSeq.xCmp is NULL, it means that the
10250 ** collating sequence is undefined.  Indices built on an undefined
10251 ** collating sequence may not be read or written.
10252 */
10253 struct CollSeq {
10254   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10255   u8 enc;               /* Text encoding handled by xCmp() */
10256   void *pUser;          /* First argument to xCmp() */
10257   int (*xCmp)(void*,int, const void*, int, const void*);
10258   void (*xDel)(void*);  /* Destructor for pUser */
10259 };
10260 
10261 /*
10262 ** A sort order can be either ASC or DESC.
10263 */
10264 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10265 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10266 
10267 /*
10268 ** Column affinity types.
10269 **
10270 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10271 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10272 ** the speed a little by numbering the values consecutively.
10273 **
10274 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10275 ** when multiple affinity types are concatenated into a string and
10276 ** used as the P4 operand, they will be more readable.
10277 **
10278 ** Note also that the numeric types are grouped together so that testing
10279 ** for a numeric type is a single comparison.
10280 */
10281 #define SQLITE_AFF_TEXT     'a'
10282 #define SQLITE_AFF_NONE     'b'
10283 #define SQLITE_AFF_NUMERIC  'c'
10284 #define SQLITE_AFF_INTEGER  'd'
10285 #define SQLITE_AFF_REAL     'e'
10286 
10287 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10288 
10289 /*
10290 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10291 ** affinity value.
10292 */
10293 #define SQLITE_AFF_MASK     0x67
10294 
10295 /*
10296 ** Additional bit values that can be ORed with an affinity without
10297 ** changing the affinity.
10298 */
10299 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10300 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10301 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10302 
10303 /*
10304 ** An object of this type is created for each virtual table present in
10305 ** the database schema.
10306 **
10307 ** If the database schema is shared, then there is one instance of this
10308 ** structure for each database connection (sqlite3*) that uses the shared
10309 ** schema. This is because each database connection requires its own unique
10310 ** instance of the sqlite3_vtab* handle used to access the virtual table
10311 ** implementation. sqlite3_vtab* handles can not be shared between
10312 ** database connections, even when the rest of the in-memory database
10313 ** schema is shared, as the implementation often stores the database
10314 ** connection handle passed to it via the xConnect() or xCreate() method
10315 ** during initialization internally. This database connection handle may
10316 ** then be used by the virtual table implementation to access real tables
10317 ** within the database. So that they appear as part of the callers
10318 ** transaction, these accesses need to be made via the same database
10319 ** connection as that used to execute SQL operations on the virtual table.
10320 **
10321 ** All VTable objects that correspond to a single table in a shared
10322 ** database schema are initially stored in a linked-list pointed to by
10323 ** the Table.pVTable member variable of the corresponding Table object.
10324 ** When an sqlite3_prepare() operation is required to access the virtual
10325 ** table, it searches the list for the VTable that corresponds to the
10326 ** database connection doing the preparing so as to use the correct
10327 ** sqlite3_vtab* handle in the compiled query.
10328 **
10329 ** When an in-memory Table object is deleted (for example when the
10330 ** schema is being reloaded for some reason), the VTable objects are not
10331 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10332 ** immediately. Instead, they are moved from the Table.pVTable list to
10333 ** another linked list headed by the sqlite3.pDisconnect member of the
10334 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
10335 ** next time a statement is prepared using said sqlite3*. This is done
10336 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10337 ** Refer to comments above function sqlite3VtabUnlockList() for an
10338 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10339 ** list without holding the corresponding sqlite3.mutex mutex.
10340 **
10341 ** The memory for objects of this type is always allocated by
10342 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10343 ** the first argument.
10344 */
10345 struct VTable {
10346   sqlite3 *db;              /* Database connection associated with this table */
10347   Module *pMod;             /* Pointer to module implementation */
10348   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10349   int nRef;                 /* Number of pointers to this structure */
10350   u8 bConstraint;           /* True if constraints are supported */
10351   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10352   VTable *pNext;            /* Next in linked list (see above) */
10353 };
10354 
10355 /*
10356 ** Each SQL table is represented in memory by an instance of the
10357 ** following structure.
10358 **
10359 ** Table.zName is the name of the table.  The case of the original
10360 ** CREATE TABLE statement is stored, but case is not significant for
10361 ** comparisons.
10362 **
10363 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10364 ** pointer to an array of Column structures, one for each column.
10365 **
10366 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10367 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10368 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10369 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10370 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10371 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10372 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10373 **
10374 ** Table.tnum is the page number for the root BTree page of the table in the
10375 ** database file.  If Table.iDb is the index of the database table backend
10376 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10377 ** holds temporary tables and indices.  If TF_Ephemeral is set
10378 ** then the table is stored in a file that is automatically deleted
10379 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
10380 ** refers VDBE cursor number that holds the table open, not to the root
10381 ** page number.  Transient tables are used to hold the results of a
10382 ** sub-query that appears instead of a real table name in the FROM clause
10383 ** of a SELECT statement.
10384 */
10385 struct Table {
10386   char *zName;         /* Name of the table or view */
10387   Column *aCol;        /* Information about each column */
10388   Index *pIndex;       /* List of SQL indexes on this table. */
10389   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10390   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10391   char *zColAff;       /* String defining the affinity of each column */
10392 #ifndef SQLITE_OMIT_CHECK
10393   ExprList *pCheck;    /* All CHECK constraints */
10394 #endif
10395   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10396   int tnum;            /* Root BTree node for this table (see note above) */
10397   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10398   i16 nCol;            /* Number of columns in this table */
10399   u16 nRef;            /* Number of pointers to this Table */
10400   u8 tabFlags;         /* Mask of TF_* values */
10401   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10402 #ifndef SQLITE_OMIT_ALTERTABLE
10403   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10404 #endif
10405 #ifndef SQLITE_OMIT_VIRTUALTABLE
10406   int nModuleArg;      /* Number of arguments to the module */
10407   char **azModuleArg;  /* Text of all module args. [0] is module name */
10408   VTable *pVTable;     /* List of VTable objects. */
10409 #endif
10410   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10411   Schema *pSchema;     /* Schema that contains this table */
10412   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10413 };
10414 
10415 /*
10416 ** Allowed values for Tabe.tabFlags.
10417 */
10418 #define TF_Readonly        0x01    /* Read-only system table */
10419 #define TF_Ephemeral       0x02    /* An ephemeral table */
10420 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10421 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10422 #define TF_Virtual         0x10    /* Is a virtual table */
10423 
10424 
10425 /*
10426 ** Test to see whether or not a table is a virtual table.  This is
10427 ** done as a macro so that it will be optimized out when virtual
10428 ** table support is omitted from the build.
10429 */
10430 #ifndef SQLITE_OMIT_VIRTUALTABLE
10431 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10432 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10433 #else
10434 #  define IsVirtual(X)      0
10435 #  define IsHiddenColumn(X) 0
10436 #endif
10437 
10438 /*
10439 ** Each foreign key constraint is an instance of the following structure.
10440 **
10441 ** A foreign key is associated with two tables.  The "from" table is
10442 ** the table that contains the REFERENCES clause that creates the foreign
10443 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10444 ** Consider this example:
10445 **
10446 **     CREATE TABLE ex1(
10447 **       a INTEGER PRIMARY KEY,
10448 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10449 **     );
10450 **
10451 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10452 **
10453 ** Each REFERENCES clause generates an instance of the following structure
10454 ** which is attached to the from-table.  The to-table need not exist when
10455 ** the from-table is created.  The existence of the to-table is not checked.
10456 */
10457 struct FKey {
10458   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10459   FKey *pNextFrom;  /* Next foreign key in pFrom */
10460   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10461   FKey *pNextTo;    /* Next foreign key on table named zTo */
10462   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10463   int nCol;         /* Number of columns in this key */
10464   /* EV: R-30323-21917 */
10465   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10466   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10467   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10468   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10469     int iFrom;         /* Index of column in pFrom */
10470     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10471   } aCol[1];        /* One entry for each of nCol column s */
10472 };
10473 
10474 /*
10475 ** SQLite supports many different ways to resolve a constraint
10476 ** error.  ROLLBACK processing means that a constraint violation
10477 ** causes the operation in process to fail and for the current transaction
10478 ** to be rolled back.  ABORT processing means the operation in process
10479 ** fails and any prior changes from that one operation are backed out,
10480 ** but the transaction is not rolled back.  FAIL processing means that
10481 ** the operation in progress stops and returns an error code.  But prior
10482 ** changes due to the same operation are not backed out and no rollback
10483 ** occurs.  IGNORE means that the particular row that caused the constraint
10484 ** error is not inserted or updated.  Processing continues and no error
10485 ** is returned.  REPLACE means that preexisting database rows that caused
10486 ** a UNIQUE constraint violation are removed so that the new insert or
10487 ** update can proceed.  Processing continues and no error is reported.
10488 **
10489 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10490 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10491 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10492 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10493 ** referenced table row is propagated into the row that holds the
10494 ** foreign key.
10495 **
10496 ** The following symbolic values are used to record which type
10497 ** of action to take.
10498 */
10499 #define OE_None     0   /* There is no constraint to check */
10500 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10501 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10502 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10503 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10504 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10505 
10506 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10507 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10508 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10509 #define OE_Cascade  9   /* Cascade the changes */
10510 
10511 #define OE_Default  99  /* Do whatever the default action is */
10512 
10513 
10514 /*
10515 ** An instance of the following structure is passed as the first
10516 ** argument to sqlite3VdbeKeyCompare and is used to control the
10517 ** comparison of the two index keys.
10518 */
10519 struct KeyInfo {
10520   sqlite3 *db;        /* The database connection */
10521   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10522   u16 nField;         /* Number of entries in aColl[] */
10523   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10524   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10525 };
10526 
10527 /*
10528 ** An instance of the following structure holds information about a
10529 ** single index record that has already been parsed out into individual
10530 ** values.
10531 **
10532 ** A record is an object that contains one or more fields of data.
10533 ** Records are used to store the content of a table row and to store
10534 ** the key of an index.  A blob encoding of a record is created by
10535 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10536 ** OP_Column opcode.
10537 **
10538 ** This structure holds a record that has already been disassembled
10539 ** into its constituent fields.
10540 */
10541 struct UnpackedRecord {
10542   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10543   u16 nField;         /* Number of entries in apMem[] */
10544   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10545   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10546   Mem *aMem;          /* Values */
10547 };
10548 
10549 /*
10550 ** Allowed values of UnpackedRecord.flags
10551 */
10552 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10553 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10554 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10555 
10556 /*
10557 ** Each SQL index is represented in memory by an
10558 ** instance of the following structure.
10559 **
10560 ** The columns of the table that are to be indexed are described
10561 ** by the aiColumn[] field of this structure.  For example, suppose
10562 ** we have the following table and index:
10563 **
10564 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10565 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10566 **
10567 ** In the Table structure describing Ex1, nCol==3 because there are
10568 ** three columns in the table.  In the Index structure describing
10569 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10570 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
10571 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10572 ** The second column to be indexed (c1) has an index of 0 in
10573 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10574 **
10575 ** The Index.onError field determines whether or not the indexed columns
10576 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10577 ** it means this is not a unique index.  Otherwise it is a unique index
10578 ** and the value of Index.onError indicate the which conflict resolution
10579 ** algorithm to employ whenever an attempt is made to insert a non-unique
10580 ** element.
10581 */
10582 struct Index {
10583   char *zName;             /* Name of this index */
10584   int *aiColumn;           /* Which columns are used by this index.  1st is 0 */
10585   tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
10586   Table *pTable;           /* The SQL table being indexed */
10587   char *zColAff;           /* String defining the affinity of each column */
10588   Index *pNext;            /* The next index associated with the same table */
10589   Schema *pSchema;         /* Schema containing this index */
10590   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
10591   char **azColl;           /* Array of collation sequence names for index */
10592   int tnum;                /* DB Page containing root of this index */
10593   u16 nColumn;             /* Number of columns in table used by this index */
10594   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10595   unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10596   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
10597 #ifdef SQLITE_ENABLE_STAT3
10598   int nSample;             /* Number of elements in aSample[] */
10599   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10600   IndexSample *aSample;    /* Samples of the left-most key */
10601 #endif
10602 };
10603 
10604 /*
10605 ** Each sample stored in the sqlite_stat3 table is represented in memory
10606 ** using a structure of this type.  See documentation at the top of the
10607 ** analyze.c source file for additional information.
10608 */
10609 struct IndexSample {
10610   union {
10611     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10612     double r;       /* Value if eType is SQLITE_FLOAT */
10613     i64 i;          /* Value if eType is SQLITE_INTEGER */
10614   } u;
10615   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10616   int nByte;        /* Size in byte of text or blob. */
10617   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10618   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10619   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10620 };
10621 
10622 /*
10623 ** Each token coming out of the lexer is an instance of
10624 ** this structure.  Tokens are also used as part of an expression.
10625 **
10626 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10627 ** may contain random values.  Do not make any assumptions about Token.dyn
10628 ** and Token.n when Token.z==0.
10629 */
10630 struct Token {
10631   const char *z;     /* Text of the token.  Not NULL-terminated! */
10632   unsigned int n;    /* Number of characters in this token */
10633 };
10634 
10635 /*
10636 ** An instance of this structure contains information needed to generate
10637 ** code for a SELECT that contains aggregate functions.
10638 **
10639 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10640 ** pointer to this structure.  The Expr.iColumn field is the index in
10641 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10642 ** code for that node.
10643 **
10644 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10645 ** original Select structure that describes the SELECT statement.  These
10646 ** fields do not need to be freed when deallocating the AggInfo structure.
10647 */
10648 struct AggInfo {
10649   u8 directMode;          /* Direct rendering mode means take data directly
10650                           ** from source tables rather than from accumulators */
10651   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10652                           ** than the source table */
10653   int sortingIdx;         /* Cursor number of the sorting index */
10654   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10655   int nSortingColumn;     /* Number of columns in the sorting index */
10656   ExprList *pGroupBy;     /* The group by clause */
10657   struct AggInfo_col {    /* For each column used in source tables */
10658     Table *pTab;             /* Source table */
10659     int iTable;              /* Cursor number of the source table */
10660     int iColumn;             /* Column number within the source table */
10661     int iSorterColumn;       /* Column number in the sorting index */
10662     int iMem;                /* Memory location that acts as accumulator */
10663     Expr *pExpr;             /* The original expression */
10664   } *aCol;
10665   int nColumn;            /* Number of used entries in aCol[] */
10666   int nAccumulator;       /* Number of columns that show through to the output.
10667                           ** Additional columns are used only as parameters to
10668                           ** aggregate functions */
10669   struct AggInfo_func {   /* For each aggregate function */
10670     Expr *pExpr;             /* Expression encoding the function */
10671     FuncDef *pFunc;          /* The aggregate function implementation */
10672     int iMem;                /* Memory location that acts as accumulator */
10673     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10674   } *aFunc;
10675   int nFunc;              /* Number of entries in aFunc[] */
10676 };
10677 
10678 /*
10679 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10680 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10681 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10682 ** it uses less memory in the Expr object, which is a big memory user
10683 ** in systems with lots of prepared statements.  And few applications
10684 ** need more than about 10 or 20 variables.  But some extreme users want
10685 ** to have prepared statements with over 32767 variables, and for them
10686 ** the option is available (at compile-time).
10687 */
10688 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10689 typedef i16 ynVar;
10690 #else
10691 typedef int ynVar;
10692 #endif
10693 
10694 /*
10695 ** Each node of an expression in the parse tree is an instance
10696 ** of this structure.
10697 **
10698 ** Expr.op is the opcode. The integer parser token codes are reused
10699 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10700 ** code representing the ">=" operator. This same integer code is reused
10701 ** to represent the greater-than-or-equal-to operator in the expression
10702 ** tree.
10703 **
10704 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10705 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10706 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10707 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10708 ** then Expr.token contains the name of the function.
10709 **
10710 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10711 ** binary operator. Either or both may be NULL.
10712 **
10713 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10714 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10715 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10716 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10717 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10718 ** valid.
10719 **
10720 ** An expression of the form ID or ID.ID refers to a column in a table.
10721 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10722 ** the integer cursor number of a VDBE cursor pointing to that table and
10723 ** Expr.iColumn is the column number for the specific column.  If the
10724 ** expression is used as a result in an aggregate SELECT, then the
10725 ** value is also stored in the Expr.iAgg column in the aggregate so that
10726 ** it can be accessed after all aggregates are computed.
10727 **
10728 ** If the expression is an unbound variable marker (a question mark
10729 ** character '?' in the original SQL) then the Expr.iTable holds the index
10730 ** number for that variable.
10731 **
10732 ** If the expression is a subquery then Expr.iColumn holds an integer
10733 ** register number containing the result of the subquery.  If the
10734 ** subquery gives a constant result, then iTable is -1.  If the subquery
10735 ** gives a different answer at different times during statement processing
10736 ** then iTable is the address of a subroutine that computes the subquery.
10737 **
10738 ** If the Expr is of type OP_Column, and the table it is selecting from
10739 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10740 ** corresponding table definition.
10741 **
10742 ** ALLOCATION NOTES:
10743 **
10744 ** Expr objects can use a lot of memory space in database schema.  To
10745 ** help reduce memory requirements, sometimes an Expr object will be
10746 ** truncated.  And to reduce the number of memory allocations, sometimes
10747 ** two or more Expr objects will be stored in a single memory allocation,
10748 ** together with Expr.zToken strings.
10749 **
10750 ** If the EP_Reduced and EP_TokenOnly flags are set when
10751 ** an Expr object is truncated.  When EP_Reduced is set, then all
10752 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10753 ** are contained within the same memory allocation.  Note, however, that
10754 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10755 ** allocated, regardless of whether or not EP_Reduced is set.
10756 */
10757 struct Expr {
10758   u8 op;                 /* Operation performed by this node */
10759   char affinity;         /* The affinity of the column or 0 if not a column */
10760   u16 flags;             /* Various flags.  EP_* See below */
10761   union {
10762     char *zToken;          /* Token value. Zero terminated and dequoted */
10763     int iValue;            /* Non-negative integer value if EP_IntValue */
10764   } u;
10765 
10766   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10767   ** space is allocated for the fields below this point. An attempt to
10768   ** access them will result in a segfault or malfunction.
10769   *********************************************************************/
10770 
10771   Expr *pLeft;           /* Left subnode */
10772   Expr *pRight;          /* Right subnode */
10773   union {
10774     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10775     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10776   } x;
10777 
10778   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10779   ** space is allocated for the fields below this point. An attempt to
10780   ** access them will result in a segfault or malfunction.
10781   *********************************************************************/
10782 
10783 #if SQLITE_MAX_EXPR_DEPTH>0
10784   int nHeight;           /* Height of the tree headed by this node */
10785 #endif
10786   int iTable;            /* TK_COLUMN: cursor number of table holding column
10787                          ** TK_REGISTER: register number
10788                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10789   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10790                          ** TK_VARIABLE: variable number (always >= 1). */
10791   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10792   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10793   u8 flags2;             /* Second set of flags.  EP2_... */
10794   u8 op2;                /* TK_REGISTER: original value of Expr.op
10795                          ** TK_COLUMN: the value of p5 for OP_Column
10796                          ** TK_AGG_FUNCTION: nesting depth */
10797   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10798   Table *pTab;           /* Table for TK_COLUMN expressions. */
10799 };
10800 
10801 /*
10802 ** The following are the meanings of bits in the Expr.flags field.
10803 */
10804 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10805 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10806 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10807 #define EP_Error      0x0008  /* Expression contains one or more errors */
10808 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10809 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10810 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10811 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10812 #define EP_Collate    0x0100  /* Tree contains a TK_COLLATE opeartor */
10813 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10814 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10815 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10816 #define EP_Hint       0x1000  /* Not used */
10817 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10818 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10819 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10820 
10821 /*
10822 ** The following are the meanings of bits in the Expr.flags2 field.
10823 */
10824 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10825 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10826 
10827 /*
10828 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10829 ** flag on an expression structure.  This flag is used for VV&A only.  The
10830 ** routine is implemented as a macro that only works when in debugging mode,
10831 ** so as not to burden production code.
10832 */
10833 #ifdef SQLITE_DEBUG
10834 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10835 #else
10836 # define ExprSetIrreducible(X)
10837 #endif
10838 
10839 /*
10840 ** These macros can be used to test, set, or clear bits in the
10841 ** Expr.flags field.
10842 */
10843 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10844 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10845 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10846 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10847 
10848 /*
10849 ** Macros to determine the number of bytes required by a normal Expr
10850 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10851 ** and an Expr struct with the EP_TokenOnly flag set.
10852 */
10853 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10854 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10855 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10856 
10857 /*
10858 ** Flags passed to the sqlite3ExprDup() function. See the header comment
10859 ** above sqlite3ExprDup() for details.
10860 */
10861 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10862 
10863 /*
10864 ** A list of expressions.  Each expression may optionally have a
10865 ** name.  An expr/name combination can be used in several ways, such
10866 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10867 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10868 ** also be used as the argument to a function, in which case the a.zName
10869 ** field is not used.
10870 **
10871 ** By default the Expr.zSpan field holds a human-readable description of
10872 ** the expression that is used in the generation of error messages and
10873 ** column labels.  In this case, Expr.zSpan is typically the text of a
10874 ** column expression as it exists in a SELECT statement.  However, if
10875 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
10876 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
10877 ** form is used for name resolution with nested FROM clauses.
10878 */
10879 struct ExprList {
10880   int nExpr;             /* Number of expressions on the list */
10881   int iECursor;          /* VDBE Cursor associated with this ExprList */
10882   struct ExprList_item { /* For each expression in the list */
10883     Expr *pExpr;            /* The list of expressions */
10884     char *zName;            /* Token associated with this expression */
10885     char *zSpan;            /* Original text of the expression */
10886     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
10887     unsigned done :1;       /* A flag to indicate when processing is finished */
10888     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
10889     u16 iOrderByCol;        /* For ORDER BY, column number in result set */
10890     u16 iAlias;             /* Index into Parse.aAlias[] for zName */
10891   } *a;                  /* Alloc a power of two greater or equal to nExpr */
10892 };
10893 
10894 /*
10895 ** An instance of this structure is used by the parser to record both
10896 ** the parse tree for an expression and the span of input text for an
10897 ** expression.
10898 */
10899 struct ExprSpan {
10900   Expr *pExpr;          /* The expression parse tree */
10901   const char *zStart;   /* First character of input text */
10902   const char *zEnd;     /* One character past the end of input text */
10903 };
10904 
10905 /*
10906 ** An instance of this structure can hold a simple list of identifiers,
10907 ** such as the list "a,b,c" in the following statements:
10908 **
10909 **      INSERT INTO t(a,b,c) VALUES ...;
10910 **      CREATE INDEX idx ON t(a,b,c);
10911 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10912 **
10913 ** The IdList.a.idx field is used when the IdList represents the list of
10914 ** column names after a table name in an INSERT statement.  In the statement
10915 **
10916 **     INSERT INTO t(a,b,c) ...
10917 **
10918 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10919 */
10920 struct IdList {
10921   struct IdList_item {
10922     char *zName;      /* Name of the identifier */
10923     int idx;          /* Index in some Table.aCol[] of a column named zName */
10924   } *a;
10925   int nId;         /* Number of identifiers on the list */
10926 };
10927 
10928 /*
10929 ** The bitmask datatype defined below is used for various optimizations.
10930 **
10931 ** Changing this from a 64-bit to a 32-bit type limits the number of
10932 ** tables in a join to 32 instead of 64.  But it also reduces the size
10933 ** of the library by 738 bytes on ix86.
10934 */
10935 typedef u64 Bitmask;
10936 
10937 /*
10938 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10939 */
10940 #define BMS  ((int)(sizeof(Bitmask)*8))
10941 
10942 /*
10943 ** The following structure describes the FROM clause of a SELECT statement.
10944 ** Each table or subquery in the FROM clause is a separate element of
10945 ** the SrcList.a[] array.
10946 **
10947 ** With the addition of multiple database support, the following structure
10948 ** can also be used to describe a particular table such as the table that
10949 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10950 ** such a table must be a simple name: ID.  But in SQLite, the table can
10951 ** now be identified by a database name, a dot, then the table name: ID.ID.
10952 **
10953 ** The jointype starts out showing the join type between the current table
10954 ** and the next table on the list.  The parser builds the list this way.
10955 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10956 ** jointype expresses the join between the table and the previous table.
10957 **
10958 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10959 ** contains more than 63 columns and the 64-th or later column is used.
10960 */
10961 struct SrcList {
10962   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10963   i16 nAlloc;      /* Number of entries allocated in a[] below */
10964   struct SrcList_item {
10965     Schema *pSchema;  /* Schema to which this item is fixed */
10966     char *zDatabase;  /* Name of database holding this table */
10967     char *zName;      /* Name of the table */
10968     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10969     Table *pTab;      /* An SQL table corresponding to zName */
10970     Select *pSelect;  /* A SELECT statement used in place of a table name */
10971     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10972     int regReturn;    /* Register holding return address of addrFillSub */
10973     u8 jointype;      /* Type of join between this able and the previous */
10974     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
10975     unsigned isCorrelated :1;  /* True if sub-query is correlated */
10976     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
10977 #ifndef SQLITE_OMIT_EXPLAIN
10978     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10979 #endif
10980     int iCursor;      /* The VDBE cursor number used to access this table */
10981     Expr *pOn;        /* The ON clause of a join */
10982     IdList *pUsing;   /* The USING clause of a join */
10983     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10984     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10985     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10986   } a[1];             /* One entry for each identifier on the list */
10987 };
10988 
10989 /*
10990 ** Permitted values of the SrcList.a.jointype field
10991 */
10992 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10993 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10994 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10995 #define JT_LEFT      0x0008    /* Left outer join */
10996 #define JT_RIGHT     0x0010    /* Right outer join */
10997 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10998 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10999 
11000 
11001 /*
11002 ** A WherePlan object holds information that describes a lookup
11003 ** strategy.
11004 **
11005 ** This object is intended to be opaque outside of the where.c module.
11006 ** It is included here only so that that compiler will know how big it
11007 ** is.  None of the fields in this object should be used outside of
11008 ** the where.c module.
11009 **
11010 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
11011 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
11012 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
11013 ** case that more than one of these conditions is true.
11014 */
11015 struct WherePlan {
11016   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
11017   u16 nEq;                       /* Number of == constraints */
11018   u16 nOBSat;                    /* Number of ORDER BY terms satisfied */
11019   double nRow;                   /* Estimated number of rows (for EQP) */
11020   union {
11021     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
11022     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
11023     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
11024   } u;
11025 };
11026 
11027 /*
11028 ** For each nested loop in a WHERE clause implementation, the WhereInfo
11029 ** structure contains a single instance of this structure.  This structure
11030 ** is intended to be private to the where.c module and should not be
11031 ** access or modified by other modules.
11032 **
11033 ** The pIdxInfo field is used to help pick the best index on a
11034 ** virtual table.  The pIdxInfo pointer contains indexing
11035 ** information for the i-th table in the FROM clause before reordering.
11036 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11037 ** All other information in the i-th WhereLevel object for the i-th table
11038 ** after FROM clause ordering.
11039 */
11040 struct WhereLevel {
11041   WherePlan plan;       /* query plan for this element of the FROM clause */
11042   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
11043   int iTabCur;          /* The VDBE cursor used to access the table */
11044   int iIdxCur;          /* The VDBE cursor used to access pIdx */
11045   int addrBrk;          /* Jump here to break out of the loop */
11046   int addrNxt;          /* Jump here to start the next IN combination */
11047   int addrCont;         /* Jump here to continue with the next loop cycle */
11048   int addrFirst;        /* First instruction of interior of the loop */
11049   u8 iFrom;             /* Which entry in the FROM clause */
11050   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
11051   int p1, p2;           /* Operands of the opcode used to ends the loop */
11052   union {               /* Information that depends on plan.wsFlags */
11053     struct {
11054       int nIn;              /* Number of entries in aInLoop[] */
11055       struct InLoop {
11056         int iCur;              /* The VDBE cursor used by this IN operator */
11057         int addrInTop;         /* Top of the IN loop */
11058         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
11059       } *aInLoop;           /* Information about each nested IN operator */
11060     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
11061     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
11062   } u;
11063   double rOptCost;      /* "Optimal" cost for this level */
11064 
11065   /* The following field is really not part of the current level.  But
11066   ** we need a place to cache virtual table index information for each
11067   ** virtual table in the FROM clause and the WhereLevel structure is
11068   ** a convenient place since there is one WhereLevel for each FROM clause
11069   ** element.
11070   */
11071   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
11072 };
11073 
11074 /*
11075 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11076 ** and the WhereInfo.wctrlFlags member.
11077 */
11078 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11079 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11080 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11081 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11082 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11083 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11084 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11085 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11086 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11087 
11088 /*
11089 ** The WHERE clause processing routine has two halves.  The
11090 ** first part does the start of the WHERE loop and the second
11091 ** half does the tail of the WHERE loop.  An instance of
11092 ** this structure is returned by the first half and passed
11093 ** into the second half to give some continuity.
11094 */
11095 struct WhereInfo {
11096   Parse *pParse;            /* Parsing and code generating context */
11097   SrcList *pTabList;        /* List of tables in the join */
11098   u16 nOBSat;               /* Number of ORDER BY terms satisfied by indices */
11099   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
11100   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
11101   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
11102   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
11103   int iTop;                 /* The very beginning of the WHERE loop */
11104   int iContinue;            /* Jump here to continue with next record */
11105   int iBreak;               /* Jump here to break out of the loop */
11106   int nLevel;               /* Number of nested loop */
11107   struct WhereClause *pWC;  /* Decomposition of the WHERE clause */
11108   double savedNQueryLoop;   /* pParse->nQueryLoop outside the WHERE loop */
11109   double nRowOut;           /* Estimated number of output rows */
11110   WhereLevel a[1];          /* Information about each nest loop in WHERE */
11111 };
11112 
11113 /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11114 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11115 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11116 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11117 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11118 
11119 /*
11120 ** A NameContext defines a context in which to resolve table and column
11121 ** names.  The context consists of a list of tables (the pSrcList) field and
11122 ** a list of named expression (pEList).  The named expression list may
11123 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11124 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11125 ** pEList corresponds to the result set of a SELECT and is NULL for
11126 ** other statements.
11127 **
11128 ** NameContexts can be nested.  When resolving names, the inner-most
11129 ** context is searched first.  If no match is found, the next outer
11130 ** context is checked.  If there is still no match, the next context
11131 ** is checked.  This process continues until either a match is found
11132 ** or all contexts are check.  When a match is found, the nRef member of
11133 ** the context containing the match is incremented.
11134 **
11135 ** Each subquery gets a new NameContext.  The pNext field points to the
11136 ** NameContext in the parent query.  Thus the process of scanning the
11137 ** NameContext list corresponds to searching through successively outer
11138 ** subqueries looking for a match.
11139 */
11140 struct NameContext {
11141   Parse *pParse;       /* The parser */
11142   SrcList *pSrcList;   /* One or more tables used to resolve names */
11143   ExprList *pEList;    /* Optional list of named expressions */
11144   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11145   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11146   int nRef;            /* Number of names resolved by this context */
11147   int nErr;            /* Number of errors encountered while resolving names */
11148   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11149 };
11150 
11151 /*
11152 ** Allowed values for the NameContext, ncFlags field.
11153 */
11154 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11155 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11156 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11157 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11158 
11159 /*
11160 ** An instance of the following structure contains all information
11161 ** needed to generate code for a single SELECT statement.
11162 **
11163 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11164 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11165 ** limit and nOffset to the value of the offset (or 0 if there is not
11166 ** offset).  But later on, nLimit and nOffset become the memory locations
11167 ** in the VDBE that record the limit and offset counters.
11168 **
11169 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11170 ** These addresses must be stored so that we can go back and fill in
11171 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11172 ** the number of columns in P2 can be computed at the same time
11173 ** as the OP_OpenEphm instruction is coded because not
11174 ** enough information about the compound query is known at that point.
11175 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11176 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11177 ** sequences for the ORDER BY clause.
11178 */
11179 struct Select {
11180   ExprList *pEList;      /* The fields of the result */
11181   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11182   u16 selFlags;          /* Various SF_* values */
11183   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11184   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11185   double nSelectRow;     /* Estimated number of result rows */
11186   SrcList *pSrc;         /* The FROM clause */
11187   Expr *pWhere;          /* The WHERE clause */
11188   ExprList *pGroupBy;    /* The GROUP BY clause */
11189   Expr *pHaving;         /* The HAVING clause */
11190   ExprList *pOrderBy;    /* The ORDER BY clause */
11191   Select *pPrior;        /* Prior select in a compound select statement */
11192   Select *pNext;         /* Next select to the left in a compound */
11193   Select *pRightmost;    /* Right-most select in a compound select statement */
11194   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11195   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11196 };
11197 
11198 /*
11199 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11200 ** "Select Flag".
11201 */
11202 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
11203 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
11204 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
11205 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11206 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11207 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11208 #define SF_UseSorter       0x0040  /* Sort using a sorter */
11209 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
11210 #define SF_Materialize     0x0100  /* Force materialization of views */
11211 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11212 
11213 
11214 /*
11215 ** The results of a select can be distributed in several ways.  The
11216 ** "SRT" prefix means "SELECT Result Type".
11217 */
11218 #define SRT_Union        1  /* Store result as keys in an index */
11219 #define SRT_Except       2  /* Remove result from a UNION index */
11220 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11221 #define SRT_Discard      4  /* Do not save the results anywhere */
11222 
11223 /* The ORDER BY clause is ignored for all of the above */
11224 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11225 
11226 #define SRT_Output       5  /* Output each row of result */
11227 #define SRT_Mem          6  /* Store result in a memory cell */
11228 #define SRT_Set          7  /* Store results as keys in an index */
11229 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11230 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11231 #define SRT_Coroutine   10  /* Generate a single row of result */
11232 
11233 /*
11234 ** An instance of this object describes where to put of the results of
11235 ** a SELECT statement.
11236 */
11237 struct SelectDest {
11238   u8 eDest;         /* How to dispose of the results.  On of SRT_* above. */
11239   char affSdst;     /* Affinity used when eDest==SRT_Set */
11240   int iSDParm;      /* A parameter used by the eDest disposal method */
11241   int iSdst;        /* Base register where results are written */
11242   int nSdst;        /* Number of registers allocated */
11243 };
11244 
11245 /*
11246 ** During code generation of statements that do inserts into AUTOINCREMENT
11247 ** tables, the following information is attached to the Table.u.autoInc.p
11248 ** pointer of each autoincrement table to record some side information that
11249 ** the code generator needs.  We have to keep per-table autoincrement
11250 ** information in case inserts are down within triggers.  Triggers do not
11251 ** normally coordinate their activities, but we do need to coordinate the
11252 ** loading and saving of autoincrement information.
11253 */
11254 struct AutoincInfo {
11255   AutoincInfo *pNext;   /* Next info block in a list of them all */
11256   Table *pTab;          /* Table this info block refers to */
11257   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11258   int regCtr;           /* Memory register holding the rowid counter */
11259 };
11260 
11261 /*
11262 ** Size of the column cache
11263 */
11264 #ifndef SQLITE_N_COLCACHE
11265 # define SQLITE_N_COLCACHE 10
11266 #endif
11267 
11268 /*
11269 ** At least one instance of the following structure is created for each
11270 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11271 ** statement. All such objects are stored in the linked list headed at
11272 ** Parse.pTriggerPrg and deleted once statement compilation has been
11273 ** completed.
11274 **
11275 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11276 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11277 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11278 ** The Parse.pTriggerPrg list never contains two entries with the same
11279 ** values for both pTrigger and orconf.
11280 **
11281 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11282 ** accessed (or set to 0 for triggers fired as a result of INSERT
11283 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11284 ** a mask of new.* columns used by the program.
11285 */
11286 struct TriggerPrg {
11287   Trigger *pTrigger;      /* Trigger this program was coded from */
11288   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11289   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11290   int orconf;             /* Default ON CONFLICT policy */
11291   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11292 };
11293 
11294 /*
11295 ** The yDbMask datatype for the bitmask of all attached databases.
11296 */
11297 #if SQLITE_MAX_ATTACHED>30
11298   typedef sqlite3_uint64 yDbMask;
11299 #else
11300   typedef unsigned int yDbMask;
11301 #endif
11302 
11303 /*
11304 ** An SQL parser context.  A copy of this structure is passed through
11305 ** the parser and down into all the parser action routine in order to
11306 ** carry around information that is global to the entire parse.
11307 **
11308 ** The structure is divided into two parts.  When the parser and code
11309 ** generate call themselves recursively, the first part of the structure
11310 ** is constant but the second part is reset at the beginning and end of
11311 ** each recursion.
11312 **
11313 ** The nTableLock and aTableLock variables are only used if the shared-cache
11314 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11315 ** used to store the set of table-locks required by the statement being
11316 ** compiled. Function sqlite3TableLock() is used to add entries to the
11317 ** list.
11318 */
11319 struct Parse {
11320   sqlite3 *db;         /* The main database structure */
11321   char *zErrMsg;       /* An error message */
11322   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11323   int rc;              /* Return code from execution */
11324   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11325   u8 checkSchema;      /* Causes schema cookie check after an error */
11326   u8 nested;           /* Number of nested calls to the parser/code generator */
11327   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11328   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11329   u8 nColCache;        /* Number of entries in aColCache[] */
11330   u8 iColCache;        /* Next entry in aColCache[] to replace */
11331   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11332   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11333   int aTempReg[8];     /* Holding area for temporary registers */
11334   int nRangeReg;       /* Size of the temporary register block */
11335   int iRangeReg;       /* First register in temporary register block */
11336   int nErr;            /* Number of errors seen */
11337   int nTab;            /* Number of previously allocated VDBE cursors */
11338   int nMem;            /* Number of memory cells used so far */
11339   int nSet;            /* Number of sets used so far */
11340   int nOnce;           /* Number of OP_Once instructions so far */
11341   int ckBase;          /* Base register of data during check constraints */
11342   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11343   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11344   struct yColCache {
11345     int iTable;           /* Table cursor number */
11346     int iColumn;          /* Table column number */
11347     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11348     int iLevel;           /* Nesting level */
11349     int iReg;             /* Reg with value of this column. 0 means none. */
11350     int lru;              /* Least recently used entry has the smallest value */
11351   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11352   yDbMask writeMask;   /* Start a write transaction on these databases */
11353   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11354   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11355   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11356   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11357   int regRoot;         /* Register holding root page number for new objects */
11358   int nMaxArg;         /* Max args passed to user function by sub-program */
11359   Token constraintName;/* Name of the constraint currently being parsed */
11360 #ifndef SQLITE_OMIT_SHARED_CACHE
11361   int nTableLock;        /* Number of locks in aTableLock */
11362   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11363 #endif
11364   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11365 
11366   /* Information used while coding trigger programs. */
11367   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11368   Table *pTriggerTab;  /* Table triggers are being coded for */
11369   double nQueryLoop;   /* Estimated number of iterations of a query */
11370   u32 oldmask;         /* Mask of old.* columns referenced */
11371   u32 newmask;         /* Mask of new.* columns referenced */
11372   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11373   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11374   u8 disableTriggers;  /* True to disable triggers */
11375 
11376   /* Above is constant between recursions.  Below is reset before and after
11377   ** each recursion */
11378 
11379   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11380   int nzVar;                /* Number of available slots in azVar[] */
11381   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11382 #ifndef SQLITE_OMIT_VIRTUALTABLE
11383   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11384   int nVtabLock;            /* Number of virtual tables to lock */
11385 #endif
11386   int nAlias;               /* Number of aliased result set columns */
11387   int nHeight;              /* Expression tree height of current sub-select */
11388 #ifndef SQLITE_OMIT_EXPLAIN
11389   int iSelectId;            /* ID of current select for EXPLAIN output */
11390   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11391 #endif
11392   char **azVar;             /* Pointers to names of parameters */
11393   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11394   int *aAlias;              /* Register used to hold aliased result */
11395   const char *zTail;        /* All SQL text past the last semicolon parsed */
11396   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11397   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11398   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11399   Token sNameToken;         /* Token with unqualified schema object name */
11400   Token sLastToken;         /* The last token parsed */
11401 #ifndef SQLITE_OMIT_VIRTUALTABLE
11402   Token sArg;               /* Complete text of a module argument */
11403   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11404 #endif
11405   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11406   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11407 };
11408 
11409 /*
11410 ** Return true if currently inside an sqlite3_declare_vtab() call.
11411 */
11412 #ifdef SQLITE_OMIT_VIRTUALTABLE
11413   #define IN_DECLARE_VTAB 0
11414 #else
11415   #define IN_DECLARE_VTAB (pParse->declareVtab)
11416 #endif
11417 
11418 /*
11419 ** An instance of the following structure can be declared on a stack and used
11420 ** to save the Parse.zAuthContext value so that it can be restored later.
11421 */
11422 struct AuthContext {
11423   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11424   Parse *pParse;              /* The Parse structure */
11425 };
11426 
11427 /*
11428 ** Bitfield flags for P5 value in various opcodes.
11429 */
11430 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11431 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11432 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11433 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11434 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11435 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11436 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11437 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11438 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11439 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11440 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
11441 
11442 /*
11443  * Each trigger present in the database schema is stored as an instance of
11444  * struct Trigger.
11445  *
11446  * Pointers to instances of struct Trigger are stored in two ways.
11447  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11448  *    database). This allows Trigger structures to be retrieved by name.
11449  * 2. All triggers associated with a single table form a linked list, using the
11450  *    pNext member of struct Trigger. A pointer to the first element of the
11451  *    linked list is stored as the "pTrigger" member of the associated
11452  *    struct Table.
11453  *
11454  * The "step_list" member points to the first element of a linked list
11455  * containing the SQL statements specified as the trigger program.
11456  */
11457 struct Trigger {
11458   char *zName;            /* The name of the trigger                        */
11459   char *table;            /* The table or view to which the trigger applies */
11460   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11461   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11462   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11463   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11464                              the <column-list> is stored here */
11465   Schema *pSchema;        /* Schema containing the trigger */
11466   Schema *pTabSchema;     /* Schema containing the table */
11467   TriggerStep *step_list; /* Link list of trigger program steps             */
11468   Trigger *pNext;         /* Next trigger associated with the table */
11469 };
11470 
11471 /*
11472 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11473 ** determine which.
11474 **
11475 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11476 ** In that cases, the constants below can be ORed together.
11477 */
11478 #define TRIGGER_BEFORE  1
11479 #define TRIGGER_AFTER   2
11480 
11481 /*
11482  * An instance of struct TriggerStep is used to store a single SQL statement
11483  * that is a part of a trigger-program.
11484  *
11485  * Instances of struct TriggerStep are stored in a singly linked list (linked
11486  * using the "pNext" member) referenced by the "step_list" member of the
11487  * associated struct Trigger instance. The first element of the linked list is
11488  * the first step of the trigger-program.
11489  *
11490  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11491  * "SELECT" statement. The meanings of the other members is determined by the
11492  * value of "op" as follows:
11493  *
11494  * (op == TK_INSERT)
11495  * orconf    -> stores the ON CONFLICT algorithm
11496  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11497  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11498  * target    -> A token holding the quoted name of the table to insert into.
11499  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11500  *              this stores values to be inserted. Otherwise NULL.
11501  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11502  *              statement, then this stores the column-names to be
11503  *              inserted into.
11504  *
11505  * (op == TK_DELETE)
11506  * target    -> A token holding the quoted name of the table to delete from.
11507  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11508  *              Otherwise NULL.
11509  *
11510  * (op == TK_UPDATE)
11511  * target    -> A token holding the quoted name of the table to update rows of.
11512  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11513  *              Otherwise NULL.
11514  * pExprList -> A list of the columns to update and the expressions to update
11515  *              them to. See sqlite3Update() documentation of "pChanges"
11516  *              argument.
11517  *
11518  */
11519 struct TriggerStep {
11520   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11521   u8 orconf;           /* OE_Rollback etc. */
11522   Trigger *pTrig;      /* The trigger that this step is a part of */
11523   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11524   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11525   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11526   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11527   IdList *pIdList;     /* Column names for INSERT */
11528   TriggerStep *pNext;  /* Next in the link-list */
11529   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11530 };
11531 
11532 /*
11533 ** The following structure contains information used by the sqliteFix...
11534 ** routines as they walk the parse tree to make database references
11535 ** explicit.
11536 */
11537 typedef struct DbFixer DbFixer;
11538 struct DbFixer {
11539   Parse *pParse;      /* The parsing context.  Error messages written here */
11540   Schema *pSchema;    /* Fix items to this schema */
11541   const char *zDb;    /* Make sure all objects are contained in this database */
11542   const char *zType;  /* Type of the container - used for error messages */
11543   const Token *pName; /* Name of the container - used for error messages */
11544 };
11545 
11546 /*
11547 ** An objected used to accumulate the text of a string where we
11548 ** do not necessarily know how big the string will be in the end.
11549 */
11550 struct StrAccum {
11551   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11552   char *zBase;         /* A base allocation.  Not from malloc. */
11553   char *zText;         /* The string collected so far */
11554   int  nChar;          /* Length of the string so far */
11555   int  nAlloc;         /* Amount of space allocated in zText */
11556   int  mxAlloc;        /* Maximum allowed string length */
11557   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11558   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11559   u8   tooBig;         /* Becomes true if string size exceeds limits */
11560 };
11561 
11562 /*
11563 ** A pointer to this structure is used to communicate information
11564 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11565 */
11566 typedef struct {
11567   sqlite3 *db;        /* The database being initialized */
11568   char **pzErrMsg;    /* Error message stored here */
11569   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11570   int rc;             /* Result code stored here */
11571 } InitData;
11572 
11573 /*
11574 ** Structure containing global configuration data for the SQLite library.
11575 **
11576 ** This structure also contains some state information.
11577 */
11578 struct Sqlite3Config {
11579   int bMemstat;                     /* True to enable memory status */
11580   int bCoreMutex;                   /* True to enable core mutexing */
11581   int bFullMutex;                   /* True to enable full mutexing */
11582   int bOpenUri;                     /* True to interpret filenames as URIs */
11583   int bUseCis;                      /* Use covering indices for full-scans */
11584   int mxStrlen;                     /* Maximum string length */
11585   int szLookaside;                  /* Default lookaside buffer size */
11586   int nLookaside;                   /* Default lookaside buffer count */
11587   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11588   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11589   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11590   void *pHeap;                      /* Heap storage space */
11591   int nHeap;                        /* Size of pHeap[] */
11592   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11593   void *pScratch;                   /* Scratch memory */
11594   int szScratch;                    /* Size of each scratch buffer */
11595   int nScratch;                     /* Number of scratch buffers */
11596   void *pPage;                      /* Page cache memory */
11597   int szPage;                       /* Size of each page in pPage[] */
11598   int nPage;                        /* Number of pages in pPage[] */
11599   int mxParserStack;                /* maximum depth of the parser stack */
11600   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11601   /* The above might be initialized to non-zero.  The following need to always
11602   ** initially be zero, however. */
11603   int isInit;                       /* True after initialization has finished */
11604   int inProgress;                   /* True while initialization in progress */
11605   int isMutexInit;                  /* True after mutexes are initialized */
11606   int isMallocInit;                 /* True after malloc is initialized */
11607   int isPCacheInit;                 /* True after malloc is initialized */
11608   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11609   int nRefInitMutex;                /* Number of users of pInitMutex */
11610   void (*xLog)(void*,int,const char*); /* Function for logging */
11611   void *pLogArg;                       /* First argument to xLog() */
11612   int bLocaltimeFault;              /* True to fail localtime() calls */
11613 #ifdef SQLITE_ENABLE_SQLLOG
11614   void(*xSqllog)(void*,sqlite3*,const char*, int);
11615   void *pSqllogArg;
11616 #endif
11617 };
11618 
11619 /*
11620 ** Context pointer passed down through the tree-walk.
11621 */
11622 struct Walker {
11623   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11624   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11625   Parse *pParse;                            /* Parser context.  */
11626   int walkerDepth;                          /* Number of subqueries */
11627   union {                                   /* Extra data for callback */
11628     NameContext *pNC;                          /* Naming context */
11629     int i;                                     /* Integer value */
11630     SrcList *pSrcList;                         /* FROM clause */
11631     struct SrcCount *pSrcCount;                /* Counting column references */
11632   } u;
11633 };
11634 
11635 /* Forward declarations */
11636 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11637 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11638 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11639 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11640 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11641 
11642 /*
11643 ** Return code from the parse-tree walking primitives and their
11644 ** callbacks.
11645 */
11646 #define WRC_Continue    0   /* Continue down into children */
11647 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11648 #define WRC_Abort       2   /* Abandon the tree walk */
11649 
11650 /*
11651 ** Assuming zIn points to the first byte of a UTF-8 character,
11652 ** advance zIn to point to the first byte of the next UTF-8 character.
11653 */
11654 #define SQLITE_SKIP_UTF8(zIn) {                        \
11655   if( (*(zIn++))>=0xc0 ){                              \
11656     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11657   }                                                    \
11658 }
11659 
11660 /*
11661 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11662 ** the same name but without the _BKPT suffix.  These macros invoke
11663 ** routines that report the line-number on which the error originated
11664 ** using sqlite3_log().  The routines also provide a convenient place
11665 ** to set a debugger breakpoint.
11666 */
11667 SQLITE_PRIVATE int sqlite3CorruptError(int);
11668 SQLITE_PRIVATE int sqlite3MisuseError(int);
11669 SQLITE_PRIVATE int sqlite3CantopenError(int);
11670 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11671 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11672 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11673 
11674 
11675 /*
11676 ** FTS4 is really an extension for FTS3.  It is enabled using the
11677 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11678 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11679 */
11680 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11681 # define SQLITE_ENABLE_FTS3
11682 #endif
11683 
11684 /*
11685 ** The ctype.h header is needed for non-ASCII systems.  It is also
11686 ** needed by FTS3 when FTS3 is included in the amalgamation.
11687 */
11688 #if !defined(SQLITE_ASCII) || \
11689     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11690 # include <ctype.h>
11691 #endif
11692 
11693 /*
11694 ** The following macros mimic the standard library functions toupper(),
11695 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11696 ** sqlite versions only work for ASCII characters, regardless of locale.
11697 */
11698 #ifdef SQLITE_ASCII
11699 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11700 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11701 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11702 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11703 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11704 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11705 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11706 #else
11707 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11708 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11709 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11710 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11711 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11712 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11713 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11714 #endif
11715 
11716 /*
11717 ** Internal function prototypes
11718 */
11719 #define sqlite3StrICmp sqlite3_stricmp
11720 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11721 #define sqlite3StrNICmp sqlite3_strnicmp
11722 
11723 SQLITE_PRIVATE int sqlite3MallocInit(void);
11724 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11725 SQLITE_PRIVATE void *sqlite3Malloc(int);
11726 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11727 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11728 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11729 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11730 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11731 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11732 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11733 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11734 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11735 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11736 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11737 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11738 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11739 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11740 SQLITE_PRIVATE void sqlite3PageFree(void*);
11741 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11742 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11743 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11744 
11745 /*
11746 ** On systems with ample stack space and that support alloca(), make
11747 ** use of alloca() to obtain space for large automatic objects.  By default,
11748 ** obtain space from malloc().
11749 **
11750 ** The alloca() routine never returns NULL.  This will cause code paths
11751 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11752 */
11753 #ifdef SQLITE_USE_ALLOCA
11754 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11755 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11756 # define sqlite3StackFree(D,P)
11757 #else
11758 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11759 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11760 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11761 #endif
11762 
11763 #ifdef SQLITE_ENABLE_MEMSYS3
11764 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11765 #endif
11766 #ifdef SQLITE_ENABLE_MEMSYS5
11767 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11768 #endif
11769 
11770 
11771 #ifndef SQLITE_MUTEX_OMIT
11772 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11773 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11774 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11775 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11776 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11777 #endif
11778 
11779 SQLITE_PRIVATE int sqlite3StatusValue(int);
11780 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11781 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11782 
11783 #ifndef SQLITE_OMIT_FLOATING_POINT
11784 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11785 #else
11786 # define sqlite3IsNaN(X)  0
11787 #endif
11788 
11789 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11790 #ifndef SQLITE_OMIT_TRACE
11791 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11792 #endif
11793 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11794 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11795 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11796 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11797 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11798 #endif
11799 #if defined(SQLITE_TEST)
11800 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11801 #endif
11802 
11803 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11804 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11805 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11806 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11807 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11808 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11809 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11810 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11811 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11812 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11813 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11814 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11815 #else
11816 # define sqlite3ExplainBegin(X)
11817 # define sqlite3ExplainSelect(A,B)
11818 # define sqlite3ExplainExpr(A,B)
11819 # define sqlite3ExplainExprList(A,B)
11820 # define sqlite3ExplainFinish(X)
11821 # define sqlite3VdbeExplanation(X) 0
11822 #endif
11823 
11824 
11825 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11826 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11827 SQLITE_PRIVATE int sqlite3Dequote(char*);
11828 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11829 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11830 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11831 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11832 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11833 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11834 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11835 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11836 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11837 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11838 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11839 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11840 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11841 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11842 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11843 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11844 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11845 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11846 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11847 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11848 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11849 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11850 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11851 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11852 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11853 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11854 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11855 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11856 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11857 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11858 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11859 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11860 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11861 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11862 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11863 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11864 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11865 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11866 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11867 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11868                     sqlite3_vfs**,char**,char **);
11869 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11870 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11871 
11872 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11873 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11874 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11875 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11876 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11877 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11878 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11879 
11880 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11881 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11882 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11883 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11884 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11885 
11886 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11887 
11888 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11889 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11890 #else
11891 # define sqlite3ViewGetColumnNames(A,B) 0
11892 #endif
11893 
11894 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11895 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11896 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11897 #ifndef SQLITE_OMIT_AUTOINCREMENT
11898 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11899 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11900 #else
11901 # define sqlite3AutoincrementBegin(X)
11902 # define sqlite3AutoincrementEnd(X)
11903 #endif
11904 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
11905 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11906 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11907 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11908 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11909 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11910 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11911 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11912                                       Token*, Select*, Expr*, IdList*);
11913 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11914 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11915 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11916 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11917 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11918 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11919 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11920                         Token*, int, int);
11921 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11922 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11923 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11924                          Expr*,ExprList*,u16,Expr*,Expr*);
11925 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11926 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11927 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11928 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11929 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11930 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
11931 #endif
11932 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11933 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11934 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
11935 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11936 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
11937 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11938 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11939 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11940 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11941 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11942 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11943 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11944 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11945 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11946 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11947 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11948 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11949 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11950 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11951 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11952 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11953 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11954 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11955 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
11956 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11957 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11958 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11959 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11960 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11961 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11962 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11963 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11964 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11965 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11966 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
11967 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11968 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11969 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11970 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11971 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11972 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11973 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11974 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11975 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11976 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11977 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11978 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11979 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
11980 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11981 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11982 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11983 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11984 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11985 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11986 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11987 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11988 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11989 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11990 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11991 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11992                                      int*,int,int,int,int,int*);
11993 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11994 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11995 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11996 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11997 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11998 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
11999 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12000 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12001 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12002 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12003 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12004 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12005 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12006 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12007 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12008 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12009 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12010 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12011 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12012 
12013 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12014 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12015 #endif
12016 
12017 #ifndef SQLITE_OMIT_TRIGGER
12018 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12019                            Expr*,int, int);
12020 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12021 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12022 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12023 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12024 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12025 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12026                             int, int, int);
12027 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12028   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12029 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12030 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12031 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12032                                         ExprList*,Select*,u8);
12033 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12034 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12035 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12036 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12037 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12038 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12039 #else
12040 # define sqlite3TriggersExist(B,C,D,E,F) 0
12041 # define sqlite3DeleteTrigger(A,B)
12042 # define sqlite3DropTriggerPtr(A,B)
12043 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12044 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12045 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12046 # define sqlite3TriggerList(X, Y) 0
12047 # define sqlite3ParseToplevel(p) p
12048 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12049 #endif
12050 
12051 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12052 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12053 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12054 #ifndef SQLITE_OMIT_AUTHORIZATION
12055 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12056 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12057 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12058 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12059 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12060 #else
12061 # define sqlite3AuthRead(a,b,c,d)
12062 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12063 # define sqlite3AuthContextPush(a,b,c)
12064 # define sqlite3AuthContextPop(a)  ((void)(a))
12065 #endif
12066 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12067 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12068 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12069 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12070 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12071 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12072 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12073 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12074 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12075 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12076 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12077 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12078 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12079 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12080 
12081 /*
12082 ** Routines to read and write variable-length integers.  These used to
12083 ** be defined locally, but now we use the varint routines in the util.c
12084 ** file.  Code should use the MACRO forms below, as the Varint32 versions
12085 ** are coded to assume the single byte case is already handled (which
12086 ** the MACRO form does).
12087 */
12088 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12089 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12090 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12091 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12092 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12093 
12094 /*
12095 ** The header of a record consists of a sequence variable-length integers.
12096 ** These integers are almost always small and are encoded as a single byte.
12097 ** The following macros take advantage this fact to provide a fast encode
12098 ** and decode of the integers in a record header.  It is faster for the common
12099 ** case where the integer is a single byte.  It is a little slower when the
12100 ** integer is two or more bytes.  But overall it is faster.
12101 **
12102 ** The following expressions are equivalent:
12103 **
12104 **     x = sqlite3GetVarint32( A, &B );
12105 **     x = sqlite3PutVarint32( A, B );
12106 **
12107 **     x = getVarint32( A, B );
12108 **     x = putVarint32( A, B );
12109 **
12110 */
12111 #define getVarint32(A,B)  \
12112   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12113 #define putVarint32(A,B)  \
12114   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12115   sqlite3PutVarint32((A),(B)))
12116 #define getVarint    sqlite3GetVarint
12117 #define putVarint    sqlite3PutVarint
12118 
12119 
12120 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12121 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12122 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12123 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12124 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12125 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12126 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12127 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12128 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12129 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12130 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12131 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12132 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12133 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12134 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12135 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12136 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12137 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12138 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12139 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12140 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12141 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12142 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12143 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12144 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12145 #ifdef SQLITE_ENABLE_8_3_NAMES
12146 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12147 #else
12148 # define sqlite3FileSuffix3(X,Y)
12149 #endif
12150 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12151 
12152 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12153 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12154 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12155                         void(*)(void*));
12156 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12157 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12158 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12159 #ifdef SQLITE_ENABLE_STAT3
12160 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12161 #endif
12162 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12163 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12164 #ifndef SQLITE_AMALGAMATION
12165 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12166 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12167 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12168 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12169 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12170 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12171 #ifndef SQLITE_OMIT_WSD
12172 SQLITE_PRIVATE int sqlite3PendingByte;
12173 #endif
12174 #endif
12175 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12176 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12177 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12178 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12179 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12180 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12181 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12182 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12183 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12184 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12185 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12186 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12187 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12188 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12189 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12190 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12191 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12192 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12193 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12194 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12195 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12196 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12197 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12198 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12199 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12200 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12201 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12202 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12203 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12204 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12205 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12206 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12207 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
12208   void (*)(sqlite3_context*,int,sqlite3_value **),
12209   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12210   FuncDestructor *pDestructor
12211 );
12212 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12213 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12214 
12215 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12216 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12217 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12218 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12219 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12220 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12221 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12222 
12223 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12224 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12225 
12226 /*
12227 ** The interface to the LEMON-generated parser
12228 */
12229 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12230 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12231 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12232 #ifdef YYTRACKMAXSTACKDEPTH
12233 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12234 #endif
12235 
12236 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12237 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12238 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12239 #else
12240 # define sqlite3CloseExtensions(X)
12241 #endif
12242 
12243 #ifndef SQLITE_OMIT_SHARED_CACHE
12244 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12245 #else
12246   #define sqlite3TableLock(v,w,x,y,z)
12247 #endif
12248 
12249 #ifdef SQLITE_TEST
12250 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12251 #endif
12252 
12253 #ifdef SQLITE_OMIT_VIRTUALTABLE
12254 #  define sqlite3VtabClear(Y)
12255 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12256 #  define sqlite3VtabRollback(X)
12257 #  define sqlite3VtabCommit(X)
12258 #  define sqlite3VtabInSync(db) 0
12259 #  define sqlite3VtabLock(X)
12260 #  define sqlite3VtabUnlock(X)
12261 #  define sqlite3VtabUnlockList(X)
12262 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12263 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12264 #else
12265 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12266 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12267 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12268 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12269 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12270 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12271 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12272 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12273 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12274 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12275 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12276 #endif
12277 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12278 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12279 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12280 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12281 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12282 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12283 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12284 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12285 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12286 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12287 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12288 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12289 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12290 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12291 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12292 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12293 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12294 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12295 #ifndef SQLITE_OMIT_WAL
12296 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12297 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12298 #endif
12299 
12300 /* Declarations for functions in fkey.c. All of these are replaced by
12301 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12302 ** key functionality is available. If OMIT_TRIGGER is defined but
12303 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12304 ** this case foreign keys are parsed, but no other functionality is
12305 ** provided (enforcement of FK constraints requires the triggers sub-system).
12306 */
12307 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12308 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12309 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12310 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12311 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12312 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12313 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12314 #else
12315   #define sqlite3FkActions(a,b,c,d)
12316   #define sqlite3FkCheck(a,b,c,d)
12317   #define sqlite3FkDropTable(a,b,c)
12318   #define sqlite3FkOldmask(a,b)      0
12319   #define sqlite3FkRequired(a,b,c,d) 0
12320 #endif
12321 #ifndef SQLITE_OMIT_FOREIGN_KEY
12322 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12323 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12324 #else
12325   #define sqlite3FkDelete(a,b)
12326   #define sqlite3FkLocateIndex(a,b,c,d,e)
12327 #endif
12328 
12329 
12330 /*
12331 ** Available fault injectors.  Should be numbered beginning with 0.
12332 */
12333 #define SQLITE_FAULTINJECTOR_MALLOC     0
12334 #define SQLITE_FAULTINJECTOR_COUNT      1
12335 
12336 /*
12337 ** The interface to the code in fault.c used for identifying "benign"
12338 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12339 ** is not defined.
12340 */
12341 #ifndef SQLITE_OMIT_BUILTIN_TEST
12342 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12343 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12344 #else
12345   #define sqlite3BeginBenignMalloc()
12346   #define sqlite3EndBenignMalloc()
12347 #endif
12348 
12349 #define IN_INDEX_ROWID           1
12350 #define IN_INDEX_EPH             2
12351 #define IN_INDEX_INDEX_ASC       3
12352 #define IN_INDEX_INDEX_DESC      4
12353 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12354 
12355 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12356 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12357 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12358 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12359 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
12360 #else
12361   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12362   #define sqlite3JournalExists(p) 1
12363 #endif
12364 
12365 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12366 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12367 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12368 
12369 #if SQLITE_MAX_EXPR_DEPTH>0
12370 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12371 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12372 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12373 #else
12374   #define sqlite3ExprSetHeight(x,y)
12375   #define sqlite3SelectExprHeight(x) 0
12376   #define sqlite3ExprCheckHeight(x,y)
12377 #endif
12378 
12379 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12380 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12381 
12382 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12383 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12384 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12385 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12386 #else
12387   #define sqlite3ConnectionBlocked(x,y)
12388   #define sqlite3ConnectionUnlocked(x)
12389   #define sqlite3ConnectionClosed(x)
12390 #endif
12391 
12392 #ifdef SQLITE_DEBUG
12393 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12394 #endif
12395 
12396 /*
12397 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12398 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12399 ** print I/O tracing messages.
12400 */
12401 #ifdef SQLITE_ENABLE_IOTRACE
12402 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12403 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12404 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12405 #else
12406 # define IOTRACE(A)
12407 # define sqlite3VdbeIOTraceSql(X)
12408 #endif
12409 
12410 /*
12411 ** These routines are available for the mem2.c debugging memory allocator
12412 ** only.  They are used to verify that different "types" of memory
12413 ** allocations are properly tracked by the system.
12414 **
12415 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12416 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12417 ** a single bit set.
12418 **
12419 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12420 ** argument match the type set by the previous sqlite3MemdebugSetType().
12421 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12422 **
12423 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12424 ** argument match the type set by the previous sqlite3MemdebugSetType().
12425 **
12426 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12427 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12428 ** it might have been allocated by lookaside, except the allocation was
12429 ** too large or lookaside was already full.  It is important to verify
12430 ** that allocations that might have been satisfied by lookaside are not
12431 ** passed back to non-lookaside free() routines.  Asserts such as the
12432 ** example above are placed on the non-lookaside free() routines to verify
12433 ** this constraint.
12434 **
12435 ** All of this is no-op for a production build.  It only comes into
12436 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12437 */
12438 #ifdef SQLITE_MEMDEBUG
12439 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12440 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12441 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12442 #else
12443 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12444 # define sqlite3MemdebugHasType(X,Y)  1
12445 # define sqlite3MemdebugNoType(X,Y)   1
12446 #endif
12447 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12448 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12449 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12450 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12451 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12452 
12453 #endif /* _SQLITEINT_H_ */
12454 
12455 /************** End of sqliteInt.h *******************************************/
12456 /************** Begin file global.c ******************************************/
12457 /*
12458 ** 2008 June 13
12459 **
12460 ** The author disclaims copyright to this source code.  In place of
12461 ** a legal notice, here is a blessing:
12462 **
12463 **    May you do good and not evil.
12464 **    May you find forgiveness for yourself and forgive others.
12465 **    May you share freely, never taking more than you give.
12466 **
12467 *************************************************************************
12468 **
12469 ** This file contains definitions of global variables and contants.
12470 */
12471 
12472 /* An array to map all upper-case characters into their corresponding
12473 ** lower-case character.
12474 **
12475 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12476 ** handle case conversions for the UTF character set since the tables
12477 ** involved are nearly as big or bigger than SQLite itself.
12478 */
12479 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12480 #ifdef SQLITE_ASCII
12481       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12482      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12483      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12484      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12485     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12486     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12487     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12488     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12489     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12490     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12491     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12492     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12493     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12494     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12495     252,253,254,255
12496 #endif
12497 #ifdef SQLITE_EBCDIC
12498       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12499      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12500      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12501      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12502      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12503      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12504      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12505     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12506     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12507     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12508     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12509     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12510     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12511     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12512     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12513     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12514 #endif
12515 };
12516 
12517 /*
12518 ** The following 256 byte lookup table is used to support SQLites built-in
12519 ** equivalents to the following standard library functions:
12520 **
12521 **   isspace()                        0x01
12522 **   isalpha()                        0x02
12523 **   isdigit()                        0x04
12524 **   isalnum()                        0x06
12525 **   isxdigit()                       0x08
12526 **   toupper()                        0x20
12527 **   SQLite identifier character      0x40
12528 **
12529 ** Bit 0x20 is set if the mapped character requires translation to upper
12530 ** case. i.e. if the character is a lower-case ASCII character.
12531 ** If x is a lower-case ASCII character, then its upper-case equivalent
12532 ** is (x - 0x20). Therefore toupper() can be implemented as:
12533 **
12534 **   (x & ~(map[x]&0x20))
12535 **
12536 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12537 ** array. tolower() is used more often than toupper() by SQLite.
12538 **
12539 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
12540 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12541 ** non-ASCII UTF character. Hence the test for whether or not a character is
12542 ** part of an identifier is 0x46.
12543 **
12544 ** SQLite's versions are identical to the standard versions assuming a
12545 ** locale of "C". They are implemented as macros in sqliteInt.h.
12546 */
12547 #ifdef SQLITE_ASCII
12548 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12549   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12550   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12551   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12552   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12553   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12554   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12555   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12556   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12557 
12558   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12559   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12560   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12561   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12562   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12563   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12564   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12565   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12566 
12567   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12568   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12569   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12570   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12571   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12572   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12573   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12574   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12575 
12576   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12577   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12578   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12579   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12580   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12581   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12582   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12583   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12584 };
12585 #endif
12586 
12587 #ifndef SQLITE_USE_URI
12588 # define  SQLITE_USE_URI 0
12589 #endif
12590 
12591 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12592 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12593 #endif
12594 
12595 /*
12596 ** The following singleton contains the global configuration for
12597 ** the SQLite library.
12598 */
12599 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12600    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12601    1,                         /* bCoreMutex */
12602    SQLITE_THREADSAFE==1,      /* bFullMutex */
12603    SQLITE_USE_URI,            /* bOpenUri */
12604    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
12605    0x7ffffffe,                /* mxStrlen */
12606    128,                       /* szLookaside */
12607    500,                       /* nLookaside */
12608    {0,0,0,0,0,0,0,0},         /* m */
12609    {0,0,0,0,0,0,0,0,0},       /* mutex */
12610    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12611    (void*)0,                  /* pHeap */
12612    0,                         /* nHeap */
12613    0, 0,                      /* mnHeap, mxHeap */
12614    (void*)0,                  /* pScratch */
12615    0,                         /* szScratch */
12616    0,                         /* nScratch */
12617    (void*)0,                  /* pPage */
12618    0,                         /* szPage */
12619    0,                         /* nPage */
12620    0,                         /* mxParserStack */
12621    0,                         /* sharedCacheEnabled */
12622    /* All the rest should always be initialized to zero */
12623    0,                         /* isInit */
12624    0,                         /* inProgress */
12625    0,                         /* isMutexInit */
12626    0,                         /* isMallocInit */
12627    0,                         /* isPCacheInit */
12628    0,                         /* pInitMutex */
12629    0,                         /* nRefInitMutex */
12630    0,                         /* xLog */
12631    0,                         /* pLogArg */
12632    0,                         /* bLocaltimeFault */
12633 #ifdef SQLITE_ENABLE_SQLLOG
12634    0,                         /* xSqllog */
12635    0                          /* pSqllogArg */
12636 #endif
12637 };
12638 
12639 
12640 /*
12641 ** Hash table for global functions - functions common to all
12642 ** database connections.  After initialization, this table is
12643 ** read-only.
12644 */
12645 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12646 
12647 /*
12648 ** Constant tokens for values 0 and 1.
12649 */
12650 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12651    { "0", 1 },
12652    { "1", 1 }
12653 };
12654 
12655 
12656 /*
12657 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12658 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12659 ** the database page that contains the pending byte.  It never attempts
12660 ** to read or write that page.  The pending byte page is set assign
12661 ** for use by the VFS layers as space for managing file locks.
12662 **
12663 ** During testing, it is often desirable to move the pending byte to
12664 ** a different position in the file.  This allows code that has to
12665 ** deal with the pending byte to run on files that are much smaller
12666 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12667 ** move the pending byte.
12668 **
12669 ** IMPORTANT:  Changing the pending byte to any value other than
12670 ** 0x40000000 results in an incompatible database file format!
12671 ** Changing the pending byte during operating results in undefined
12672 ** and dileterious behavior.
12673 */
12674 #ifndef SQLITE_OMIT_WSD
12675 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12676 #endif
12677 
12678 /*
12679 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12680 ** created by mkopcodeh.awk during compilation.  Data is obtained
12681 ** from the comments following the "case OP_xxxx:" statements in
12682 ** the vdbe.c file.
12683 */
12684 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12685 
12686 /************** End of global.c **********************************************/
12687 /************** Begin file ctime.c *******************************************/
12688 /*
12689 ** 2010 February 23
12690 **
12691 ** The author disclaims copyright to this source code.  In place of
12692 ** a legal notice, here is a blessing:
12693 **
12694 **    May you do good and not evil.
12695 **    May you find forgiveness for yourself and forgive others.
12696 **    May you share freely, never taking more than you give.
12697 **
12698 *************************************************************************
12699 **
12700 ** This file implements routines used to report what compile-time options
12701 ** SQLite was built with.
12702 */
12703 
12704 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12705 
12706 
12707 /*
12708 ** An array of names of all compile-time options.  This array should
12709 ** be sorted A-Z.
12710 **
12711 ** This array looks large, but in a typical installation actually uses
12712 ** only a handful of compile-time options, so most times this array is usually
12713 ** rather short and uses little memory space.
12714 */
12715 static const char * const azCompileOpt[] = {
12716 
12717 /* These macros are provided to "stringify" the value of the define
12718 ** for those options in which the value is meaningful. */
12719 #define CTIMEOPT_VAL_(opt) #opt
12720 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12721 
12722 #ifdef SQLITE_32BIT_ROWID
12723   "32BIT_ROWID",
12724 #endif
12725 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12726   "4_BYTE_ALIGNED_MALLOC",
12727 #endif
12728 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12729   "CASE_SENSITIVE_LIKE",
12730 #endif
12731 #ifdef SQLITE_CHECK_PAGES
12732   "CHECK_PAGES",
12733 #endif
12734 #ifdef SQLITE_COVERAGE_TEST
12735   "COVERAGE_TEST",
12736 #endif
12737 #ifdef SQLITE_CURDIR
12738   "CURDIR",
12739 #endif
12740 #ifdef SQLITE_DEBUG
12741   "DEBUG",
12742 #endif
12743 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12744   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12745 #endif
12746 #ifdef SQLITE_DISABLE_DIRSYNC
12747   "DISABLE_DIRSYNC",
12748 #endif
12749 #ifdef SQLITE_DISABLE_LFS
12750   "DISABLE_LFS",
12751 #endif
12752 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12753   "ENABLE_ATOMIC_WRITE",
12754 #endif
12755 #ifdef SQLITE_ENABLE_CEROD
12756   "ENABLE_CEROD",
12757 #endif
12758 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12759   "ENABLE_COLUMN_METADATA",
12760 #endif
12761 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12762   "ENABLE_EXPENSIVE_ASSERT",
12763 #endif
12764 #ifdef SQLITE_ENABLE_FTS1
12765   "ENABLE_FTS1",
12766 #endif
12767 #ifdef SQLITE_ENABLE_FTS2
12768   "ENABLE_FTS2",
12769 #endif
12770 #ifdef SQLITE_ENABLE_FTS3
12771   "ENABLE_FTS3",
12772 #endif
12773 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12774   "ENABLE_FTS3_PARENTHESIS",
12775 #endif
12776 #ifdef SQLITE_ENABLE_FTS4
12777   "ENABLE_FTS4",
12778 #endif
12779 #ifdef SQLITE_ENABLE_ICU
12780   "ENABLE_ICU",
12781 #endif
12782 #ifdef SQLITE_ENABLE_IOTRACE
12783   "ENABLE_IOTRACE",
12784 #endif
12785 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12786   "ENABLE_LOAD_EXTENSION",
12787 #endif
12788 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12789   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12790 #endif
12791 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12792   "ENABLE_MEMORY_MANAGEMENT",
12793 #endif
12794 #ifdef SQLITE_ENABLE_MEMSYS3
12795   "ENABLE_MEMSYS3",
12796 #endif
12797 #ifdef SQLITE_ENABLE_MEMSYS5
12798   "ENABLE_MEMSYS5",
12799 #endif
12800 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12801   "ENABLE_OVERSIZE_CELL_CHECK",
12802 #endif
12803 #ifdef SQLITE_ENABLE_RTREE
12804   "ENABLE_RTREE",
12805 #endif
12806 #ifdef SQLITE_ENABLE_STAT3
12807   "ENABLE_STAT3",
12808 #endif
12809 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12810   "ENABLE_UNLOCK_NOTIFY",
12811 #endif
12812 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12813   "ENABLE_UPDATE_DELETE_LIMIT",
12814 #endif
12815 #ifdef SQLITE_HAS_CODEC
12816   "HAS_CODEC",
12817 #endif
12818 #ifdef SQLITE_HAVE_ISNAN
12819   "HAVE_ISNAN",
12820 #endif
12821 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12822   "HOMEGROWN_RECURSIVE_MUTEX",
12823 #endif
12824 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12825   "IGNORE_AFP_LOCK_ERRORS",
12826 #endif
12827 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12828   "IGNORE_FLOCK_LOCK_ERRORS",
12829 #endif
12830 #ifdef SQLITE_INT64_TYPE
12831   "INT64_TYPE",
12832 #endif
12833 #ifdef SQLITE_LOCK_TRACE
12834   "LOCK_TRACE",
12835 #endif
12836 #ifdef SQLITE_MAX_SCHEMA_RETRY
12837   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12838 #endif
12839 #ifdef SQLITE_MEMDEBUG
12840   "MEMDEBUG",
12841 #endif
12842 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12843   "MIXED_ENDIAN_64BIT_FLOAT",
12844 #endif
12845 #ifdef SQLITE_NO_SYNC
12846   "NO_SYNC",
12847 #endif
12848 #ifdef SQLITE_OMIT_ALTERTABLE
12849   "OMIT_ALTERTABLE",
12850 #endif
12851 #ifdef SQLITE_OMIT_ANALYZE
12852   "OMIT_ANALYZE",
12853 #endif
12854 #ifdef SQLITE_OMIT_ATTACH
12855   "OMIT_ATTACH",
12856 #endif
12857 #ifdef SQLITE_OMIT_AUTHORIZATION
12858   "OMIT_AUTHORIZATION",
12859 #endif
12860 #ifdef SQLITE_OMIT_AUTOINCREMENT
12861   "OMIT_AUTOINCREMENT",
12862 #endif
12863 #ifdef SQLITE_OMIT_AUTOINIT
12864   "OMIT_AUTOINIT",
12865 #endif
12866 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12867   "OMIT_AUTOMATIC_INDEX",
12868 #endif
12869 #ifdef SQLITE_OMIT_AUTORESET
12870   "OMIT_AUTORESET",
12871 #endif
12872 #ifdef SQLITE_OMIT_AUTOVACUUM
12873   "OMIT_AUTOVACUUM",
12874 #endif
12875 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12876   "OMIT_BETWEEN_OPTIMIZATION",
12877 #endif
12878 #ifdef SQLITE_OMIT_BLOB_LITERAL
12879   "OMIT_BLOB_LITERAL",
12880 #endif
12881 #ifdef SQLITE_OMIT_BTREECOUNT
12882   "OMIT_BTREECOUNT",
12883 #endif
12884 #ifdef SQLITE_OMIT_BUILTIN_TEST
12885   "OMIT_BUILTIN_TEST",
12886 #endif
12887 #ifdef SQLITE_OMIT_CAST
12888   "OMIT_CAST",
12889 #endif
12890 #ifdef SQLITE_OMIT_CHECK
12891   "OMIT_CHECK",
12892 #endif
12893 /* // redundant
12894 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12895 **   "OMIT_COMPILEOPTION_DIAGS",
12896 ** #endif
12897 */
12898 #ifdef SQLITE_OMIT_COMPLETE
12899   "OMIT_COMPLETE",
12900 #endif
12901 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12902   "OMIT_COMPOUND_SELECT",
12903 #endif
12904 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12905   "OMIT_DATETIME_FUNCS",
12906 #endif
12907 #ifdef SQLITE_OMIT_DECLTYPE
12908   "OMIT_DECLTYPE",
12909 #endif
12910 #ifdef SQLITE_OMIT_DEPRECATED
12911   "OMIT_DEPRECATED",
12912 #endif
12913 #ifdef SQLITE_OMIT_DISKIO
12914   "OMIT_DISKIO",
12915 #endif
12916 #ifdef SQLITE_OMIT_EXPLAIN
12917   "OMIT_EXPLAIN",
12918 #endif
12919 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12920   "OMIT_FLAG_PRAGMAS",
12921 #endif
12922 #ifdef SQLITE_OMIT_FLOATING_POINT
12923   "OMIT_FLOATING_POINT",
12924 #endif
12925 #ifdef SQLITE_OMIT_FOREIGN_KEY
12926   "OMIT_FOREIGN_KEY",
12927 #endif
12928 #ifdef SQLITE_OMIT_GET_TABLE
12929   "OMIT_GET_TABLE",
12930 #endif
12931 #ifdef SQLITE_OMIT_INCRBLOB
12932   "OMIT_INCRBLOB",
12933 #endif
12934 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12935   "OMIT_INTEGRITY_CHECK",
12936 #endif
12937 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12938   "OMIT_LIKE_OPTIMIZATION",
12939 #endif
12940 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12941   "OMIT_LOAD_EXTENSION",
12942 #endif
12943 #ifdef SQLITE_OMIT_LOCALTIME
12944   "OMIT_LOCALTIME",
12945 #endif
12946 #ifdef SQLITE_OMIT_LOOKASIDE
12947   "OMIT_LOOKASIDE",
12948 #endif
12949 #ifdef SQLITE_OMIT_MEMORYDB
12950   "OMIT_MEMORYDB",
12951 #endif
12952 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12953   "OMIT_OR_OPTIMIZATION",
12954 #endif
12955 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12956   "OMIT_PAGER_PRAGMAS",
12957 #endif
12958 #ifdef SQLITE_OMIT_PRAGMA
12959   "OMIT_PRAGMA",
12960 #endif
12961 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12962   "OMIT_PROGRESS_CALLBACK",
12963 #endif
12964 #ifdef SQLITE_OMIT_QUICKBALANCE
12965   "OMIT_QUICKBALANCE",
12966 #endif
12967 #ifdef SQLITE_OMIT_REINDEX
12968   "OMIT_REINDEX",
12969 #endif
12970 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12971   "OMIT_SCHEMA_PRAGMAS",
12972 #endif
12973 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12974   "OMIT_SCHEMA_VERSION_PRAGMAS",
12975 #endif
12976 #ifdef SQLITE_OMIT_SHARED_CACHE
12977   "OMIT_SHARED_CACHE",
12978 #endif
12979 #ifdef SQLITE_OMIT_SUBQUERY
12980   "OMIT_SUBQUERY",
12981 #endif
12982 #ifdef SQLITE_OMIT_TCL_VARIABLE
12983   "OMIT_TCL_VARIABLE",
12984 #endif
12985 #ifdef SQLITE_OMIT_TEMPDB
12986   "OMIT_TEMPDB",
12987 #endif
12988 #ifdef SQLITE_OMIT_TRACE
12989   "OMIT_TRACE",
12990 #endif
12991 #ifdef SQLITE_OMIT_TRIGGER
12992   "OMIT_TRIGGER",
12993 #endif
12994 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12995   "OMIT_TRUNCATE_OPTIMIZATION",
12996 #endif
12997 #ifdef SQLITE_OMIT_UTF16
12998   "OMIT_UTF16",
12999 #endif
13000 #ifdef SQLITE_OMIT_VACUUM
13001   "OMIT_VACUUM",
13002 #endif
13003 #ifdef SQLITE_OMIT_VIEW
13004   "OMIT_VIEW",
13005 #endif
13006 #ifdef SQLITE_OMIT_VIRTUALTABLE
13007   "OMIT_VIRTUALTABLE",
13008 #endif
13009 #ifdef SQLITE_OMIT_WAL
13010   "OMIT_WAL",
13011 #endif
13012 #ifdef SQLITE_OMIT_WSD
13013   "OMIT_WSD",
13014 #endif
13015 #ifdef SQLITE_OMIT_XFER_OPT
13016   "OMIT_XFER_OPT",
13017 #endif
13018 #ifdef SQLITE_PERFORMANCE_TRACE
13019   "PERFORMANCE_TRACE",
13020 #endif
13021 #ifdef SQLITE_PROXY_DEBUG
13022   "PROXY_DEBUG",
13023 #endif
13024 #ifdef SQLITE_RTREE_INT_ONLY
13025   "RTREE_INT_ONLY",
13026 #endif
13027 #ifdef SQLITE_SECURE_DELETE
13028   "SECURE_DELETE",
13029 #endif
13030 #ifdef SQLITE_SMALL_STACK
13031   "SMALL_STACK",
13032 #endif
13033 #ifdef SQLITE_SOUNDEX
13034   "SOUNDEX",
13035 #endif
13036 #ifdef SQLITE_TCL
13037   "TCL",
13038 #endif
13039 #ifdef SQLITE_TEMP_STORE
13040   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13041 #endif
13042 #ifdef SQLITE_TEST
13043   "TEST",
13044 #endif
13045 #ifdef SQLITE_THREADSAFE
13046   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13047 #endif
13048 #ifdef SQLITE_USE_ALLOCA
13049   "USE_ALLOCA",
13050 #endif
13051 #ifdef SQLITE_ZERO_MALLOC
13052   "ZERO_MALLOC"
13053 #endif
13054 };
13055 
13056 /*
13057 ** Given the name of a compile-time option, return true if that option
13058 ** was used and false if not.
13059 **
13060 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13061 ** is not required for a match.
13062 */
13063 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13064   int i, n;
13065   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13066   n = sqlite3Strlen30(zOptName);
13067 
13068   /* Since ArraySize(azCompileOpt) is normally in single digits, a
13069   ** linear search is adequate.  No need for a binary search. */
13070   for(i=0; i<ArraySize(azCompileOpt); i++){
13071     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
13072        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
13073   }
13074   return 0;
13075 }
13076 
13077 /*
13078 ** Return the N-th compile-time option string.  If N is out of range,
13079 ** return a NULL pointer.
13080 */
13081 SQLITE_API const char *sqlite3_compileoption_get(int N){
13082   if( N>=0 && N<ArraySize(azCompileOpt) ){
13083     return azCompileOpt[N];
13084   }
13085   return 0;
13086 }
13087 
13088 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13089 
13090 /************** End of ctime.c ***********************************************/
13091 /************** Begin file status.c ******************************************/
13092 /*
13093 ** 2008 June 18
13094 **
13095 ** The author disclaims copyright to this source code.  In place of
13096 ** a legal notice, here is a blessing:
13097 **
13098 **    May you do good and not evil.
13099 **    May you find forgiveness for yourself and forgive others.
13100 **    May you share freely, never taking more than you give.
13101 **
13102 *************************************************************************
13103 **
13104 ** This module implements the sqlite3_status() interface and related
13105 ** functionality.
13106 */
13107 /************** Include vdbeInt.h in the middle of status.c ******************/
13108 /************** Begin file vdbeInt.h *****************************************/
13109 /*
13110 ** 2003 September 6
13111 **
13112 ** The author disclaims copyright to this source code.  In place of
13113 ** a legal notice, here is a blessing:
13114 **
13115 **    May you do good and not evil.
13116 **    May you find forgiveness for yourself and forgive others.
13117 **    May you share freely, never taking more than you give.
13118 **
13119 *************************************************************************
13120 ** This is the header file for information that is private to the
13121 ** VDBE.  This information used to all be at the top of the single
13122 ** source code file "vdbe.c".  When that file became too big (over
13123 ** 6000 lines long) it was split up into several smaller files and
13124 ** this header information was factored out.
13125 */
13126 #ifndef _VDBEINT_H_
13127 #define _VDBEINT_H_
13128 
13129 /*
13130 ** SQL is translated into a sequence of instructions to be
13131 ** executed by a virtual machine.  Each instruction is an instance
13132 ** of the following structure.
13133 */
13134 typedef struct VdbeOp Op;
13135 
13136 /*
13137 ** Boolean values
13138 */
13139 typedef unsigned char Bool;
13140 
13141 /* Opaque type used by code in vdbesort.c */
13142 typedef struct VdbeSorter VdbeSorter;
13143 
13144 /* Opaque type used by the explainer */
13145 typedef struct Explain Explain;
13146 
13147 /*
13148 ** A cursor is a pointer into a single BTree within a database file.
13149 ** The cursor can seek to a BTree entry with a particular key, or
13150 ** loop over all entries of the Btree.  You can also insert new BTree
13151 ** entries or retrieve the key or data from the entry that the cursor
13152 ** is currently pointing to.
13153 **
13154 ** Every cursor that the virtual machine has open is represented by an
13155 ** instance of the following structure.
13156 */
13157 struct VdbeCursor {
13158   BtCursor *pCursor;    /* The cursor structure of the backend */
13159   Btree *pBt;           /* Separate file holding temporary table */
13160   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13161   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
13162   int pseudoTableReg;   /* Register holding pseudotable content. */
13163   int nField;           /* Number of fields in the header */
13164   Bool zeroed;          /* True if zeroed out and ready for reuse */
13165   Bool rowidIsValid;    /* True if lastRowid is valid */
13166   Bool atFirst;         /* True if pointing to first entry */
13167   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
13168   Bool nullRow;         /* True if pointing to a row with no data */
13169   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
13170   Bool isTable;         /* True if a table requiring integer keys */
13171   Bool isIndex;         /* True if an index containing keys only - no data */
13172   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
13173   Bool isSorter;        /* True if a new-style sorter */
13174   Bool multiPseudo;     /* Multi-register pseudo-cursor */
13175   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13176   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
13177   i64 seqCount;         /* Sequence counter */
13178   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13179   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
13180   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13181 
13182   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
13183   ** OP_IsUnique opcode on this cursor. */
13184   int seekResult;
13185 
13186   /* Cached information about the header for the data record that the
13187   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13188   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13189   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13190   ** the cache is out of date.
13191   **
13192   ** aRow might point to (ephemeral) data for the current row, or it might
13193   ** be NULL.
13194   */
13195   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13196   int payloadSize;      /* Total number of bytes in the record */
13197   u32 *aType;           /* Type values for all entries in the record */
13198   u32 *aOffset;         /* Cached offsets to the start of each columns data */
13199   u8 *aRow;             /* Data for the current row, if all on one page */
13200 };
13201 typedef struct VdbeCursor VdbeCursor;
13202 
13203 /*
13204 ** When a sub-program is executed (OP_Program), a structure of this type
13205 ** is allocated to store the current value of the program counter, as
13206 ** well as the current memory cell array and various other frame specific
13207 ** values stored in the Vdbe struct. When the sub-program is finished,
13208 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13209 ** restoring the state of the VM to as it was before the sub-program
13210 ** began executing.
13211 **
13212 ** The memory for a VdbeFrame object is allocated and managed by a memory
13213 ** cell in the parent (calling) frame. When the memory cell is deleted or
13214 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13215 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13216 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13217 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13218 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13219 ** child frame are released.
13220 **
13221 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13222 ** set to NULL if the currently executing frame is the main program.
13223 */
13224 typedef struct VdbeFrame VdbeFrame;
13225 struct VdbeFrame {
13226   Vdbe *v;                /* VM this frame belongs to */
13227   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13228   Op *aOp;                /* Program instructions for parent frame */
13229   Mem *aMem;              /* Array of memory cells for parent frame */
13230   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13231   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13232   void *token;            /* Copy of SubProgram.token */
13233   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13234   int nCursor;            /* Number of entries in apCsr */
13235   int pc;                 /* Program Counter in parent (calling) frame */
13236   int nOp;                /* Size of aOp array */
13237   int nMem;               /* Number of entries in aMem */
13238   int nOnceFlag;          /* Number of entries in aOnceFlag */
13239   int nChildMem;          /* Number of memory cells for child frame */
13240   int nChildCsr;          /* Number of cursors for child frame */
13241   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13242 };
13243 
13244 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13245 
13246 /*
13247 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13248 */
13249 #define CACHE_STALE 0
13250 
13251 /*
13252 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13253 ** structures. Each Mem struct may cache multiple representations (string,
13254 ** integer etc.) of the same value.
13255 */
13256 struct Mem {
13257   sqlite3 *db;        /* The associated database connection */
13258   char *z;            /* String or BLOB value */
13259   double r;           /* Real value */
13260   union {
13261     i64 i;              /* Integer value used when MEM_Int is set in flags */
13262     int nZero;          /* Used when bit MEM_Zero is set in flags */
13263     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13264     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13265     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13266   } u;
13267   int n;              /* Number of characters in string value, excluding '\0' */
13268   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13269   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13270   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13271 #ifdef SQLITE_DEBUG
13272   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13273   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13274 #endif
13275   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13276   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13277 };
13278 
13279 /* One or more of the following flags are set to indicate the validOK
13280 ** representations of the value stored in the Mem struct.
13281 **
13282 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13283 ** No other flags may be set in this case.
13284 **
13285 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13286 ** Usually this is encoded in the same unicode encoding as the main
13287 ** database (see below for exceptions). If the MEM_Term flag is also
13288 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
13289 ** flags may coexist with the MEM_Str flag.
13290 */
13291 #define MEM_Null      0x0001   /* Value is NULL */
13292 #define MEM_Str       0x0002   /* Value is a string */
13293 #define MEM_Int       0x0004   /* Value is an integer */
13294 #define MEM_Real      0x0008   /* Value is a real number */
13295 #define MEM_Blob      0x0010   /* Value is a BLOB */
13296 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13297 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13298 #define MEM_Invalid   0x0080   /* Value is undefined */
13299 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
13300 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
13301 
13302 
13303 /* Whenever Mem contains a valid string or blob representation, one of
13304 ** the following flags must be set to determine the memory management
13305 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13306 ** string is \000 or \u0000 terminated
13307 */
13308 #define MEM_Term      0x0200   /* String rep is nul terminated */
13309 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13310 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13311 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13312 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13313 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13314 #ifdef SQLITE_OMIT_INCRBLOB
13315   #undef MEM_Zero
13316   #define MEM_Zero 0x0000
13317 #endif
13318 
13319 /*
13320 ** Clear any existing type flags from a Mem and replace them with f
13321 */
13322 #define MemSetTypeFlag(p, f) \
13323    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13324 
13325 /*
13326 ** Return true if a memory cell is not marked as invalid.  This macro
13327 ** is for use inside assert() statements only.
13328 */
13329 #ifdef SQLITE_DEBUG
13330 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13331 #endif
13332 
13333 
13334 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13335 ** additional information about auxiliary information bound to arguments
13336 ** of the function.  This is used to implement the sqlite3_get_auxdata()
13337 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13338 ** that can be associated with a constant argument to a function.  This
13339 ** allows functions such as "regexp" to compile their constant regular
13340 ** expression argument once and reused the compiled code for multiple
13341 ** invocations.
13342 */
13343 struct VdbeFunc {
13344   FuncDef *pFunc;               /* The definition of the function */
13345   int nAux;                     /* Number of entries allocated for apAux[] */
13346   struct AuxData {
13347     void *pAux;                   /* Aux data for the i-th argument */
13348     void (*xDelete)(void *);      /* Destructor for the aux data */
13349   } apAux[1];                   /* One slot for each function argument */
13350 };
13351 
13352 /*
13353 ** The "context" argument for a installable function.  A pointer to an
13354 ** instance of this structure is the first argument to the routines used
13355 ** implement the SQL functions.
13356 **
13357 ** There is a typedef for this structure in sqlite.h.  So all routines,
13358 ** even the public interface to SQLite, can use a pointer to this structure.
13359 ** But this file is the only place where the internal details of this
13360 ** structure are known.
13361 **
13362 ** This structure is defined inside of vdbeInt.h because it uses substructures
13363 ** (Mem) which are only defined there.
13364 */
13365 struct sqlite3_context {
13366   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13367   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13368   Mem s;                /* The return value is stored here */
13369   Mem *pMem;            /* Memory cell used to store aggregate context */
13370   CollSeq *pColl;       /* Collating sequence */
13371   int isError;          /* Error code returned by the function. */
13372   int skipFlag;         /* Skip skip accumulator loading if true */
13373 };
13374 
13375 /*
13376 ** An Explain object accumulates indented output which is helpful
13377 ** in describing recursive data structures.
13378 */
13379 struct Explain {
13380   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13381   StrAccum str;      /* The string being accumulated */
13382   int nIndent;       /* Number of elements in aIndent */
13383   u16 aIndent[100];  /* Levels of indentation */
13384   char zBase[100];   /* Initial space */
13385 };
13386 
13387 /* A bitfield type for use inside of structures.  Always follow with :N where
13388 ** N is the number of bits.
13389 */
13390 typedef unsigned bft;  /* Bit Field Type */
13391 
13392 /*
13393 ** An instance of the virtual machine.  This structure contains the complete
13394 ** state of the virtual machine.
13395 **
13396 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13397 ** is really a pointer to an instance of this structure.
13398 **
13399 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13400 ** any virtual table method invocations made by the vdbe program. It is
13401 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13402 ** variable is used for two purposes: to allow xDestroy methods to execute
13403 ** "DROP TABLE" statements and to prevent some nasty side effects of
13404 ** malloc failure when SQLite is invoked recursively by a virtual table
13405 ** method function.
13406 */
13407 struct Vdbe {
13408   sqlite3 *db;            /* The database connection that owns this statement */
13409   Op *aOp;                /* Space to hold the virtual machine's program */
13410   Mem *aMem;              /* The memory locations */
13411   Mem **apArg;            /* Arguments to currently executing user function */
13412   Mem *aColName;          /* Column names to return */
13413   Mem *pResultSet;        /* Pointer to an array of results */
13414   int nMem;               /* Number of memory locations currently allocated */
13415   int nOp;                /* Number of instructions in the program */
13416   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13417   int nLabel;             /* Number of labels used */
13418   int *aLabel;            /* Space to hold the labels */
13419   u16 nResColumn;         /* Number of columns in one row of the result set */
13420   int nCursor;            /* Number of slots in apCsr[] */
13421   u32 magic;              /* Magic number for sanity checking */
13422   char *zErrMsg;          /* Error message written here */
13423   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13424   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13425   Mem *aVar;              /* Values for the OP_Variable opcode. */
13426   char **azVar;           /* Name of variables */
13427   ynVar nVar;             /* Number of entries in aVar[] */
13428   ynVar nzVar;            /* Number of entries in azVar[] */
13429   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13430   int pc;                 /* The program counter */
13431   int rc;                 /* Value to return */
13432   u8 errorAction;         /* Recovery action to do in case of an error */
13433   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13434   bft explain:2;          /* True if EXPLAIN present on SQL command */
13435   bft inVtabMethod:2;     /* See comments above */
13436   bft changeCntOn:1;      /* True to update the change-counter */
13437   bft expired:1;          /* True if the VM needs to be recompiled */
13438   bft runOnlyOnce:1;      /* Automatically expire on reset */
13439   bft usesStmtJournal:1;  /* True if uses a statement journal */
13440   bft readOnly:1;         /* True for read-only statements */
13441   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
13442   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
13443   int nChange;            /* Number of db changes made since last reset */
13444   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13445   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13446   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13447   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13448 #ifndef SQLITE_OMIT_TRACE
13449   i64 startTime;          /* Time when query started - used for profiling */
13450 #endif
13451   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13452   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13453   char *zSql;             /* Text of the SQL statement that generated this */
13454   void *pFree;            /* Free this when deleting the vdbe */
13455 #ifdef SQLITE_DEBUG
13456   FILE *trace;            /* Write an execution trace here, if not NULL */
13457 #endif
13458 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13459   Explain *pExplain;      /* The explainer */
13460   char *zExplain;         /* Explanation of data structures */
13461 #endif
13462   VdbeFrame *pFrame;      /* Parent frame */
13463   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13464   int nFrame;             /* Number of frames in pFrame list */
13465   u32 expmask;            /* Binding to these vars invalidates VM */
13466   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13467   int nOnceFlag;          /* Size of array aOnceFlag[] */
13468   u8 *aOnceFlag;          /* Flags for OP_Once */
13469 };
13470 
13471 /*
13472 ** The following are allowed values for Vdbe.magic
13473 */
13474 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13475 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13476 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13477 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13478 
13479 /*
13480 ** Function prototypes
13481 */
13482 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13483 void sqliteVdbePopStack(Vdbe*,int);
13484 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13485 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13486 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13487 #endif
13488 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13489 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13490 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13491 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13492 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13493 
13494 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13495 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13496 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13497 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13498 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13499 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13500 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13501 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13502 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13503 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13504 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13505 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13506 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13507 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13508 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13509 #ifdef SQLITE_OMIT_FLOATING_POINT
13510 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13511 #else
13512 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13513 #endif
13514 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13515 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13516 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13517 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13518 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13519 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13520 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13521 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13522 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13523 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13524 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13525 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13526 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13527 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13528 #define VdbeMemRelease(X)  \
13529   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13530     sqlite3VdbeMemReleaseExternal(X);
13531 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13532 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13533 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13534 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13535 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13536 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13537 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13538 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13539 
13540 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13541 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13542 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13543 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13544 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13545 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13546 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13547 
13548 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13549 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13550 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13551 #else
13552 # define sqlite3VdbeEnter(X)
13553 # define sqlite3VdbeLeave(X)
13554 #endif
13555 
13556 #ifdef SQLITE_DEBUG
13557 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13558 #endif
13559 
13560 #ifndef SQLITE_OMIT_FOREIGN_KEY
13561 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13562 #else
13563 # define sqlite3VdbeCheckFk(p,i) 0
13564 #endif
13565 
13566 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13567 #ifdef SQLITE_DEBUG
13568 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13569 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13570 #endif
13571 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13572 
13573 #ifndef SQLITE_OMIT_INCRBLOB
13574 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13575   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13576 #else
13577   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13578   #define ExpandBlob(P) SQLITE_OK
13579 #endif
13580 
13581 #endif /* !defined(_VDBEINT_H_) */
13582 
13583 /************** End of vdbeInt.h *********************************************/
13584 /************** Continuing where we left off in status.c *********************/
13585 
13586 /*
13587 ** Variables in which to record status information.
13588 */
13589 typedef struct sqlite3StatType sqlite3StatType;
13590 static SQLITE_WSD struct sqlite3StatType {
13591   int nowValue[10];         /* Current value */
13592   int mxValue[10];          /* Maximum value */
13593 } sqlite3Stat = { {0,}, {0,} };
13594 
13595 
13596 /* The "wsdStat" macro will resolve to the status information
13597 ** state vector.  If writable static data is unsupported on the target,
13598 ** we have to locate the state vector at run-time.  In the more common
13599 ** case where writable static data is supported, wsdStat can refer directly
13600 ** to the "sqlite3Stat" state vector declared above.
13601 */
13602 #ifdef SQLITE_OMIT_WSD
13603 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13604 # define wsdStat x[0]
13605 #else
13606 # define wsdStatInit
13607 # define wsdStat sqlite3Stat
13608 #endif
13609 
13610 /*
13611 ** Return the current value of a status parameter.
13612 */
13613 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13614   wsdStatInit;
13615   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13616   return wsdStat.nowValue[op];
13617 }
13618 
13619 /*
13620 ** Add N to the value of a status record.  It is assumed that the
13621 ** caller holds appropriate locks.
13622 */
13623 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13624   wsdStatInit;
13625   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13626   wsdStat.nowValue[op] += N;
13627   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13628     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13629   }
13630 }
13631 
13632 /*
13633 ** Set the value of a status to X.
13634 */
13635 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13636   wsdStatInit;
13637   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13638   wsdStat.nowValue[op] = X;
13639   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13640     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13641   }
13642 }
13643 
13644 /*
13645 ** Query status information.
13646 **
13647 ** This implementation assumes that reading or writing an aligned
13648 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13649 ** then this routine is not threadsafe.
13650 */
13651 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13652   wsdStatInit;
13653   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13654     return SQLITE_MISUSE_BKPT;
13655   }
13656   *pCurrent = wsdStat.nowValue[op];
13657   *pHighwater = wsdStat.mxValue[op];
13658   if( resetFlag ){
13659     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13660   }
13661   return SQLITE_OK;
13662 }
13663 
13664 /*
13665 ** Query status information for a single database connection
13666 */
13667 SQLITE_API int sqlite3_db_status(
13668   sqlite3 *db,          /* The database connection whose status is desired */
13669   int op,               /* Status verb */
13670   int *pCurrent,        /* Write current value here */
13671   int *pHighwater,      /* Write high-water mark here */
13672   int resetFlag         /* Reset high-water mark if true */
13673 ){
13674   int rc = SQLITE_OK;   /* Return code */
13675   sqlite3_mutex_enter(db->mutex);
13676   switch( op ){
13677     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13678       *pCurrent = db->lookaside.nOut;
13679       *pHighwater = db->lookaside.mxOut;
13680       if( resetFlag ){
13681         db->lookaside.mxOut = db->lookaside.nOut;
13682       }
13683       break;
13684     }
13685 
13686     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13687     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13688     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13689       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13690       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13691       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13692       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13693       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13694       *pCurrent = 0;
13695       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13696       if( resetFlag ){
13697         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13698       }
13699       break;
13700     }
13701 
13702     /*
13703     ** Return an approximation for the amount of memory currently used
13704     ** by all pagers associated with the given database connection.  The
13705     ** highwater mark is meaningless and is returned as zero.
13706     */
13707     case SQLITE_DBSTATUS_CACHE_USED: {
13708       int totalUsed = 0;
13709       int i;
13710       sqlite3BtreeEnterAll(db);
13711       for(i=0; i<db->nDb; i++){
13712         Btree *pBt = db->aDb[i].pBt;
13713         if( pBt ){
13714           Pager *pPager = sqlite3BtreePager(pBt);
13715           totalUsed += sqlite3PagerMemUsed(pPager);
13716         }
13717       }
13718       sqlite3BtreeLeaveAll(db);
13719       *pCurrent = totalUsed;
13720       *pHighwater = 0;
13721       break;
13722     }
13723 
13724     /*
13725     ** *pCurrent gets an accurate estimate of the amount of memory used
13726     ** to store the schema for all databases (main, temp, and any ATTACHed
13727     ** databases.  *pHighwater is set to zero.
13728     */
13729     case SQLITE_DBSTATUS_SCHEMA_USED: {
13730       int i;                      /* Used to iterate through schemas */
13731       int nByte = 0;              /* Used to accumulate return value */
13732 
13733       sqlite3BtreeEnterAll(db);
13734       db->pnBytesFreed = &nByte;
13735       for(i=0; i<db->nDb; i++){
13736         Schema *pSchema = db->aDb[i].pSchema;
13737         if( ALWAYS(pSchema!=0) ){
13738           HashElem *p;
13739 
13740           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13741               pSchema->tblHash.count
13742             + pSchema->trigHash.count
13743             + pSchema->idxHash.count
13744             + pSchema->fkeyHash.count
13745           );
13746           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13747           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13748           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13749           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13750 
13751           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13752             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13753           }
13754           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13755             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13756           }
13757         }
13758       }
13759       db->pnBytesFreed = 0;
13760       sqlite3BtreeLeaveAll(db);
13761 
13762       *pHighwater = 0;
13763       *pCurrent = nByte;
13764       break;
13765     }
13766 
13767     /*
13768     ** *pCurrent gets an accurate estimate of the amount of memory used
13769     ** to store all prepared statements.
13770     ** *pHighwater is set to zero.
13771     */
13772     case SQLITE_DBSTATUS_STMT_USED: {
13773       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13774       int nByte = 0;              /* Used to accumulate return value */
13775 
13776       db->pnBytesFreed = &nByte;
13777       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13778         sqlite3VdbeClearObject(db, pVdbe);
13779         sqlite3DbFree(db, pVdbe);
13780       }
13781       db->pnBytesFreed = 0;
13782 
13783       *pHighwater = 0;
13784       *pCurrent = nByte;
13785 
13786       break;
13787     }
13788 
13789     /*
13790     ** Set *pCurrent to the total cache hits or misses encountered by all
13791     ** pagers the database handle is connected to. *pHighwater is always set
13792     ** to zero.
13793     */
13794     case SQLITE_DBSTATUS_CACHE_HIT:
13795     case SQLITE_DBSTATUS_CACHE_MISS:
13796     case SQLITE_DBSTATUS_CACHE_WRITE:{
13797       int i;
13798       int nRet = 0;
13799       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13800       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13801 
13802       for(i=0; i<db->nDb; i++){
13803         if( db->aDb[i].pBt ){
13804           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13805           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13806         }
13807       }
13808       *pHighwater = 0;
13809       *pCurrent = nRet;
13810       break;
13811     }
13812 
13813     default: {
13814       rc = SQLITE_ERROR;
13815     }
13816   }
13817   sqlite3_mutex_leave(db->mutex);
13818   return rc;
13819 }
13820 
13821 /************** End of status.c **********************************************/
13822 /************** Begin file date.c ********************************************/
13823 /*
13824 ** 2003 October 31
13825 **
13826 ** The author disclaims copyright to this source code.  In place of
13827 ** a legal notice, here is a blessing:
13828 **
13829 **    May you do good and not evil.
13830 **    May you find forgiveness for yourself and forgive others.
13831 **    May you share freely, never taking more than you give.
13832 **
13833 *************************************************************************
13834 ** This file contains the C functions that implement date and time
13835 ** functions for SQLite.
13836 **
13837 ** There is only one exported symbol in this file - the function
13838 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13839 ** All other code has file scope.
13840 **
13841 ** SQLite processes all times and dates as Julian Day numbers.  The
13842 ** dates and times are stored as the number of days since noon
13843 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13844 ** calendar system.
13845 **
13846 ** 1970-01-01 00:00:00 is JD 2440587.5
13847 ** 2000-01-01 00:00:00 is JD 2451544.5
13848 **
13849 ** This implemention requires years to be expressed as a 4-digit number
13850 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13851 ** be represented, even though julian day numbers allow a much wider
13852 ** range of dates.
13853 **
13854 ** The Gregorian calendar system is used for all dates and times,
13855 ** even those that predate the Gregorian calendar.  Historians usually
13856 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13857 ** dates afterwards, depending on locale.  Beware of this difference.
13858 **
13859 ** The conversion algorithms are implemented based on descriptions
13860 ** in the following text:
13861 **
13862 **      Jean Meeus
13863 **      Astronomical Algorithms, 2nd Edition, 1998
13864 **      ISBM 0-943396-61-1
13865 **      Willmann-Bell, Inc
13866 **      Richmond, Virginia (USA)
13867 */
13868 /* #include <stdlib.h> */
13869 /* #include <assert.h> */
13870 #include <time.h>
13871 
13872 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13873 
13874 
13875 /*
13876 ** A structure for holding a single date and time.
13877 */
13878 typedef struct DateTime DateTime;
13879 struct DateTime {
13880   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13881   int Y, M, D;       /* Year, month, and day */
13882   int h, m;          /* Hour and minutes */
13883   int tz;            /* Timezone offset in minutes */
13884   double s;          /* Seconds */
13885   char validYMD;     /* True (1) if Y,M,D are valid */
13886   char validHMS;     /* True (1) if h,m,s are valid */
13887   char validJD;      /* True (1) if iJD is valid */
13888   char validTZ;      /* True (1) if tz is valid */
13889 };
13890 
13891 
13892 /*
13893 ** Convert zDate into one or more integers.  Additional arguments
13894 ** come in groups of 5 as follows:
13895 **
13896 **       N       number of digits in the integer
13897 **       min     minimum allowed value of the integer
13898 **       max     maximum allowed value of the integer
13899 **       nextC   first character after the integer
13900 **       pVal    where to write the integers value.
13901 **
13902 ** Conversions continue until one with nextC==0 is encountered.
13903 ** The function returns the number of successful conversions.
13904 */
13905 static int getDigits(const char *zDate, ...){
13906   va_list ap;
13907   int val;
13908   int N;
13909   int min;
13910   int max;
13911   int nextC;
13912   int *pVal;
13913   int cnt = 0;
13914   va_start(ap, zDate);
13915   do{
13916     N = va_arg(ap, int);
13917     min = va_arg(ap, int);
13918     max = va_arg(ap, int);
13919     nextC = va_arg(ap, int);
13920     pVal = va_arg(ap, int*);
13921     val = 0;
13922     while( N-- ){
13923       if( !sqlite3Isdigit(*zDate) ){
13924         goto end_getDigits;
13925       }
13926       val = val*10 + *zDate - '0';
13927       zDate++;
13928     }
13929     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13930       goto end_getDigits;
13931     }
13932     *pVal = val;
13933     zDate++;
13934     cnt++;
13935   }while( nextC );
13936 end_getDigits:
13937   va_end(ap);
13938   return cnt;
13939 }
13940 
13941 /*
13942 ** Parse a timezone extension on the end of a date-time.
13943 ** The extension is of the form:
13944 **
13945 **        (+/-)HH:MM
13946 **
13947 ** Or the "zulu" notation:
13948 **
13949 **        Z
13950 **
13951 ** If the parse is successful, write the number of minutes
13952 ** of change in p->tz and return 0.  If a parser error occurs,
13953 ** return non-zero.
13954 **
13955 ** A missing specifier is not considered an error.
13956 */
13957 static int parseTimezone(const char *zDate, DateTime *p){
13958   int sgn = 0;
13959   int nHr, nMn;
13960   int c;
13961   while( sqlite3Isspace(*zDate) ){ zDate++; }
13962   p->tz = 0;
13963   c = *zDate;
13964   if( c=='-' ){
13965     sgn = -1;
13966   }else if( c=='+' ){
13967     sgn = +1;
13968   }else if( c=='Z' || c=='z' ){
13969     zDate++;
13970     goto zulu_time;
13971   }else{
13972     return c!=0;
13973   }
13974   zDate++;
13975   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13976     return 1;
13977   }
13978   zDate += 5;
13979   p->tz = sgn*(nMn + nHr*60);
13980 zulu_time:
13981   while( sqlite3Isspace(*zDate) ){ zDate++; }
13982   return *zDate!=0;
13983 }
13984 
13985 /*
13986 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13987 ** The HH, MM, and SS must each be exactly 2 digits.  The
13988 ** fractional seconds FFFF can be one or more digits.
13989 **
13990 ** Return 1 if there is a parsing error and 0 on success.
13991 */
13992 static int parseHhMmSs(const char *zDate, DateTime *p){
13993   int h, m, s;
13994   double ms = 0.0;
13995   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13996     return 1;
13997   }
13998   zDate += 5;
13999   if( *zDate==':' ){
14000     zDate++;
14001     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14002       return 1;
14003     }
14004     zDate += 2;
14005     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14006       double rScale = 1.0;
14007       zDate++;
14008       while( sqlite3Isdigit(*zDate) ){
14009         ms = ms*10.0 + *zDate - '0';
14010         rScale *= 10.0;
14011         zDate++;
14012       }
14013       ms /= rScale;
14014     }
14015   }else{
14016     s = 0;
14017   }
14018   p->validJD = 0;
14019   p->validHMS = 1;
14020   p->h = h;
14021   p->m = m;
14022   p->s = s + ms;
14023   if( parseTimezone(zDate, p) ) return 1;
14024   p->validTZ = (p->tz!=0)?1:0;
14025   return 0;
14026 }
14027 
14028 /*
14029 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14030 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14031 **
14032 ** Reference:  Meeus page 61
14033 */
14034 static void computeJD(DateTime *p){
14035   int Y, M, D, A, B, X1, X2;
14036 
14037   if( p->validJD ) return;
14038   if( p->validYMD ){
14039     Y = p->Y;
14040     M = p->M;
14041     D = p->D;
14042   }else{
14043     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14044     M = 1;
14045     D = 1;
14046   }
14047   if( M<=2 ){
14048     Y--;
14049     M += 12;
14050   }
14051   A = Y/100;
14052   B = 2 - A + (A/4);
14053   X1 = 36525*(Y+4716)/100;
14054   X2 = 306001*(M+1)/10000;
14055   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14056   p->validJD = 1;
14057   if( p->validHMS ){
14058     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14059     if( p->validTZ ){
14060       p->iJD -= p->tz*60000;
14061       p->validYMD = 0;
14062       p->validHMS = 0;
14063       p->validTZ = 0;
14064     }
14065   }
14066 }
14067 
14068 /*
14069 ** Parse dates of the form
14070 **
14071 **     YYYY-MM-DD HH:MM:SS.FFF
14072 **     YYYY-MM-DD HH:MM:SS
14073 **     YYYY-MM-DD HH:MM
14074 **     YYYY-MM-DD
14075 **
14076 ** Write the result into the DateTime structure and return 0
14077 ** on success and 1 if the input string is not a well-formed
14078 ** date.
14079 */
14080 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14081   int Y, M, D, neg;
14082 
14083   if( zDate[0]=='-' ){
14084     zDate++;
14085     neg = 1;
14086   }else{
14087     neg = 0;
14088   }
14089   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14090     return 1;
14091   }
14092   zDate += 10;
14093   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14094   if( parseHhMmSs(zDate, p)==0 ){
14095     /* We got the time */
14096   }else if( *zDate==0 ){
14097     p->validHMS = 0;
14098   }else{
14099     return 1;
14100   }
14101   p->validJD = 0;
14102   p->validYMD = 1;
14103   p->Y = neg ? -Y : Y;
14104   p->M = M;
14105   p->D = D;
14106   if( p->validTZ ){
14107     computeJD(p);
14108   }
14109   return 0;
14110 }
14111 
14112 /*
14113 ** Set the time to the current time reported by the VFS.
14114 **
14115 ** Return the number of errors.
14116 */
14117 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14118   sqlite3 *db = sqlite3_context_db_handle(context);
14119   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
14120     p->validJD = 1;
14121     return 0;
14122   }else{
14123     return 1;
14124   }
14125 }
14126 
14127 /*
14128 ** Attempt to parse the given string into a Julian Day Number.  Return
14129 ** the number of errors.
14130 **
14131 ** The following are acceptable forms for the input string:
14132 **
14133 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14134 **      DDDD.DD
14135 **      now
14136 **
14137 ** In the first form, the +/-HH:MM is always optional.  The fractional
14138 ** seconds extension (the ".FFF") is optional.  The seconds portion
14139 ** (":SS.FFF") is option.  The year and date can be omitted as long
14140 ** as there is a time string.  The time string can be omitted as long
14141 ** as there is a year and date.
14142 */
14143 static int parseDateOrTime(
14144   sqlite3_context *context,
14145   const char *zDate,
14146   DateTime *p
14147 ){
14148   double r;
14149   if( parseYyyyMmDd(zDate,p)==0 ){
14150     return 0;
14151   }else if( parseHhMmSs(zDate, p)==0 ){
14152     return 0;
14153   }else if( sqlite3StrICmp(zDate,"now")==0){
14154     return setDateTimeToCurrent(context, p);
14155   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14156     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14157     p->validJD = 1;
14158     return 0;
14159   }
14160   return 1;
14161 }
14162 
14163 /*
14164 ** Compute the Year, Month, and Day from the julian day number.
14165 */
14166 static void computeYMD(DateTime *p){
14167   int Z, A, B, C, D, E, X1;
14168   if( p->validYMD ) return;
14169   if( !p->validJD ){
14170     p->Y = 2000;
14171     p->M = 1;
14172     p->D = 1;
14173   }else{
14174     Z = (int)((p->iJD + 43200000)/86400000);
14175     A = (int)((Z - 1867216.25)/36524.25);
14176     A = Z + 1 + A - (A/4);
14177     B = A + 1524;
14178     C = (int)((B - 122.1)/365.25);
14179     D = (36525*C)/100;
14180     E = (int)((B-D)/30.6001);
14181     X1 = (int)(30.6001*E);
14182     p->D = B - D - X1;
14183     p->M = E<14 ? E-1 : E-13;
14184     p->Y = p->M>2 ? C - 4716 : C - 4715;
14185   }
14186   p->validYMD = 1;
14187 }
14188 
14189 /*
14190 ** Compute the Hour, Minute, and Seconds from the julian day number.
14191 */
14192 static void computeHMS(DateTime *p){
14193   int s;
14194   if( p->validHMS ) return;
14195   computeJD(p);
14196   s = (int)((p->iJD + 43200000) % 86400000);
14197   p->s = s/1000.0;
14198   s = (int)p->s;
14199   p->s -= s;
14200   p->h = s/3600;
14201   s -= p->h*3600;
14202   p->m = s/60;
14203   p->s += s - p->m*60;
14204   p->validHMS = 1;
14205 }
14206 
14207 /*
14208 ** Compute both YMD and HMS
14209 */
14210 static void computeYMD_HMS(DateTime *p){
14211   computeYMD(p);
14212   computeHMS(p);
14213 }
14214 
14215 /*
14216 ** Clear the YMD and HMS and the TZ
14217 */
14218 static void clearYMD_HMS_TZ(DateTime *p){
14219   p->validYMD = 0;
14220   p->validHMS = 0;
14221   p->validTZ = 0;
14222 }
14223 
14224 /*
14225 ** On recent Windows platforms, the localtime_s() function is available
14226 ** as part of the "Secure CRT". It is essentially equivalent to
14227 ** localtime_r() available under most POSIX platforms, except that the
14228 ** order of the parameters is reversed.
14229 **
14230 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14231 **
14232 ** If the user has not indicated to use localtime_r() or localtime_s()
14233 ** already, check for an MSVC build environment that provides
14234 ** localtime_s().
14235 */
14236 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14237      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14238 #define HAVE_LOCALTIME_S 1
14239 #endif
14240 
14241 #ifndef SQLITE_OMIT_LOCALTIME
14242 /*
14243 ** The following routine implements the rough equivalent of localtime_r()
14244 ** using whatever operating-system specific localtime facility that
14245 ** is available.  This routine returns 0 on success and
14246 ** non-zero on any kind of error.
14247 **
14248 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14249 ** routine will always fail.
14250 */
14251 static int osLocaltime(time_t *t, struct tm *pTm){
14252   int rc;
14253 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14254       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14255   struct tm *pX;
14256 #if SQLITE_THREADSAFE>0
14257   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14258 #endif
14259   sqlite3_mutex_enter(mutex);
14260   pX = localtime(t);
14261 #ifndef SQLITE_OMIT_BUILTIN_TEST
14262   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14263 #endif
14264   if( pX ) *pTm = *pX;
14265   sqlite3_mutex_leave(mutex);
14266   rc = pX==0;
14267 #else
14268 #ifndef SQLITE_OMIT_BUILTIN_TEST
14269   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14270 #endif
14271 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14272   rc = localtime_r(t, pTm)==0;
14273 #else
14274   rc = localtime_s(pTm, t);
14275 #endif /* HAVE_LOCALTIME_R */
14276 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14277   return rc;
14278 }
14279 #endif /* SQLITE_OMIT_LOCALTIME */
14280 
14281 
14282 #ifndef SQLITE_OMIT_LOCALTIME
14283 /*
14284 ** Compute the difference (in milliseconds) between localtime and UTC
14285 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14286 ** return this value and set *pRc to SQLITE_OK.
14287 **
14288 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14289 ** is undefined in this case.
14290 */
14291 static sqlite3_int64 localtimeOffset(
14292   DateTime *p,                    /* Date at which to calculate offset */
14293   sqlite3_context *pCtx,          /* Write error here if one occurs */
14294   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14295 ){
14296   DateTime x, y;
14297   time_t t;
14298   struct tm sLocal;
14299 
14300   /* Initialize the contents of sLocal to avoid a compiler warning. */
14301   memset(&sLocal, 0, sizeof(sLocal));
14302 
14303   x = *p;
14304   computeYMD_HMS(&x);
14305   if( x.Y<1971 || x.Y>=2038 ){
14306     x.Y = 2000;
14307     x.M = 1;
14308     x.D = 1;
14309     x.h = 0;
14310     x.m = 0;
14311     x.s = 0.0;
14312   } else {
14313     int s = (int)(x.s + 0.5);
14314     x.s = s;
14315   }
14316   x.tz = 0;
14317   x.validJD = 0;
14318   computeJD(&x);
14319   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14320   if( osLocaltime(&t, &sLocal) ){
14321     sqlite3_result_error(pCtx, "local time unavailable", -1);
14322     *pRc = SQLITE_ERROR;
14323     return 0;
14324   }
14325   y.Y = sLocal.tm_year + 1900;
14326   y.M = sLocal.tm_mon + 1;
14327   y.D = sLocal.tm_mday;
14328   y.h = sLocal.tm_hour;
14329   y.m = sLocal.tm_min;
14330   y.s = sLocal.tm_sec;
14331   y.validYMD = 1;
14332   y.validHMS = 1;
14333   y.validJD = 0;
14334   y.validTZ = 0;
14335   computeJD(&y);
14336   *pRc = SQLITE_OK;
14337   return y.iJD - x.iJD;
14338 }
14339 #endif /* SQLITE_OMIT_LOCALTIME */
14340 
14341 /*
14342 ** Process a modifier to a date-time stamp.  The modifiers are
14343 ** as follows:
14344 **
14345 **     NNN days
14346 **     NNN hours
14347 **     NNN minutes
14348 **     NNN.NNNN seconds
14349 **     NNN months
14350 **     NNN years
14351 **     start of month
14352 **     start of year
14353 **     start of week
14354 **     start of day
14355 **     weekday N
14356 **     unixepoch
14357 **     localtime
14358 **     utc
14359 **
14360 ** Return 0 on success and 1 if there is any kind of error. If the error
14361 ** is in a system call (i.e. localtime()), then an error message is written
14362 ** to context pCtx. If the error is an unrecognized modifier, no error is
14363 ** written to pCtx.
14364 */
14365 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14366   int rc = 1;
14367   int n;
14368   double r;
14369   char *z, zBuf[30];
14370   z = zBuf;
14371   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14372     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14373   }
14374   z[n] = 0;
14375   switch( z[0] ){
14376 #ifndef SQLITE_OMIT_LOCALTIME
14377     case 'l': {
14378       /*    localtime
14379       **
14380       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14381       ** show local time.
14382       */
14383       if( strcmp(z, "localtime")==0 ){
14384         computeJD(p);
14385         p->iJD += localtimeOffset(p, pCtx, &rc);
14386         clearYMD_HMS_TZ(p);
14387       }
14388       break;
14389     }
14390 #endif
14391     case 'u': {
14392       /*
14393       **    unixepoch
14394       **
14395       ** Treat the current value of p->iJD as the number of
14396       ** seconds since 1970.  Convert to a real julian day number.
14397       */
14398       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14399         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14400         clearYMD_HMS_TZ(p);
14401         rc = 0;
14402       }
14403 #ifndef SQLITE_OMIT_LOCALTIME
14404       else if( strcmp(z, "utc")==0 ){
14405         sqlite3_int64 c1;
14406         computeJD(p);
14407         c1 = localtimeOffset(p, pCtx, &rc);
14408         if( rc==SQLITE_OK ){
14409           p->iJD -= c1;
14410           clearYMD_HMS_TZ(p);
14411           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14412         }
14413       }
14414 #endif
14415       break;
14416     }
14417     case 'w': {
14418       /*
14419       **    weekday N
14420       **
14421       ** Move the date to the same time on the next occurrence of
14422       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14423       ** date is already on the appropriate weekday, this is a no-op.
14424       */
14425       if( strncmp(z, "weekday ", 8)==0
14426                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14427                && (n=(int)r)==r && n>=0 && r<7 ){
14428         sqlite3_int64 Z;
14429         computeYMD_HMS(p);
14430         p->validTZ = 0;
14431         p->validJD = 0;
14432         computeJD(p);
14433         Z = ((p->iJD + 129600000)/86400000) % 7;
14434         if( Z>n ) Z -= 7;
14435         p->iJD += (n - Z)*86400000;
14436         clearYMD_HMS_TZ(p);
14437         rc = 0;
14438       }
14439       break;
14440     }
14441     case 's': {
14442       /*
14443       **    start of TTTTT
14444       **
14445       ** Move the date backwards to the beginning of the current day,
14446       ** or month or year.
14447       */
14448       if( strncmp(z, "start of ", 9)!=0 ) break;
14449       z += 9;
14450       computeYMD(p);
14451       p->validHMS = 1;
14452       p->h = p->m = 0;
14453       p->s = 0.0;
14454       p->validTZ = 0;
14455       p->validJD = 0;
14456       if( strcmp(z,"month")==0 ){
14457         p->D = 1;
14458         rc = 0;
14459       }else if( strcmp(z,"year")==0 ){
14460         computeYMD(p);
14461         p->M = 1;
14462         p->D = 1;
14463         rc = 0;
14464       }else if( strcmp(z,"day")==0 ){
14465         rc = 0;
14466       }
14467       break;
14468     }
14469     case '+':
14470     case '-':
14471     case '0':
14472     case '1':
14473     case '2':
14474     case '3':
14475     case '4':
14476     case '5':
14477     case '6':
14478     case '7':
14479     case '8':
14480     case '9': {
14481       double rRounder;
14482       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14483       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14484         rc = 1;
14485         break;
14486       }
14487       if( z[n]==':' ){
14488         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14489         ** specified number of hours, minutes, seconds, and fractional seconds
14490         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14491         ** omitted.
14492         */
14493         const char *z2 = z;
14494         DateTime tx;
14495         sqlite3_int64 day;
14496         if( !sqlite3Isdigit(*z2) ) z2++;
14497         memset(&tx, 0, sizeof(tx));
14498         if( parseHhMmSs(z2, &tx) ) break;
14499         computeJD(&tx);
14500         tx.iJD -= 43200000;
14501         day = tx.iJD/86400000;
14502         tx.iJD -= day*86400000;
14503         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14504         computeJD(p);
14505         clearYMD_HMS_TZ(p);
14506         p->iJD += tx.iJD;
14507         rc = 0;
14508         break;
14509       }
14510       z += n;
14511       while( sqlite3Isspace(*z) ) z++;
14512       n = sqlite3Strlen30(z);
14513       if( n>10 || n<3 ) break;
14514       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14515       computeJD(p);
14516       rc = 0;
14517       rRounder = r<0 ? -0.5 : +0.5;
14518       if( n==3 && strcmp(z,"day")==0 ){
14519         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14520       }else if( n==4 && strcmp(z,"hour")==0 ){
14521         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14522       }else if( n==6 && strcmp(z,"minute")==0 ){
14523         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14524       }else if( n==6 && strcmp(z,"second")==0 ){
14525         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14526       }else if( n==5 && strcmp(z,"month")==0 ){
14527         int x, y;
14528         computeYMD_HMS(p);
14529         p->M += (int)r;
14530         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14531         p->Y += x;
14532         p->M -= x*12;
14533         p->validJD = 0;
14534         computeJD(p);
14535         y = (int)r;
14536         if( y!=r ){
14537           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14538         }
14539       }else if( n==4 && strcmp(z,"year")==0 ){
14540         int y = (int)r;
14541         computeYMD_HMS(p);
14542         p->Y += y;
14543         p->validJD = 0;
14544         computeJD(p);
14545         if( y!=r ){
14546           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14547         }
14548       }else{
14549         rc = 1;
14550       }
14551       clearYMD_HMS_TZ(p);
14552       break;
14553     }
14554     default: {
14555       break;
14556     }
14557   }
14558   return rc;
14559 }
14560 
14561 /*
14562 ** Process time function arguments.  argv[0] is a date-time stamp.
14563 ** argv[1] and following are modifiers.  Parse them all and write
14564 ** the resulting time into the DateTime structure p.  Return 0
14565 ** on success and 1 if there are any errors.
14566 **
14567 ** If there are zero parameters (if even argv[0] is undefined)
14568 ** then assume a default value of "now" for argv[0].
14569 */
14570 static int isDate(
14571   sqlite3_context *context,
14572   int argc,
14573   sqlite3_value **argv,
14574   DateTime *p
14575 ){
14576   int i;
14577   const unsigned char *z;
14578   int eType;
14579   memset(p, 0, sizeof(*p));
14580   if( argc==0 ){
14581     return setDateTimeToCurrent(context, p);
14582   }
14583   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14584                    || eType==SQLITE_INTEGER ){
14585     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14586     p->validJD = 1;
14587   }else{
14588     z = sqlite3_value_text(argv[0]);
14589     if( !z || parseDateOrTime(context, (char*)z, p) ){
14590       return 1;
14591     }
14592   }
14593   for(i=1; i<argc; i++){
14594     z = sqlite3_value_text(argv[i]);
14595     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14596   }
14597   return 0;
14598 }
14599 
14600 
14601 /*
14602 ** The following routines implement the various date and time functions
14603 ** of SQLite.
14604 */
14605 
14606 /*
14607 **    julianday( TIMESTRING, MOD, MOD, ...)
14608 **
14609 ** Return the julian day number of the date specified in the arguments
14610 */
14611 static void juliandayFunc(
14612   sqlite3_context *context,
14613   int argc,
14614   sqlite3_value **argv
14615 ){
14616   DateTime x;
14617   if( isDate(context, argc, argv, &x)==0 ){
14618     computeJD(&x);
14619     sqlite3_result_double(context, x.iJD/86400000.0);
14620   }
14621 }
14622 
14623 /*
14624 **    datetime( TIMESTRING, MOD, MOD, ...)
14625 **
14626 ** Return YYYY-MM-DD HH:MM:SS
14627 */
14628 static void datetimeFunc(
14629   sqlite3_context *context,
14630   int argc,
14631   sqlite3_value **argv
14632 ){
14633   DateTime x;
14634   if( isDate(context, argc, argv, &x)==0 ){
14635     char zBuf[100];
14636     computeYMD_HMS(&x);
14637     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14638                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14639     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14640   }
14641 }
14642 
14643 /*
14644 **    time( TIMESTRING, MOD, MOD, ...)
14645 **
14646 ** Return HH:MM:SS
14647 */
14648 static void timeFunc(
14649   sqlite3_context *context,
14650   int argc,
14651   sqlite3_value **argv
14652 ){
14653   DateTime x;
14654   if( isDate(context, argc, argv, &x)==0 ){
14655     char zBuf[100];
14656     computeHMS(&x);
14657     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14658     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14659   }
14660 }
14661 
14662 /*
14663 **    date( TIMESTRING, MOD, MOD, ...)
14664 **
14665 ** Return YYYY-MM-DD
14666 */
14667 static void dateFunc(
14668   sqlite3_context *context,
14669   int argc,
14670   sqlite3_value **argv
14671 ){
14672   DateTime x;
14673   if( isDate(context, argc, argv, &x)==0 ){
14674     char zBuf[100];
14675     computeYMD(&x);
14676     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14677     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14678   }
14679 }
14680 
14681 /*
14682 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14683 **
14684 ** Return a string described by FORMAT.  Conversions as follows:
14685 **
14686 **   %d  day of month
14687 **   %f  ** fractional seconds  SS.SSS
14688 **   %H  hour 00-24
14689 **   %j  day of year 000-366
14690 **   %J  ** Julian day number
14691 **   %m  month 01-12
14692 **   %M  minute 00-59
14693 **   %s  seconds since 1970-01-01
14694 **   %S  seconds 00-59
14695 **   %w  day of week 0-6  sunday==0
14696 **   %W  week of year 00-53
14697 **   %Y  year 0000-9999
14698 **   %%  %
14699 */
14700 static void strftimeFunc(
14701   sqlite3_context *context,
14702   int argc,
14703   sqlite3_value **argv
14704 ){
14705   DateTime x;
14706   u64 n;
14707   size_t i,j;
14708   char *z;
14709   sqlite3 *db;
14710   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14711   char zBuf[100];
14712   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14713   db = sqlite3_context_db_handle(context);
14714   for(i=0, n=1; zFmt[i]; i++, n++){
14715     if( zFmt[i]=='%' ){
14716       switch( zFmt[i+1] ){
14717         case 'd':
14718         case 'H':
14719         case 'm':
14720         case 'M':
14721         case 'S':
14722         case 'W':
14723           n++;
14724           /* fall thru */
14725         case 'w':
14726         case '%':
14727           break;
14728         case 'f':
14729           n += 8;
14730           break;
14731         case 'j':
14732           n += 3;
14733           break;
14734         case 'Y':
14735           n += 8;
14736           break;
14737         case 's':
14738         case 'J':
14739           n += 50;
14740           break;
14741         default:
14742           return;  /* ERROR.  return a NULL */
14743       }
14744       i++;
14745     }
14746   }
14747   testcase( n==sizeof(zBuf)-1 );
14748   testcase( n==sizeof(zBuf) );
14749   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14750   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14751   if( n<sizeof(zBuf) ){
14752     z = zBuf;
14753   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14754     sqlite3_result_error_toobig(context);
14755     return;
14756   }else{
14757     z = sqlite3DbMallocRaw(db, (int)n);
14758     if( z==0 ){
14759       sqlite3_result_error_nomem(context);
14760       return;
14761     }
14762   }
14763   computeJD(&x);
14764   computeYMD_HMS(&x);
14765   for(i=j=0; zFmt[i]; i++){
14766     if( zFmt[i]!='%' ){
14767       z[j++] = zFmt[i];
14768     }else{
14769       i++;
14770       switch( zFmt[i] ){
14771         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14772         case 'f': {
14773           double s = x.s;
14774           if( s>59.999 ) s = 59.999;
14775           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14776           j += sqlite3Strlen30(&z[j]);
14777           break;
14778         }
14779         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14780         case 'W': /* Fall thru */
14781         case 'j': {
14782           int nDay;             /* Number of days since 1st day of year */
14783           DateTime y = x;
14784           y.validJD = 0;
14785           y.M = 1;
14786           y.D = 1;
14787           computeJD(&y);
14788           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14789           if( zFmt[i]=='W' ){
14790             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14791             wd = (int)(((x.iJD+43200000)/86400000)%7);
14792             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14793             j += 2;
14794           }else{
14795             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14796             j += 3;
14797           }
14798           break;
14799         }
14800         case 'J': {
14801           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14802           j+=sqlite3Strlen30(&z[j]);
14803           break;
14804         }
14805         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14806         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14807         case 's': {
14808           sqlite3_snprintf(30,&z[j],"%lld",
14809                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14810           j += sqlite3Strlen30(&z[j]);
14811           break;
14812         }
14813         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14814         case 'w': {
14815           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14816           break;
14817         }
14818         case 'Y': {
14819           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14820           break;
14821         }
14822         default:   z[j++] = '%'; break;
14823       }
14824     }
14825   }
14826   z[j] = 0;
14827   sqlite3_result_text(context, z, -1,
14828                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14829 }
14830 
14831 /*
14832 ** current_time()
14833 **
14834 ** This function returns the same value as time('now').
14835 */
14836 static void ctimeFunc(
14837   sqlite3_context *context,
14838   int NotUsed,
14839   sqlite3_value **NotUsed2
14840 ){
14841   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14842   timeFunc(context, 0, 0);
14843 }
14844 
14845 /*
14846 ** current_date()
14847 **
14848 ** This function returns the same value as date('now').
14849 */
14850 static void cdateFunc(
14851   sqlite3_context *context,
14852   int NotUsed,
14853   sqlite3_value **NotUsed2
14854 ){
14855   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14856   dateFunc(context, 0, 0);
14857 }
14858 
14859 /*
14860 ** current_timestamp()
14861 **
14862 ** This function returns the same value as datetime('now').
14863 */
14864 static void ctimestampFunc(
14865   sqlite3_context *context,
14866   int NotUsed,
14867   sqlite3_value **NotUsed2
14868 ){
14869   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14870   datetimeFunc(context, 0, 0);
14871 }
14872 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14873 
14874 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14875 /*
14876 ** If the library is compiled to omit the full-scale date and time
14877 ** handling (to get a smaller binary), the following minimal version
14878 ** of the functions current_time(), current_date() and current_timestamp()
14879 ** are included instead. This is to support column declarations that
14880 ** include "DEFAULT CURRENT_TIME" etc.
14881 **
14882 ** This function uses the C-library functions time(), gmtime()
14883 ** and strftime(). The format string to pass to strftime() is supplied
14884 ** as the user-data for the function.
14885 */
14886 static void currentTimeFunc(
14887   sqlite3_context *context,
14888   int argc,
14889   sqlite3_value **argv
14890 ){
14891   time_t t;
14892   char *zFormat = (char *)sqlite3_user_data(context);
14893   sqlite3 *db;
14894   sqlite3_int64 iT;
14895   struct tm *pTm;
14896   struct tm sNow;
14897   char zBuf[20];
14898 
14899   UNUSED_PARAMETER(argc);
14900   UNUSED_PARAMETER(argv);
14901 
14902   db = sqlite3_context_db_handle(context);
14903   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14904   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14905 #ifdef HAVE_GMTIME_R
14906   pTm = gmtime_r(&t, &sNow);
14907 #else
14908   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14909   pTm = gmtime(&t);
14910   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14911   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14912 #endif
14913   if( pTm ){
14914     strftime(zBuf, 20, zFormat, &sNow);
14915     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14916   }
14917 }
14918 #endif
14919 
14920 /*
14921 ** This function registered all of the above C functions as SQL
14922 ** functions.  This should be the only routine in this file with
14923 ** external linkage.
14924 */
14925 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14926   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14927 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14928     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14929     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14930     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14931     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14932     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14933     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14934     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14935     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14936 #else
14937     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14938     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14939     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14940 #endif
14941   };
14942   int i;
14943   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14944   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14945 
14946   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14947     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14948   }
14949 }
14950 
14951 /************** End of date.c ************************************************/
14952 /************** Begin file os.c **********************************************/
14953 /*
14954 ** 2005 November 29
14955 **
14956 ** The author disclaims copyright to this source code.  In place of
14957 ** a legal notice, here is a blessing:
14958 **
14959 **    May you do good and not evil.
14960 **    May you find forgiveness for yourself and forgive others.
14961 **    May you share freely, never taking more than you give.
14962 **
14963 ******************************************************************************
14964 **
14965 ** This file contains OS interface code that is common to all
14966 ** architectures.
14967 */
14968 #define _SQLITE_OS_C_ 1
14969 #undef _SQLITE_OS_C_
14970 
14971 /*
14972 ** The default SQLite sqlite3_vfs implementations do not allocate
14973 ** memory (actually, os_unix.c allocates a small amount of memory
14974 ** from within OsOpen()), but some third-party implementations may.
14975 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14976 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14977 **
14978 ** The following functions are instrumented for malloc() failure
14979 ** testing:
14980 **
14981 **     sqlite3OsRead()
14982 **     sqlite3OsWrite()
14983 **     sqlite3OsSync()
14984 **     sqlite3OsFileSize()
14985 **     sqlite3OsLock()
14986 **     sqlite3OsCheckReservedLock()
14987 **     sqlite3OsFileControl()
14988 **     sqlite3OsShmMap()
14989 **     sqlite3OsOpen()
14990 **     sqlite3OsDelete()
14991 **     sqlite3OsAccess()
14992 **     sqlite3OsFullPathname()
14993 **
14994 */
14995 #if defined(SQLITE_TEST)
14996 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14997   #define DO_OS_MALLOC_TEST(x)                                       \
14998   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14999     void *pTstAlloc = sqlite3Malloc(10);                             \
15000     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15001     sqlite3_free(pTstAlloc);                                         \
15002   }
15003 #else
15004   #define DO_OS_MALLOC_TEST(x)
15005 #endif
15006 
15007 /*
15008 ** The following routines are convenience wrappers around methods
15009 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15010 ** of this would be completely automatic if SQLite were coded using
15011 ** C++ instead of plain old C.
15012 */
15013 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15014   int rc = SQLITE_OK;
15015   if( pId->pMethods ){
15016     rc = pId->pMethods->xClose(pId);
15017     pId->pMethods = 0;
15018   }
15019   return rc;
15020 }
15021 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15022   DO_OS_MALLOC_TEST(id);
15023   return id->pMethods->xRead(id, pBuf, amt, offset);
15024 }
15025 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15026   DO_OS_MALLOC_TEST(id);
15027   return id->pMethods->xWrite(id, pBuf, amt, offset);
15028 }
15029 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15030   return id->pMethods->xTruncate(id, size);
15031 }
15032 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15033   DO_OS_MALLOC_TEST(id);
15034   return id->pMethods->xSync(id, flags);
15035 }
15036 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15037   DO_OS_MALLOC_TEST(id);
15038   return id->pMethods->xFileSize(id, pSize);
15039 }
15040 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15041   DO_OS_MALLOC_TEST(id);
15042   return id->pMethods->xLock(id, lockType);
15043 }
15044 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15045   return id->pMethods->xUnlock(id, lockType);
15046 }
15047 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15048   DO_OS_MALLOC_TEST(id);
15049   return id->pMethods->xCheckReservedLock(id, pResOut);
15050 }
15051 
15052 /*
15053 ** Use sqlite3OsFileControl() when we are doing something that might fail
15054 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15055 ** when simply tossing information over the wall to the VFS and we do not
15056 ** really care if the VFS receives and understands the information since it
15057 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15058 ** routine has no return value since the return value would be meaningless.
15059 */
15060 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15061   DO_OS_MALLOC_TEST(id);
15062   return id->pMethods->xFileControl(id, op, pArg);
15063 }
15064 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15065   (void)id->pMethods->xFileControl(id, op, pArg);
15066 }
15067 
15068 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15069   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15070   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15071 }
15072 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15073   return id->pMethods->xDeviceCharacteristics(id);
15074 }
15075 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15076   return id->pMethods->xShmLock(id, offset, n, flags);
15077 }
15078 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15079   id->pMethods->xShmBarrier(id);
15080 }
15081 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15082   return id->pMethods->xShmUnmap(id, deleteFlag);
15083 }
15084 SQLITE_PRIVATE int sqlite3OsShmMap(
15085   sqlite3_file *id,               /* Database file handle */
15086   int iPage,
15087   int pgsz,
15088   int bExtend,                    /* True to extend file if necessary */
15089   void volatile **pp              /* OUT: Pointer to mapping */
15090 ){
15091   DO_OS_MALLOC_TEST(id);
15092   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15093 }
15094 
15095 /*
15096 ** The next group of routines are convenience wrappers around the
15097 ** VFS methods.
15098 */
15099 SQLITE_PRIVATE int sqlite3OsOpen(
15100   sqlite3_vfs *pVfs,
15101   const char *zPath,
15102   sqlite3_file *pFile,
15103   int flags,
15104   int *pFlagsOut
15105 ){
15106   int rc;
15107   DO_OS_MALLOC_TEST(0);
15108   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15109   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15110   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15111   ** reaching the VFS. */
15112   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15113   assert( rc==SQLITE_OK || pFile->pMethods==0 );
15114   return rc;
15115 }
15116 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15117   DO_OS_MALLOC_TEST(0);
15118   assert( dirSync==0 || dirSync==1 );
15119   return pVfs->xDelete(pVfs, zPath, dirSync);
15120 }
15121 SQLITE_PRIVATE int sqlite3OsAccess(
15122   sqlite3_vfs *pVfs,
15123   const char *zPath,
15124   int flags,
15125   int *pResOut
15126 ){
15127   DO_OS_MALLOC_TEST(0);
15128   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15129 }
15130 SQLITE_PRIVATE int sqlite3OsFullPathname(
15131   sqlite3_vfs *pVfs,
15132   const char *zPath,
15133   int nPathOut,
15134   char *zPathOut
15135 ){
15136   DO_OS_MALLOC_TEST(0);
15137   zPathOut[0] = 0;
15138   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15139 }
15140 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15141 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15142   return pVfs->xDlOpen(pVfs, zPath);
15143 }
15144 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15145   pVfs->xDlError(pVfs, nByte, zBufOut);
15146 }
15147 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15148   return pVfs->xDlSym(pVfs, pHdle, zSym);
15149 }
15150 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15151   pVfs->xDlClose(pVfs, pHandle);
15152 }
15153 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15154 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15155   return pVfs->xRandomness(pVfs, nByte, zBufOut);
15156 }
15157 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15158   return pVfs->xSleep(pVfs, nMicro);
15159 }
15160 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15161   int rc;
15162   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15163   ** method to get the current date and time if that method is available
15164   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15165   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15166   ** unavailable.
15167   */
15168   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15169     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15170   }else{
15171     double r;
15172     rc = pVfs->xCurrentTime(pVfs, &r);
15173     *pTimeOut = (sqlite3_int64)(r*86400000.0);
15174   }
15175   return rc;
15176 }
15177 
15178 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15179   sqlite3_vfs *pVfs,
15180   const char *zFile,
15181   sqlite3_file **ppFile,
15182   int flags,
15183   int *pOutFlags
15184 ){
15185   int rc = SQLITE_NOMEM;
15186   sqlite3_file *pFile;
15187   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15188   if( pFile ){
15189     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15190     if( rc!=SQLITE_OK ){
15191       sqlite3_free(pFile);
15192     }else{
15193       *ppFile = pFile;
15194     }
15195   }
15196   return rc;
15197 }
15198 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15199   int rc = SQLITE_OK;
15200   assert( pFile );
15201   rc = sqlite3OsClose(pFile);
15202   sqlite3_free(pFile);
15203   return rc;
15204 }
15205 
15206 /*
15207 ** This function is a wrapper around the OS specific implementation of
15208 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15209 ** ability to simulate a malloc failure, so that the handling of an
15210 ** error in sqlite3_os_init() by the upper layers can be tested.
15211 */
15212 SQLITE_PRIVATE int sqlite3OsInit(void){
15213   void *p = sqlite3_malloc(10);
15214   if( p==0 ) return SQLITE_NOMEM;
15215   sqlite3_free(p);
15216   return sqlite3_os_init();
15217 }
15218 
15219 /*
15220 ** The list of all registered VFS implementations.
15221 */
15222 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15223 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15224 
15225 /*
15226 ** Locate a VFS by name.  If no name is given, simply return the
15227 ** first VFS on the list.
15228 */
15229 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15230   sqlite3_vfs *pVfs = 0;
15231 #if SQLITE_THREADSAFE
15232   sqlite3_mutex *mutex;
15233 #endif
15234 #ifndef SQLITE_OMIT_AUTOINIT
15235   int rc = sqlite3_initialize();
15236   if( rc ) return 0;
15237 #endif
15238 #if SQLITE_THREADSAFE
15239   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15240 #endif
15241   sqlite3_mutex_enter(mutex);
15242   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15243     if( zVfs==0 ) break;
15244     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15245   }
15246   sqlite3_mutex_leave(mutex);
15247   return pVfs;
15248 }
15249 
15250 /*
15251 ** Unlink a VFS from the linked list
15252 */
15253 static void vfsUnlink(sqlite3_vfs *pVfs){
15254   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15255   if( pVfs==0 ){
15256     /* No-op */
15257   }else if( vfsList==pVfs ){
15258     vfsList = pVfs->pNext;
15259   }else if( vfsList ){
15260     sqlite3_vfs *p = vfsList;
15261     while( p->pNext && p->pNext!=pVfs ){
15262       p = p->pNext;
15263     }
15264     if( p->pNext==pVfs ){
15265       p->pNext = pVfs->pNext;
15266     }
15267   }
15268 }
15269 
15270 /*
15271 ** Register a VFS with the system.  It is harmless to register the same
15272 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15273 ** true.
15274 */
15275 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15276   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15277 #ifndef SQLITE_OMIT_AUTOINIT
15278   int rc = sqlite3_initialize();
15279   if( rc ) return rc;
15280 #endif
15281   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15282   sqlite3_mutex_enter(mutex);
15283   vfsUnlink(pVfs);
15284   if( makeDflt || vfsList==0 ){
15285     pVfs->pNext = vfsList;
15286     vfsList = pVfs;
15287   }else{
15288     pVfs->pNext = vfsList->pNext;
15289     vfsList->pNext = pVfs;
15290   }
15291   assert(vfsList);
15292   sqlite3_mutex_leave(mutex);
15293   return SQLITE_OK;
15294 }
15295 
15296 /*
15297 ** Unregister a VFS so that it is no longer accessible.
15298 */
15299 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15300 #if SQLITE_THREADSAFE
15301   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15302 #endif
15303   sqlite3_mutex_enter(mutex);
15304   vfsUnlink(pVfs);
15305   sqlite3_mutex_leave(mutex);
15306   return SQLITE_OK;
15307 }
15308 
15309 /************** End of os.c **************************************************/
15310 /************** Begin file fault.c *******************************************/
15311 /*
15312 ** 2008 Jan 22
15313 **
15314 ** The author disclaims copyright to this source code.  In place of
15315 ** a legal notice, here is a blessing:
15316 **
15317 **    May you do good and not evil.
15318 **    May you find forgiveness for yourself and forgive others.
15319 **    May you share freely, never taking more than you give.
15320 **
15321 *************************************************************************
15322 **
15323 ** This file contains code to support the concept of "benign"
15324 ** malloc failures (when the xMalloc() or xRealloc() method of the
15325 ** sqlite3_mem_methods structure fails to allocate a block of memory
15326 ** and returns 0).
15327 **
15328 ** Most malloc failures are non-benign. After they occur, SQLite
15329 ** abandons the current operation and returns an error code (usually
15330 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15331 ** fatal. For example, if a malloc fails while resizing a hash table, this
15332 ** is completely recoverable simply by not carrying out the resize. The
15333 ** hash table will continue to function normally.  So a malloc failure
15334 ** during a hash table resize is a benign fault.
15335 */
15336 
15337 
15338 #ifndef SQLITE_OMIT_BUILTIN_TEST
15339 
15340 /*
15341 ** Global variables.
15342 */
15343 typedef struct BenignMallocHooks BenignMallocHooks;
15344 static SQLITE_WSD struct BenignMallocHooks {
15345   void (*xBenignBegin)(void);
15346   void (*xBenignEnd)(void);
15347 } sqlite3Hooks = { 0, 0 };
15348 
15349 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15350 ** structure.  If writable static data is unsupported on the target,
15351 ** we have to locate the state vector at run-time.  In the more common
15352 ** case where writable static data is supported, wsdHooks can refer directly
15353 ** to the "sqlite3Hooks" state vector declared above.
15354 */
15355 #ifdef SQLITE_OMIT_WSD
15356 # define wsdHooksInit \
15357   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15358 # define wsdHooks x[0]
15359 #else
15360 # define wsdHooksInit
15361 # define wsdHooks sqlite3Hooks
15362 #endif
15363 
15364 
15365 /*
15366 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15367 ** sqlite3EndBenignMalloc() are called, respectively.
15368 */
15369 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15370   void (*xBenignBegin)(void),
15371   void (*xBenignEnd)(void)
15372 ){
15373   wsdHooksInit;
15374   wsdHooks.xBenignBegin = xBenignBegin;
15375   wsdHooks.xBenignEnd = xBenignEnd;
15376 }
15377 
15378 /*
15379 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15380 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15381 ** indicates that subsequent malloc failures are non-benign.
15382 */
15383 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15384   wsdHooksInit;
15385   if( wsdHooks.xBenignBegin ){
15386     wsdHooks.xBenignBegin();
15387   }
15388 }
15389 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15390   wsdHooksInit;
15391   if( wsdHooks.xBenignEnd ){
15392     wsdHooks.xBenignEnd();
15393   }
15394 }
15395 
15396 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15397 
15398 /************** End of fault.c ***********************************************/
15399 /************** Begin file mem0.c ********************************************/
15400 /*
15401 ** 2008 October 28
15402 **
15403 ** The author disclaims copyright to this source code.  In place of
15404 ** a legal notice, here is a blessing:
15405 **
15406 **    May you do good and not evil.
15407 **    May you find forgiveness for yourself and forgive others.
15408 **    May you share freely, never taking more than you give.
15409 **
15410 *************************************************************************
15411 **
15412 ** This file contains a no-op memory allocation drivers for use when
15413 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15414 ** here always fail.  SQLite will not operate with these drivers.  These
15415 ** are merely placeholders.  Real drivers must be substituted using
15416 ** sqlite3_config() before SQLite will operate.
15417 */
15418 
15419 /*
15420 ** This version of the memory allocator is the default.  It is
15421 ** used when no other memory allocator is specified using compile-time
15422 ** macros.
15423 */
15424 #ifdef SQLITE_ZERO_MALLOC
15425 
15426 /*
15427 ** No-op versions of all memory allocation routines
15428 */
15429 static void *sqlite3MemMalloc(int nByte){ return 0; }
15430 static void sqlite3MemFree(void *pPrior){ return; }
15431 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15432 static int sqlite3MemSize(void *pPrior){ return 0; }
15433 static int sqlite3MemRoundup(int n){ return n; }
15434 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15435 static void sqlite3MemShutdown(void *NotUsed){ return; }
15436 
15437 /*
15438 ** This routine is the only routine in this file with external linkage.
15439 **
15440 ** Populate the low-level memory allocation function pointers in
15441 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15442 */
15443 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15444   static const sqlite3_mem_methods defaultMethods = {
15445      sqlite3MemMalloc,
15446      sqlite3MemFree,
15447      sqlite3MemRealloc,
15448      sqlite3MemSize,
15449      sqlite3MemRoundup,
15450      sqlite3MemInit,
15451      sqlite3MemShutdown,
15452      0
15453   };
15454   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15455 }
15456 
15457 #endif /* SQLITE_ZERO_MALLOC */
15458 
15459 /************** End of mem0.c ************************************************/
15460 /************** Begin file mem1.c ********************************************/
15461 /*
15462 ** 2007 August 14
15463 **
15464 ** The author disclaims copyright to this source code.  In place of
15465 ** a legal notice, here is a blessing:
15466 **
15467 **    May you do good and not evil.
15468 **    May you find forgiveness for yourself and forgive others.
15469 **    May you share freely, never taking more than you give.
15470 **
15471 *************************************************************************
15472 **
15473 ** This file contains low-level memory allocation drivers for when
15474 ** SQLite will use the standard C-library malloc/realloc/free interface
15475 ** to obtain the memory it needs.
15476 **
15477 ** This file contains implementations of the low-level memory allocation
15478 ** routines specified in the sqlite3_mem_methods object.  The content of
15479 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15480 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15481 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15482 ** default configuration is to use memory allocation routines in this
15483 ** file.
15484 **
15485 ** C-preprocessor macro summary:
15486 **
15487 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15488 **                                the malloc_usable_size() interface exists
15489 **                                on the target platform.  Or, this symbol
15490 **                                can be set manually, if desired.
15491 **                                If an equivalent interface exists by
15492 **                                a different name, using a separate -D
15493 **                                option to rename it.
15494 **
15495 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15496 **                                memory allocator.  Set this symbol to enable
15497 **                                building on older macs.
15498 **
15499 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15500 **                                _msize() on windows systems.  This might
15501 **                                be necessary when compiling for Delphi,
15502 **                                for example.
15503 */
15504 
15505 /*
15506 ** This version of the memory allocator is the default.  It is
15507 ** used when no other memory allocator is specified using compile-time
15508 ** macros.
15509 */
15510 #ifdef SQLITE_SYSTEM_MALLOC
15511 
15512 /*
15513 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15514 ** The use of _msize() is automatic, but can be disabled by compiling
15515 ** with -DSQLITE_WITHOUT_MSIZE
15516 */
15517 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15518 # define SQLITE_MALLOCSIZE _msize
15519 #endif
15520 
15521 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15522 
15523 /*
15524 ** Use the zone allocator available on apple products unless the
15525 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15526 */
15527 #include <sys/sysctl.h>
15528 #include <malloc/malloc.h>
15529 #include <libkern/OSAtomic.h>
15530 static malloc_zone_t* _sqliteZone_;
15531 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15532 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15533 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15534 #define SQLITE_MALLOCSIZE(x) \
15535         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15536 
15537 #else /* if not __APPLE__ */
15538 
15539 /*
15540 ** Use standard C library malloc and free on non-Apple systems.
15541 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15542 */
15543 #define SQLITE_MALLOC(x)    malloc(x)
15544 #define SQLITE_FREE(x)      free(x)
15545 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15546 
15547 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15548       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15549 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
15550 #endif
15551 #ifdef HAVE_MALLOC_USABLE_SIZE
15552 # ifndef SQLITE_MALLOCSIZE
15553 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15554 # endif
15555 #else
15556 # undef SQLITE_MALLOCSIZE
15557 #endif
15558 
15559 #endif /* __APPLE__ or not __APPLE__ */
15560 
15561 /*
15562 ** Like malloc(), but remember the size of the allocation
15563 ** so that we can find it later using sqlite3MemSize().
15564 **
15565 ** For this low-level routine, we are guaranteed that nByte>0 because
15566 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15567 ** routines.
15568 */
15569 static void *sqlite3MemMalloc(int nByte){
15570 #ifdef SQLITE_MALLOCSIZE
15571   void *p = SQLITE_MALLOC( nByte );
15572   if( p==0 ){
15573     testcase( sqlite3GlobalConfig.xLog!=0 );
15574     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15575   }
15576   return p;
15577 #else
15578   sqlite3_int64 *p;
15579   assert( nByte>0 );
15580   nByte = ROUND8(nByte);
15581   p = SQLITE_MALLOC( nByte+8 );
15582   if( p ){
15583     p[0] = nByte;
15584     p++;
15585   }else{
15586     testcase( sqlite3GlobalConfig.xLog!=0 );
15587     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15588   }
15589   return (void *)p;
15590 #endif
15591 }
15592 
15593 /*
15594 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15595 ** or sqlite3MemRealloc().
15596 **
15597 ** For this low-level routine, we already know that pPrior!=0 since
15598 ** cases where pPrior==0 will have been intecepted and dealt with
15599 ** by higher-level routines.
15600 */
15601 static void sqlite3MemFree(void *pPrior){
15602 #ifdef SQLITE_MALLOCSIZE
15603   SQLITE_FREE(pPrior);
15604 #else
15605   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15606   assert( pPrior!=0 );
15607   p--;
15608   SQLITE_FREE(p);
15609 #endif
15610 }
15611 
15612 /*
15613 ** Report the allocated size of a prior return from xMalloc()
15614 ** or xRealloc().
15615 */
15616 static int sqlite3MemSize(void *pPrior){
15617 #ifdef SQLITE_MALLOCSIZE
15618   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15619 #else
15620   sqlite3_int64 *p;
15621   if( pPrior==0 ) return 0;
15622   p = (sqlite3_int64*)pPrior;
15623   p--;
15624   return (int)p[0];
15625 #endif
15626 }
15627 
15628 /*
15629 ** Like realloc().  Resize an allocation previously obtained from
15630 ** sqlite3MemMalloc().
15631 **
15632 ** For this low-level interface, we know that pPrior!=0.  Cases where
15633 ** pPrior==0 while have been intercepted by higher-level routine and
15634 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15635 ** cases where nByte<=0 will have been intercepted by higher-level
15636 ** routines and redirected to xFree.
15637 */
15638 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15639 #ifdef SQLITE_MALLOCSIZE
15640   void *p = SQLITE_REALLOC(pPrior, nByte);
15641   if( p==0 ){
15642     testcase( sqlite3GlobalConfig.xLog!=0 );
15643     sqlite3_log(SQLITE_NOMEM,
15644       "failed memory resize %u to %u bytes",
15645       SQLITE_MALLOCSIZE(pPrior), nByte);
15646   }
15647   return p;
15648 #else
15649   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15650   assert( pPrior!=0 && nByte>0 );
15651   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15652   p--;
15653   p = SQLITE_REALLOC(p, nByte+8 );
15654   if( p ){
15655     p[0] = nByte;
15656     p++;
15657   }else{
15658     testcase( sqlite3GlobalConfig.xLog!=0 );
15659     sqlite3_log(SQLITE_NOMEM,
15660       "failed memory resize %u to %u bytes",
15661       sqlite3MemSize(pPrior), nByte);
15662   }
15663   return (void*)p;
15664 #endif
15665 }
15666 
15667 /*
15668 ** Round up a request size to the next valid allocation size.
15669 */
15670 static int sqlite3MemRoundup(int n){
15671   return ROUND8(n);
15672 }
15673 
15674 /*
15675 ** Initialize this module.
15676 */
15677 static int sqlite3MemInit(void *NotUsed){
15678 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15679   int cpuCount;
15680   size_t len;
15681   if( _sqliteZone_ ){
15682     return SQLITE_OK;
15683   }
15684   len = sizeof(cpuCount);
15685   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15686   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15687   if( cpuCount>1 ){
15688     /* defer MT decisions to system malloc */
15689     _sqliteZone_ = malloc_default_zone();
15690   }else{
15691     /* only 1 core, use our own zone to contention over global locks,
15692     ** e.g. we have our own dedicated locks */
15693     bool success;
15694     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15695     malloc_set_zone_name(newzone, "Sqlite_Heap");
15696     do{
15697       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
15698                                  (void * volatile *)&_sqliteZone_);
15699     }while(!_sqliteZone_);
15700     if( !success ){
15701       /* somebody registered a zone first */
15702       malloc_destroy_zone(newzone);
15703     }
15704   }
15705 #endif
15706   UNUSED_PARAMETER(NotUsed);
15707   return SQLITE_OK;
15708 }
15709 
15710 /*
15711 ** Deinitialize this module.
15712 */
15713 static void sqlite3MemShutdown(void *NotUsed){
15714   UNUSED_PARAMETER(NotUsed);
15715   return;
15716 }
15717 
15718 /*
15719 ** This routine is the only routine in this file with external linkage.
15720 **
15721 ** Populate the low-level memory allocation function pointers in
15722 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15723 */
15724 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15725   static const sqlite3_mem_methods defaultMethods = {
15726      sqlite3MemMalloc,
15727      sqlite3MemFree,
15728      sqlite3MemRealloc,
15729      sqlite3MemSize,
15730      sqlite3MemRoundup,
15731      sqlite3MemInit,
15732      sqlite3MemShutdown,
15733      0
15734   };
15735   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15736 }
15737 
15738 #endif /* SQLITE_SYSTEM_MALLOC */
15739 
15740 /************** End of mem1.c ************************************************/
15741 /************** Begin file mem2.c ********************************************/
15742 /*
15743 ** 2007 August 15
15744 **
15745 ** The author disclaims copyright to this source code.  In place of
15746 ** a legal notice, here is a blessing:
15747 **
15748 **    May you do good and not evil.
15749 **    May you find forgiveness for yourself and forgive others.
15750 **    May you share freely, never taking more than you give.
15751 **
15752 *************************************************************************
15753 **
15754 ** This file contains low-level memory allocation drivers for when
15755 ** SQLite will use the standard C-library malloc/realloc/free interface
15756 ** to obtain the memory it needs while adding lots of additional debugging
15757 ** information to each allocation in order to help detect and fix memory
15758 ** leaks and memory usage errors.
15759 **
15760 ** This file contains implementations of the low-level memory allocation
15761 ** routines specified in the sqlite3_mem_methods object.
15762 */
15763 
15764 /*
15765 ** This version of the memory allocator is used only if the
15766 ** SQLITE_MEMDEBUG macro is defined
15767 */
15768 #ifdef SQLITE_MEMDEBUG
15769 
15770 /*
15771 ** The backtrace functionality is only available with GLIBC
15772 */
15773 #ifdef __GLIBC__
15774   extern int backtrace(void**,int);
15775   extern void backtrace_symbols_fd(void*const*,int,int);
15776 #else
15777 # define backtrace(A,B) 1
15778 # define backtrace_symbols_fd(A,B,C)
15779 #endif
15780 /* #include <stdio.h> */
15781 
15782 /*
15783 ** Each memory allocation looks like this:
15784 **
15785 **  ------------------------------------------------------------------------
15786 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15787 **  ------------------------------------------------------------------------
15788 **
15789 ** The application code sees only a pointer to the allocation.  We have
15790 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15791 ** MemBlockHdr tells us the size of the allocation and the number of
15792 ** backtrace pointers.  There is also a guard word at the end of the
15793 ** MemBlockHdr.
15794 */
15795 struct MemBlockHdr {
15796   i64 iSize;                          /* Size of this allocation */
15797   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15798   char nBacktrace;                    /* Number of backtraces on this alloc */
15799   char nBacktraceSlots;               /* Available backtrace slots */
15800   u8 nTitle;                          /* Bytes of title; includes '\0' */
15801   u8 eType;                           /* Allocation type code */
15802   int iForeGuard;                     /* Guard word for sanity */
15803 };
15804 
15805 /*
15806 ** Guard words
15807 */
15808 #define FOREGUARD 0x80F5E153
15809 #define REARGUARD 0xE4676B53
15810 
15811 /*
15812 ** Number of malloc size increments to track.
15813 */
15814 #define NCSIZE  1000
15815 
15816 /*
15817 ** All of the static variables used by this module are collected
15818 ** into a single structure named "mem".  This is to keep the
15819 ** static variables organized and to reduce namespace pollution
15820 ** when this module is combined with other in the amalgamation.
15821 */
15822 static struct {
15823 
15824   /*
15825   ** Mutex to control access to the memory allocation subsystem.
15826   */
15827   sqlite3_mutex *mutex;
15828 
15829   /*
15830   ** Head and tail of a linked list of all outstanding allocations
15831   */
15832   struct MemBlockHdr *pFirst;
15833   struct MemBlockHdr *pLast;
15834 
15835   /*
15836   ** The number of levels of backtrace to save in new allocations.
15837   */
15838   int nBacktrace;
15839   void (*xBacktrace)(int, int, void **);
15840 
15841   /*
15842   ** Title text to insert in front of each block
15843   */
15844   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15845   char zTitle[100];  /* The title text */
15846 
15847   /*
15848   ** sqlite3MallocDisallow() increments the following counter.
15849   ** sqlite3MallocAllow() decrements it.
15850   */
15851   int disallow; /* Do not allow memory allocation */
15852 
15853   /*
15854   ** Gather statistics on the sizes of memory allocations.
15855   ** nAlloc[i] is the number of allocation attempts of i*8
15856   ** bytes.  i==NCSIZE is the number of allocation attempts for
15857   ** sizes more than NCSIZE*8 bytes.
15858   */
15859   int nAlloc[NCSIZE];      /* Total number of allocations */
15860   int nCurrent[NCSIZE];    /* Current number of allocations */
15861   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15862 
15863 } mem;
15864 
15865 
15866 /*
15867 ** Adjust memory usage statistics
15868 */
15869 static void adjustStats(int iSize, int increment){
15870   int i = ROUND8(iSize)/8;
15871   if( i>NCSIZE-1 ){
15872     i = NCSIZE - 1;
15873   }
15874   if( increment>0 ){
15875     mem.nAlloc[i]++;
15876     mem.nCurrent[i]++;
15877     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15878       mem.mxCurrent[i] = mem.nCurrent[i];
15879     }
15880   }else{
15881     mem.nCurrent[i]--;
15882     assert( mem.nCurrent[i]>=0 );
15883   }
15884 }
15885 
15886 /*
15887 ** Given an allocation, find the MemBlockHdr for that allocation.
15888 **
15889 ** This routine checks the guards at either end of the allocation and
15890 ** if they are incorrect it asserts.
15891 */
15892 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15893   struct MemBlockHdr *p;
15894   int *pInt;
15895   u8 *pU8;
15896   int nReserve;
15897 
15898   p = (struct MemBlockHdr*)pAllocation;
15899   p--;
15900   assert( p->iForeGuard==(int)FOREGUARD );
15901   nReserve = ROUND8(p->iSize);
15902   pInt = (int*)pAllocation;
15903   pU8 = (u8*)pAllocation;
15904   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15905   /* This checks any of the "extra" bytes allocated due
15906   ** to rounding up to an 8 byte boundary to ensure
15907   ** they haven't been overwritten.
15908   */
15909   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15910   return p;
15911 }
15912 
15913 /*
15914 ** Return the number of bytes currently allocated at address p.
15915 */
15916 static int sqlite3MemSize(void *p){
15917   struct MemBlockHdr *pHdr;
15918   if( !p ){
15919     return 0;
15920   }
15921   pHdr = sqlite3MemsysGetHeader(p);
15922   return pHdr->iSize;
15923 }
15924 
15925 /*
15926 ** Initialize the memory allocation subsystem.
15927 */
15928 static int sqlite3MemInit(void *NotUsed){
15929   UNUSED_PARAMETER(NotUsed);
15930   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15931   if( !sqlite3GlobalConfig.bMemstat ){
15932     /* If memory status is enabled, then the malloc.c wrapper will already
15933     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15934     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15935   }
15936   return SQLITE_OK;
15937 }
15938 
15939 /*
15940 ** Deinitialize the memory allocation subsystem.
15941 */
15942 static void sqlite3MemShutdown(void *NotUsed){
15943   UNUSED_PARAMETER(NotUsed);
15944   mem.mutex = 0;
15945 }
15946 
15947 /*
15948 ** Round up a request size to the next valid allocation size.
15949 */
15950 static int sqlite3MemRoundup(int n){
15951   return ROUND8(n);
15952 }
15953 
15954 /*
15955 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15956 ** the content of a new memory allocation to unpredictable values and
15957 ** to clear the content of a freed allocation to unpredictable values.
15958 */
15959 static void randomFill(char *pBuf, int nByte){
15960   unsigned int x, y, r;
15961   x = SQLITE_PTR_TO_INT(pBuf);
15962   y = nByte | 1;
15963   while( nByte >= 4 ){
15964     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15965     y = y*1103515245 + 12345;
15966     r = x ^ y;
15967     *(int*)pBuf = r;
15968     pBuf += 4;
15969     nByte -= 4;
15970   }
15971   while( nByte-- > 0 ){
15972     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15973     y = y*1103515245 + 12345;
15974     r = x ^ y;
15975     *(pBuf++) = r & 0xff;
15976   }
15977 }
15978 
15979 /*
15980 ** Allocate nByte bytes of memory.
15981 */
15982 static void *sqlite3MemMalloc(int nByte){
15983   struct MemBlockHdr *pHdr;
15984   void **pBt;
15985   char *z;
15986   int *pInt;
15987   void *p = 0;
15988   int totalSize;
15989   int nReserve;
15990   sqlite3_mutex_enter(mem.mutex);
15991   assert( mem.disallow==0 );
15992   nReserve = ROUND8(nByte);
15993   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15994                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15995   p = malloc(totalSize);
15996   if( p ){
15997     z = p;
15998     pBt = (void**)&z[mem.nTitle];
15999     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16000     pHdr->pNext = 0;
16001     pHdr->pPrev = mem.pLast;
16002     if( mem.pLast ){
16003       mem.pLast->pNext = pHdr;
16004     }else{
16005       mem.pFirst = pHdr;
16006     }
16007     mem.pLast = pHdr;
16008     pHdr->iForeGuard = FOREGUARD;
16009     pHdr->eType = MEMTYPE_HEAP;
16010     pHdr->nBacktraceSlots = mem.nBacktrace;
16011     pHdr->nTitle = mem.nTitle;
16012     if( mem.nBacktrace ){
16013       void *aAddr[40];
16014       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16015       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16016       assert(pBt[0]);
16017       if( mem.xBacktrace ){
16018         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16019       }
16020     }else{
16021       pHdr->nBacktrace = 0;
16022     }
16023     if( mem.nTitle ){
16024       memcpy(z, mem.zTitle, mem.nTitle);
16025     }
16026     pHdr->iSize = nByte;
16027     adjustStats(nByte, +1);
16028     pInt = (int*)&pHdr[1];
16029     pInt[nReserve/sizeof(int)] = REARGUARD;
16030     randomFill((char*)pInt, nByte);
16031     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16032     p = (void*)pInt;
16033   }
16034   sqlite3_mutex_leave(mem.mutex);
16035   return p;
16036 }
16037 
16038 /*
16039 ** Free memory.
16040 */
16041 static void sqlite3MemFree(void *pPrior){
16042   struct MemBlockHdr *pHdr;
16043   void **pBt;
16044   char *z;
16045   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
16046        || mem.mutex!=0 );
16047   pHdr = sqlite3MemsysGetHeader(pPrior);
16048   pBt = (void**)pHdr;
16049   pBt -= pHdr->nBacktraceSlots;
16050   sqlite3_mutex_enter(mem.mutex);
16051   if( pHdr->pPrev ){
16052     assert( pHdr->pPrev->pNext==pHdr );
16053     pHdr->pPrev->pNext = pHdr->pNext;
16054   }else{
16055     assert( mem.pFirst==pHdr );
16056     mem.pFirst = pHdr->pNext;
16057   }
16058   if( pHdr->pNext ){
16059     assert( pHdr->pNext->pPrev==pHdr );
16060     pHdr->pNext->pPrev = pHdr->pPrev;
16061   }else{
16062     assert( mem.pLast==pHdr );
16063     mem.pLast = pHdr->pPrev;
16064   }
16065   z = (char*)pBt;
16066   z -= pHdr->nTitle;
16067   adjustStats(pHdr->iSize, -1);
16068   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16069                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
16070   free(z);
16071   sqlite3_mutex_leave(mem.mutex);
16072 }
16073 
16074 /*
16075 ** Change the size of an existing memory allocation.
16076 **
16077 ** For this debugging implementation, we *always* make a copy of the
16078 ** allocation into a new place in memory.  In this way, if the
16079 ** higher level code is using pointer to the old allocation, it is
16080 ** much more likely to break and we are much more liking to find
16081 ** the error.
16082 */
16083 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16084   struct MemBlockHdr *pOldHdr;
16085   void *pNew;
16086   assert( mem.disallow==0 );
16087   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16088   pOldHdr = sqlite3MemsysGetHeader(pPrior);
16089   pNew = sqlite3MemMalloc(nByte);
16090   if( pNew ){
16091     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
16092     if( nByte>pOldHdr->iSize ){
16093       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
16094     }
16095     sqlite3MemFree(pPrior);
16096   }
16097   return pNew;
16098 }
16099 
16100 /*
16101 ** Populate the low-level memory allocation function pointers in
16102 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16103 */
16104 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16105   static const sqlite3_mem_methods defaultMethods = {
16106      sqlite3MemMalloc,
16107      sqlite3MemFree,
16108      sqlite3MemRealloc,
16109      sqlite3MemSize,
16110      sqlite3MemRoundup,
16111      sqlite3MemInit,
16112      sqlite3MemShutdown,
16113      0
16114   };
16115   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16116 }
16117 
16118 /*
16119 ** Set the "type" of an allocation.
16120 */
16121 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16122   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16123     struct MemBlockHdr *pHdr;
16124     pHdr = sqlite3MemsysGetHeader(p);
16125     assert( pHdr->iForeGuard==FOREGUARD );
16126     pHdr->eType = eType;
16127   }
16128 }
16129 
16130 /*
16131 ** Return TRUE if the mask of type in eType matches the type of the
16132 ** allocation p.  Also return true if p==NULL.
16133 **
16134 ** This routine is designed for use within an assert() statement, to
16135 ** verify the type of an allocation.  For example:
16136 **
16137 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16138 */
16139 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16140   int rc = 1;
16141   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16142     struct MemBlockHdr *pHdr;
16143     pHdr = sqlite3MemsysGetHeader(p);
16144     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16145     if( (pHdr->eType&eType)==0 ){
16146       rc = 0;
16147     }
16148   }
16149   return rc;
16150 }
16151 
16152 /*
16153 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16154 ** allocation p.  Also return true if p==NULL.
16155 **
16156 ** This routine is designed for use within an assert() statement, to
16157 ** verify the type of an allocation.  For example:
16158 **
16159 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16160 */
16161 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16162   int rc = 1;
16163   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16164     struct MemBlockHdr *pHdr;
16165     pHdr = sqlite3MemsysGetHeader(p);
16166     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16167     if( (pHdr->eType&eType)!=0 ){
16168       rc = 0;
16169     }
16170   }
16171   return rc;
16172 }
16173 
16174 /*
16175 ** Set the number of backtrace levels kept for each allocation.
16176 ** A value of zero turns off backtracing.  The number is always rounded
16177 ** up to a multiple of 2.
16178 */
16179 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16180   if( depth<0 ){ depth = 0; }
16181   if( depth>20 ){ depth = 20; }
16182   depth = (depth+1)&0xfe;
16183   mem.nBacktrace = depth;
16184 }
16185 
16186 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16187   mem.xBacktrace = xBacktrace;
16188 }
16189 
16190 /*
16191 ** Set the title string for subsequent allocations.
16192 */
16193 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16194   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16195   sqlite3_mutex_enter(mem.mutex);
16196   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16197   memcpy(mem.zTitle, zTitle, n);
16198   mem.zTitle[n] = 0;
16199   mem.nTitle = ROUND8(n);
16200   sqlite3_mutex_leave(mem.mutex);
16201 }
16202 
16203 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16204   struct MemBlockHdr *pHdr;
16205   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16206     void **pBt = (void**)pHdr;
16207     pBt -= pHdr->nBacktraceSlots;
16208     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16209   }
16210 }
16211 
16212 /*
16213 ** Open the file indicated and write a log of all unfreed memory
16214 ** allocations into that log.
16215 */
16216 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16217   FILE *out;
16218   struct MemBlockHdr *pHdr;
16219   void **pBt;
16220   int i;
16221   out = fopen(zFilename, "w");
16222   if( out==0 ){
16223     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16224                     zFilename);
16225     return;
16226   }
16227   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16228     char *z = (char*)pHdr;
16229     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16230     fprintf(out, "**** %lld bytes at %p from %s ****\n",
16231             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16232     if( pHdr->nBacktrace ){
16233       fflush(out);
16234       pBt = (void**)pHdr;
16235       pBt -= pHdr->nBacktraceSlots;
16236       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16237       fprintf(out, "\n");
16238     }
16239   }
16240   fprintf(out, "COUNTS:\n");
16241   for(i=0; i<NCSIZE-1; i++){
16242     if( mem.nAlloc[i] ){
16243       fprintf(out, "   %5d: %10d %10d %10d\n",
16244             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16245     }
16246   }
16247   if( mem.nAlloc[NCSIZE-1] ){
16248     fprintf(out, "   %5d: %10d %10d %10d\n",
16249              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16250              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16251   }
16252   fclose(out);
16253 }
16254 
16255 /*
16256 ** Return the number of times sqlite3MemMalloc() has been called.
16257 */
16258 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16259   int i;
16260   int nTotal = 0;
16261   for(i=0; i<NCSIZE; i++){
16262     nTotal += mem.nAlloc[i];
16263   }
16264   return nTotal;
16265 }
16266 
16267 
16268 #endif /* SQLITE_MEMDEBUG */
16269 
16270 /************** End of mem2.c ************************************************/
16271 /************** Begin file mem3.c ********************************************/
16272 /*
16273 ** 2007 October 14
16274 **
16275 ** The author disclaims copyright to this source code.  In place of
16276 ** a legal notice, here is a blessing:
16277 **
16278 **    May you do good and not evil.
16279 **    May you find forgiveness for yourself and forgive others.
16280 **    May you share freely, never taking more than you give.
16281 **
16282 *************************************************************************
16283 ** This file contains the C functions that implement a memory
16284 ** allocation subsystem for use by SQLite.
16285 **
16286 ** This version of the memory allocation subsystem omits all
16287 ** use of malloc(). The SQLite user supplies a block of memory
16288 ** before calling sqlite3_initialize() from which allocations
16289 ** are made and returned by the xMalloc() and xRealloc()
16290 ** implementations. Once sqlite3_initialize() has been called,
16291 ** the amount of memory available to SQLite is fixed and cannot
16292 ** be changed.
16293 **
16294 ** This version of the memory allocation subsystem is included
16295 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16296 */
16297 
16298 /*
16299 ** This version of the memory allocator is only built into the library
16300 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16301 ** mean that the library will use a memory-pool by default, just that
16302 ** it is available. The mempool allocator is activated by calling
16303 ** sqlite3_config().
16304 */
16305 #ifdef SQLITE_ENABLE_MEMSYS3
16306 
16307 /*
16308 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16309 */
16310 #define MX_SMALL 10
16311 
16312 
16313 /*
16314 ** Number of freelist hash slots
16315 */
16316 #define N_HASH  61
16317 
16318 /*
16319 ** A memory allocation (also called a "chunk") consists of two or
16320 ** more blocks where each block is 8 bytes.  The first 8 bytes are
16321 ** a header that is not returned to the user.
16322 **
16323 ** A chunk is two or more blocks that is either checked out or
16324 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16325 ** size of the allocation in blocks if the allocation is free.
16326 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16327 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16328 ** is true if the previous chunk is checked out and false if the
16329 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16330 ** the previous chunk in blocks if the previous chunk is on the
16331 ** freelist. If the previous chunk is checked out, then
16332 ** u.hdr.prevSize can be part of the data for that chunk and should
16333 ** not be read or written.
16334 **
16335 ** We often identify a chunk by its index in mem3.aPool[].  When
16336 ** this is done, the chunk index refers to the second block of
16337 ** the chunk.  In this way, the first chunk has an index of 1.
16338 ** A chunk index of 0 means "no such chunk" and is the equivalent
16339 ** of a NULL pointer.
16340 **
16341 ** The second block of free chunks is of the form u.list.  The
16342 ** two fields form a double-linked list of chunks of related sizes.
16343 ** Pointers to the head of the list are stored in mem3.aiSmall[]
16344 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16345 **
16346 ** The second block of a chunk is user data if the chunk is checked
16347 ** out.  If a chunk is checked out, the user data may extend into
16348 ** the u.hdr.prevSize value of the following chunk.
16349 */
16350 typedef struct Mem3Block Mem3Block;
16351 struct Mem3Block {
16352   union {
16353     struct {
16354       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16355       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16356     } hdr;
16357     struct {
16358       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16359       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16360     } list;
16361   } u;
16362 };
16363 
16364 /*
16365 ** All of the static variables used by this module are collected
16366 ** into a single structure named "mem3".  This is to keep the
16367 ** static variables organized and to reduce namespace pollution
16368 ** when this module is combined with other in the amalgamation.
16369 */
16370 static SQLITE_WSD struct Mem3Global {
16371   /*
16372   ** Memory available for allocation. nPool is the size of the array
16373   ** (in Mem3Blocks) pointed to by aPool less 2.
16374   */
16375   u32 nPool;
16376   Mem3Block *aPool;
16377 
16378   /*
16379   ** True if we are evaluating an out-of-memory callback.
16380   */
16381   int alarmBusy;
16382 
16383   /*
16384   ** Mutex to control access to the memory allocation subsystem.
16385   */
16386   sqlite3_mutex *mutex;
16387 
16388   /*
16389   ** The minimum amount of free space that we have seen.
16390   */
16391   u32 mnMaster;
16392 
16393   /*
16394   ** iMaster is the index of the master chunk.  Most new allocations
16395   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16396   ** of the current master.  iMaster is 0 if there is not master chunk.
16397   ** The master chunk is not in either the aiHash[] or aiSmall[].
16398   */
16399   u32 iMaster;
16400   u32 szMaster;
16401 
16402   /*
16403   ** Array of lists of free blocks according to the block size
16404   ** for smaller chunks, or a hash on the block size for larger
16405   ** chunks.
16406   */
16407   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16408   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16409 } mem3 = { 97535575 };
16410 
16411 #define mem3 GLOBAL(struct Mem3Global, mem3)
16412 
16413 /*
16414 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16415 ** on.  *pRoot is the list that i is a member of.
16416 */
16417 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16418   u32 next = mem3.aPool[i].u.list.next;
16419   u32 prev = mem3.aPool[i].u.list.prev;
16420   assert( sqlite3_mutex_held(mem3.mutex) );
16421   if( prev==0 ){
16422     *pRoot = next;
16423   }else{
16424     mem3.aPool[prev].u.list.next = next;
16425   }
16426   if( next ){
16427     mem3.aPool[next].u.list.prev = prev;
16428   }
16429   mem3.aPool[i].u.list.next = 0;
16430   mem3.aPool[i].u.list.prev = 0;
16431 }
16432 
16433 /*
16434 ** Unlink the chunk at index i from
16435 ** whatever list is currently a member of.
16436 */
16437 static void memsys3Unlink(u32 i){
16438   u32 size, hash;
16439   assert( sqlite3_mutex_held(mem3.mutex) );
16440   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16441   assert( i>=1 );
16442   size = mem3.aPool[i-1].u.hdr.size4x/4;
16443   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16444   assert( size>=2 );
16445   if( size <= MX_SMALL ){
16446     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16447   }else{
16448     hash = size % N_HASH;
16449     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16450   }
16451 }
16452 
16453 /*
16454 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16455 ** at *pRoot.
16456 */
16457 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16458   assert( sqlite3_mutex_held(mem3.mutex) );
16459   mem3.aPool[i].u.list.next = *pRoot;
16460   mem3.aPool[i].u.list.prev = 0;
16461   if( *pRoot ){
16462     mem3.aPool[*pRoot].u.list.prev = i;
16463   }
16464   *pRoot = i;
16465 }
16466 
16467 /*
16468 ** Link the chunk at index i into either the appropriate
16469 ** small chunk list, or into the large chunk hash table.
16470 */
16471 static void memsys3Link(u32 i){
16472   u32 size, hash;
16473   assert( sqlite3_mutex_held(mem3.mutex) );
16474   assert( i>=1 );
16475   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16476   size = mem3.aPool[i-1].u.hdr.size4x/4;
16477   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16478   assert( size>=2 );
16479   if( size <= MX_SMALL ){
16480     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16481   }else{
16482     hash = size % N_HASH;
16483     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16484   }
16485 }
16486 
16487 /*
16488 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16489 ** will already be held (obtained by code in malloc.c) if
16490 ** sqlite3GlobalConfig.bMemStat is true.
16491 */
16492 static void memsys3Enter(void){
16493   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16494     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16495   }
16496   sqlite3_mutex_enter(mem3.mutex);
16497 }
16498 static void memsys3Leave(void){
16499   sqlite3_mutex_leave(mem3.mutex);
16500 }
16501 
16502 /*
16503 ** Called when we are unable to satisfy an allocation of nBytes.
16504 */
16505 static void memsys3OutOfMemory(int nByte){
16506   if( !mem3.alarmBusy ){
16507     mem3.alarmBusy = 1;
16508     assert( sqlite3_mutex_held(mem3.mutex) );
16509     sqlite3_mutex_leave(mem3.mutex);
16510     sqlite3_release_memory(nByte);
16511     sqlite3_mutex_enter(mem3.mutex);
16512     mem3.alarmBusy = 0;
16513   }
16514 }
16515 
16516 
16517 /*
16518 ** Chunk i is a free chunk that has been unlinked.  Adjust its
16519 ** size parameters for check-out and return a pointer to the
16520 ** user portion of the chunk.
16521 */
16522 static void *memsys3Checkout(u32 i, u32 nBlock){
16523   u32 x;
16524   assert( sqlite3_mutex_held(mem3.mutex) );
16525   assert( i>=1 );
16526   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16527   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16528   x = mem3.aPool[i-1].u.hdr.size4x;
16529   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16530   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16531   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16532   return &mem3.aPool[i];
16533 }
16534 
16535 /*
16536 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16537 ** Return a pointer to the new allocation.  Or, if the master chunk
16538 ** is not large enough, return 0.
16539 */
16540 static void *memsys3FromMaster(u32 nBlock){
16541   assert( sqlite3_mutex_held(mem3.mutex) );
16542   assert( mem3.szMaster>=nBlock );
16543   if( nBlock>=mem3.szMaster-1 ){
16544     /* Use the entire master */
16545     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16546     mem3.iMaster = 0;
16547     mem3.szMaster = 0;
16548     mem3.mnMaster = 0;
16549     return p;
16550   }else{
16551     /* Split the master block.  Return the tail. */
16552     u32 newi, x;
16553     newi = mem3.iMaster + mem3.szMaster - nBlock;
16554     assert( newi > mem3.iMaster+1 );
16555     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16556     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16557     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16558     mem3.szMaster -= nBlock;
16559     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16560     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16561     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16562     if( mem3.szMaster < mem3.mnMaster ){
16563       mem3.mnMaster = mem3.szMaster;
16564     }
16565     return (void*)&mem3.aPool[newi];
16566   }
16567 }
16568 
16569 /*
16570 ** *pRoot is the head of a list of free chunks of the same size
16571 ** or same size hash.  In other words, *pRoot is an entry in either
16572 ** mem3.aiSmall[] or mem3.aiHash[].
16573 **
16574 ** This routine examines all entries on the given list and tries
16575 ** to coalesce each entries with adjacent free chunks.
16576 **
16577 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
16578 ** the current mem3.iMaster with the new larger chunk.  In order for
16579 ** this mem3.iMaster replacement to work, the master chunk must be
16580 ** linked into the hash tables.  That is not the normal state of
16581 ** affairs, of course.  The calling routine must link the master
16582 ** chunk before invoking this routine, then must unlink the (possibly
16583 ** changed) master chunk once this routine has finished.
16584 */
16585 static void memsys3Merge(u32 *pRoot){
16586   u32 iNext, prev, size, i, x;
16587 
16588   assert( sqlite3_mutex_held(mem3.mutex) );
16589   for(i=*pRoot; i>0; i=iNext){
16590     iNext = mem3.aPool[i].u.list.next;
16591     size = mem3.aPool[i-1].u.hdr.size4x;
16592     assert( (size&1)==0 );
16593     if( (size&2)==0 ){
16594       memsys3UnlinkFromList(i, pRoot);
16595       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16596       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16597       if( prev==iNext ){
16598         iNext = mem3.aPool[prev].u.list.next;
16599       }
16600       memsys3Unlink(prev);
16601       size = i + size/4 - prev;
16602       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16603       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16604       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16605       memsys3Link(prev);
16606       i = prev;
16607     }else{
16608       size /= 4;
16609     }
16610     if( size>mem3.szMaster ){
16611       mem3.iMaster = i;
16612       mem3.szMaster = size;
16613     }
16614   }
16615 }
16616 
16617 /*
16618 ** Return a block of memory of at least nBytes in size.
16619 ** Return NULL if unable.
16620 **
16621 ** This function assumes that the necessary mutexes, if any, are
16622 ** already held by the caller. Hence "Unsafe".
16623 */
16624 static void *memsys3MallocUnsafe(int nByte){
16625   u32 i;
16626   u32 nBlock;
16627   u32 toFree;
16628 
16629   assert( sqlite3_mutex_held(mem3.mutex) );
16630   assert( sizeof(Mem3Block)==8 );
16631   if( nByte<=12 ){
16632     nBlock = 2;
16633   }else{
16634     nBlock = (nByte + 11)/8;
16635   }
16636   assert( nBlock>=2 );
16637 
16638   /* STEP 1:
16639   ** Look for an entry of the correct size in either the small
16640   ** chunk table or in the large chunk hash table.  This is
16641   ** successful most of the time (about 9 times out of 10).
16642   */
16643   if( nBlock <= MX_SMALL ){
16644     i = mem3.aiSmall[nBlock-2];
16645     if( i>0 ){
16646       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16647       return memsys3Checkout(i, nBlock);
16648     }
16649   }else{
16650     int hash = nBlock % N_HASH;
16651     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16652       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16653         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16654         return memsys3Checkout(i, nBlock);
16655       }
16656     }
16657   }
16658 
16659   /* STEP 2:
16660   ** Try to satisfy the allocation by carving a piece off of the end
16661   ** of the master chunk.  This step usually works if step 1 fails.
16662   */
16663   if( mem3.szMaster>=nBlock ){
16664     return memsys3FromMaster(nBlock);
16665   }
16666 
16667 
16668   /* STEP 3:
16669   ** Loop through the entire memory pool.  Coalesce adjacent free
16670   ** chunks.  Recompute the master chunk as the largest free chunk.
16671   ** Then try again to satisfy the allocation by carving a piece off
16672   ** of the end of the master chunk.  This step happens very
16673   ** rarely (we hope!)
16674   */
16675   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16676     memsys3OutOfMemory(toFree);
16677     if( mem3.iMaster ){
16678       memsys3Link(mem3.iMaster);
16679       mem3.iMaster = 0;
16680       mem3.szMaster = 0;
16681     }
16682     for(i=0; i<N_HASH; i++){
16683       memsys3Merge(&mem3.aiHash[i]);
16684     }
16685     for(i=0; i<MX_SMALL-1; i++){
16686       memsys3Merge(&mem3.aiSmall[i]);
16687     }
16688     if( mem3.szMaster ){
16689       memsys3Unlink(mem3.iMaster);
16690       if( mem3.szMaster>=nBlock ){
16691         return memsys3FromMaster(nBlock);
16692       }
16693     }
16694   }
16695 
16696   /* If none of the above worked, then we fail. */
16697   return 0;
16698 }
16699 
16700 /*
16701 ** Free an outstanding memory allocation.
16702 **
16703 ** This function assumes that the necessary mutexes, if any, are
16704 ** already held by the caller. Hence "Unsafe".
16705 */
16706 static void memsys3FreeUnsafe(void *pOld){
16707   Mem3Block *p = (Mem3Block*)pOld;
16708   int i;
16709   u32 size, x;
16710   assert( sqlite3_mutex_held(mem3.mutex) );
16711   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16712   i = p - mem3.aPool;
16713   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16714   size = mem3.aPool[i-1].u.hdr.size4x/4;
16715   assert( i+size<=mem3.nPool+1 );
16716   mem3.aPool[i-1].u.hdr.size4x &= ~1;
16717   mem3.aPool[i+size-1].u.hdr.prevSize = size;
16718   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16719   memsys3Link(i);
16720 
16721   /* Try to expand the master using the newly freed chunk */
16722   if( mem3.iMaster ){
16723     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16724       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16725       mem3.iMaster -= size;
16726       mem3.szMaster += size;
16727       memsys3Unlink(mem3.iMaster);
16728       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16729       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16730       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16731     }
16732     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16733     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16734       memsys3Unlink(mem3.iMaster+mem3.szMaster);
16735       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16736       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16737       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16738     }
16739   }
16740 }
16741 
16742 /*
16743 ** Return the size of an outstanding allocation, in bytes.  The
16744 ** size returned omits the 8-byte header overhead.  This only
16745 ** works for chunks that are currently checked out.
16746 */
16747 static int memsys3Size(void *p){
16748   Mem3Block *pBlock;
16749   if( p==0 ) return 0;
16750   pBlock = (Mem3Block*)p;
16751   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16752   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16753 }
16754 
16755 /*
16756 ** Round up a request size to the next valid allocation size.
16757 */
16758 static int memsys3Roundup(int n){
16759   if( n<=12 ){
16760     return 12;
16761   }else{
16762     return ((n+11)&~7) - 4;
16763   }
16764 }
16765 
16766 /*
16767 ** Allocate nBytes of memory.
16768 */
16769 static void *memsys3Malloc(int nBytes){
16770   sqlite3_int64 *p;
16771   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16772   memsys3Enter();
16773   p = memsys3MallocUnsafe(nBytes);
16774   memsys3Leave();
16775   return (void*)p;
16776 }
16777 
16778 /*
16779 ** Free memory.
16780 */
16781 static void memsys3Free(void *pPrior){
16782   assert( pPrior );
16783   memsys3Enter();
16784   memsys3FreeUnsafe(pPrior);
16785   memsys3Leave();
16786 }
16787 
16788 /*
16789 ** Change the size of an existing memory allocation
16790 */
16791 static void *memsys3Realloc(void *pPrior, int nBytes){
16792   int nOld;
16793   void *p;
16794   if( pPrior==0 ){
16795     return sqlite3_malloc(nBytes);
16796   }
16797   if( nBytes<=0 ){
16798     sqlite3_free(pPrior);
16799     return 0;
16800   }
16801   nOld = memsys3Size(pPrior);
16802   if( nBytes<=nOld && nBytes>=nOld-128 ){
16803     return pPrior;
16804   }
16805   memsys3Enter();
16806   p = memsys3MallocUnsafe(nBytes);
16807   if( p ){
16808     if( nOld<nBytes ){
16809       memcpy(p, pPrior, nOld);
16810     }else{
16811       memcpy(p, pPrior, nBytes);
16812     }
16813     memsys3FreeUnsafe(pPrior);
16814   }
16815   memsys3Leave();
16816   return p;
16817 }
16818 
16819 /*
16820 ** Initialize this module.
16821 */
16822 static int memsys3Init(void *NotUsed){
16823   UNUSED_PARAMETER(NotUsed);
16824   if( !sqlite3GlobalConfig.pHeap ){
16825     return SQLITE_ERROR;
16826   }
16827 
16828   /* Store a pointer to the memory block in global structure mem3. */
16829   assert( sizeof(Mem3Block)==8 );
16830   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16831   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16832 
16833   /* Initialize the master block. */
16834   mem3.szMaster = mem3.nPool;
16835   mem3.mnMaster = mem3.szMaster;
16836   mem3.iMaster = 1;
16837   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16838   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16839   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16840 
16841   return SQLITE_OK;
16842 }
16843 
16844 /*
16845 ** Deinitialize this module.
16846 */
16847 static void memsys3Shutdown(void *NotUsed){
16848   UNUSED_PARAMETER(NotUsed);
16849   mem3.mutex = 0;
16850   return;
16851 }
16852 
16853 
16854 
16855 /*
16856 ** Open the file indicated and write a log of all unfreed memory
16857 ** allocations into that log.
16858 */
16859 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16860 #ifdef SQLITE_DEBUG
16861   FILE *out;
16862   u32 i, j;
16863   u32 size;
16864   if( zFilename==0 || zFilename[0]==0 ){
16865     out = stdout;
16866   }else{
16867     out = fopen(zFilename, "w");
16868     if( out==0 ){
16869       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16870                       zFilename);
16871       return;
16872     }
16873   }
16874   memsys3Enter();
16875   fprintf(out, "CHUNKS:\n");
16876   for(i=1; i<=mem3.nPool; i+=size/4){
16877     size = mem3.aPool[i-1].u.hdr.size4x;
16878     if( size/4<=1 ){
16879       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16880       assert( 0 );
16881       break;
16882     }
16883     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16884       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16885       assert( 0 );
16886       break;
16887     }
16888     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16889       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16890       assert( 0 );
16891       break;
16892     }
16893     if( size&1 ){
16894       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16895     }else{
16896       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16897                   i==mem3.iMaster ? " **master**" : "");
16898     }
16899   }
16900   for(i=0; i<MX_SMALL-1; i++){
16901     if( mem3.aiSmall[i]==0 ) continue;
16902     fprintf(out, "small(%2d):", i);
16903     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16904       fprintf(out, " %p(%d)", &mem3.aPool[j],
16905               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16906     }
16907     fprintf(out, "\n");
16908   }
16909   for(i=0; i<N_HASH; i++){
16910     if( mem3.aiHash[i]==0 ) continue;
16911     fprintf(out, "hash(%2d):", i);
16912     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16913       fprintf(out, " %p(%d)", &mem3.aPool[j],
16914               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16915     }
16916     fprintf(out, "\n");
16917   }
16918   fprintf(out, "master=%d\n", mem3.iMaster);
16919   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16920   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16921   sqlite3_mutex_leave(mem3.mutex);
16922   if( out==stdout ){
16923     fflush(stdout);
16924   }else{
16925     fclose(out);
16926   }
16927 #else
16928   UNUSED_PARAMETER(zFilename);
16929 #endif
16930 }
16931 
16932 /*
16933 ** This routine is the only routine in this file with external
16934 ** linkage.
16935 **
16936 ** Populate the low-level memory allocation function pointers in
16937 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16938 ** arguments specify the block of memory to manage.
16939 **
16940 ** This routine is only called by sqlite3_config(), and therefore
16941 ** is not required to be threadsafe (it is not).
16942 */
16943 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16944   static const sqlite3_mem_methods mempoolMethods = {
16945      memsys3Malloc,
16946      memsys3Free,
16947      memsys3Realloc,
16948      memsys3Size,
16949      memsys3Roundup,
16950      memsys3Init,
16951      memsys3Shutdown,
16952      0
16953   };
16954   return &mempoolMethods;
16955 }
16956 
16957 #endif /* SQLITE_ENABLE_MEMSYS3 */
16958 
16959 /************** End of mem3.c ************************************************/
16960 /************** Begin file mem5.c ********************************************/
16961 /*
16962 ** 2007 October 14
16963 **
16964 ** The author disclaims copyright to this source code.  In place of
16965 ** a legal notice, here is a blessing:
16966 **
16967 **    May you do good and not evil.
16968 **    May you find forgiveness for yourself and forgive others.
16969 **    May you share freely, never taking more than you give.
16970 **
16971 *************************************************************************
16972 ** This file contains the C functions that implement a memory
16973 ** allocation subsystem for use by SQLite.
16974 **
16975 ** This version of the memory allocation subsystem omits all
16976 ** use of malloc(). The application gives SQLite a block of memory
16977 ** before calling sqlite3_initialize() from which allocations
16978 ** are made and returned by the xMalloc() and xRealloc()
16979 ** implementations. Once sqlite3_initialize() has been called,
16980 ** the amount of memory available to SQLite is fixed and cannot
16981 ** be changed.
16982 **
16983 ** This version of the memory allocation subsystem is included
16984 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16985 **
16986 ** This memory allocator uses the following algorithm:
16987 **
16988 **   1.  All memory allocations sizes are rounded up to a power of 2.
16989 **
16990 **   2.  If two adjacent free blocks are the halves of a larger block,
16991 **       then the two blocks are coalesed into the single larger block.
16992 **
16993 **   3.  New memory is allocated from the first available free block.
16994 **
16995 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16996 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16997 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16998 **
16999 ** Let n be the size of the largest allocation divided by the minimum
17000 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
17001 ** be the maximum amount of memory ever outstanding at one time.  Let
17002 ** N be the total amount of memory available for allocation.  Robson
17003 ** proved that this memory allocator will never breakdown due to
17004 ** fragmentation as long as the following constraint holds:
17005 **
17006 **      N >=  M*(1 + log2(n)/2) - n + 1
17007 **
17008 ** The sqlite3_status() logic tracks the maximum values of n and M so
17009 ** that an application can, at any time, verify this constraint.
17010 */
17011 
17012 /*
17013 ** This version of the memory allocator is used only when
17014 ** SQLITE_ENABLE_MEMSYS5 is defined.
17015 */
17016 #ifdef SQLITE_ENABLE_MEMSYS5
17017 
17018 /*
17019 ** A minimum allocation is an instance of the following structure.
17020 ** Larger allocations are an array of these structures where the
17021 ** size of the array is a power of 2.
17022 **
17023 ** The size of this object must be a power of two.  That fact is
17024 ** verified in memsys5Init().
17025 */
17026 typedef struct Mem5Link Mem5Link;
17027 struct Mem5Link {
17028   int next;       /* Index of next free chunk */
17029   int prev;       /* Index of previous free chunk */
17030 };
17031 
17032 /*
17033 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17034 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17035 ** it is not actually possible to reach this limit.
17036 */
17037 #define LOGMAX 30
17038 
17039 /*
17040 ** Masks used for mem5.aCtrl[] elements.
17041 */
17042 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17043 #define CTRL_FREE     0x20    /* True if not checked out */
17044 
17045 /*
17046 ** All of the static variables used by this module are collected
17047 ** into a single structure named "mem5".  This is to keep the
17048 ** static variables organized and to reduce namespace pollution
17049 ** when this module is combined with other in the amalgamation.
17050 */
17051 static SQLITE_WSD struct Mem5Global {
17052   /*
17053   ** Memory available for allocation
17054   */
17055   int szAtom;      /* Smallest possible allocation in bytes */
17056   int nBlock;      /* Number of szAtom sized blocks in zPool */
17057   u8 *zPool;       /* Memory available to be allocated */
17058 
17059   /*
17060   ** Mutex to control access to the memory allocation subsystem.
17061   */
17062   sqlite3_mutex *mutex;
17063 
17064   /*
17065   ** Performance statistics
17066   */
17067   u64 nAlloc;         /* Total number of calls to malloc */
17068   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17069   u64 totalExcess;    /* Total internal fragmentation */
17070   u32 currentOut;     /* Current checkout, including internal fragmentation */
17071   u32 currentCount;   /* Current number of distinct checkouts */
17072   u32 maxOut;         /* Maximum instantaneous currentOut */
17073   u32 maxCount;       /* Maximum instantaneous currentCount */
17074   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17075 
17076   /*
17077   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17078   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17079   ** and so forth.
17080   */
17081   int aiFreelist[LOGMAX+1];
17082 
17083   /*
17084   ** Space for tracking which blocks are checked out and the size
17085   ** of each block.  One byte per block.
17086   */
17087   u8 *aCtrl;
17088 
17089 } mem5;
17090 
17091 /*
17092 ** Access the static variable through a macro for SQLITE_OMIT_WSD
17093 */
17094 #define mem5 GLOBAL(struct Mem5Global, mem5)
17095 
17096 /*
17097 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17098 ** structures, return a pointer to the idx-th such lik.
17099 */
17100 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17101 
17102 /*
17103 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17104 ** on.  It should be found on mem5.aiFreelist[iLogsize].
17105 */
17106 static void memsys5Unlink(int i, int iLogsize){
17107   int next, prev;
17108   assert( i>=0 && i<mem5.nBlock );
17109   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17110   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17111 
17112   next = MEM5LINK(i)->next;
17113   prev = MEM5LINK(i)->prev;
17114   if( prev<0 ){
17115     mem5.aiFreelist[iLogsize] = next;
17116   }else{
17117     MEM5LINK(prev)->next = next;
17118   }
17119   if( next>=0 ){
17120     MEM5LINK(next)->prev = prev;
17121   }
17122 }
17123 
17124 /*
17125 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17126 ** free list.
17127 */
17128 static void memsys5Link(int i, int iLogsize){
17129   int x;
17130   assert( sqlite3_mutex_held(mem5.mutex) );
17131   assert( i>=0 && i<mem5.nBlock );
17132   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17133   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17134 
17135   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17136   MEM5LINK(i)->prev = -1;
17137   if( x>=0 ){
17138     assert( x<mem5.nBlock );
17139     MEM5LINK(x)->prev = i;
17140   }
17141   mem5.aiFreelist[iLogsize] = i;
17142 }
17143 
17144 /*
17145 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17146 ** will already be held (obtained by code in malloc.c) if
17147 ** sqlite3GlobalConfig.bMemStat is true.
17148 */
17149 static void memsys5Enter(void){
17150   sqlite3_mutex_enter(mem5.mutex);
17151 }
17152 static void memsys5Leave(void){
17153   sqlite3_mutex_leave(mem5.mutex);
17154 }
17155 
17156 /*
17157 ** Return the size of an outstanding allocation, in bytes.  The
17158 ** size returned omits the 8-byte header overhead.  This only
17159 ** works for chunks that are currently checked out.
17160 */
17161 static int memsys5Size(void *p){
17162   int iSize = 0;
17163   if( p ){
17164     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17165     assert( i>=0 && i<mem5.nBlock );
17166     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17167   }
17168   return iSize;
17169 }
17170 
17171 /*
17172 ** Find the first entry on the freelist iLogsize.  Unlink that
17173 ** entry and return its index.
17174 */
17175 static int memsys5UnlinkFirst(int iLogsize){
17176   int i;
17177   int iFirst;
17178 
17179   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17180   i = iFirst = mem5.aiFreelist[iLogsize];
17181   assert( iFirst>=0 );
17182   while( i>0 ){
17183     if( i<iFirst ) iFirst = i;
17184     i = MEM5LINK(i)->next;
17185   }
17186   memsys5Unlink(iFirst, iLogsize);
17187   return iFirst;
17188 }
17189 
17190 /*
17191 ** Return a block of memory of at least nBytes in size.
17192 ** Return NULL if unable.  Return NULL if nBytes==0.
17193 **
17194 ** The caller guarantees that nByte positive.
17195 **
17196 ** The caller has obtained a mutex prior to invoking this
17197 ** routine so there is never any chance that two or more
17198 ** threads can be in this routine at the same time.
17199 */
17200 static void *memsys5MallocUnsafe(int nByte){
17201   int i;           /* Index of a mem5.aPool[] slot */
17202   int iBin;        /* Index into mem5.aiFreelist[] */
17203   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17204   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17205 
17206   /* nByte must be a positive */
17207   assert( nByte>0 );
17208 
17209   /* Keep track of the maximum allocation request.  Even unfulfilled
17210   ** requests are counted */
17211   if( (u32)nByte>mem5.maxRequest ){
17212     mem5.maxRequest = nByte;
17213   }
17214 
17215   /* Abort if the requested allocation size is larger than the largest
17216   ** power of two that we can represent using 32-bit signed integers.
17217   */
17218   if( nByte > 0x40000000 ){
17219     return 0;
17220   }
17221 
17222   /* Round nByte up to the next valid power of two */
17223   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17224 
17225   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17226   ** block.  If not, then split a block of the next larger power of
17227   ** two in order to create a new free block of size iLogsize.
17228   */
17229   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17230   if( iBin>LOGMAX ){
17231     testcase( sqlite3GlobalConfig.xLog!=0 );
17232     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17233     return 0;
17234   }
17235   i = memsys5UnlinkFirst(iBin);
17236   while( iBin>iLogsize ){
17237     int newSize;
17238 
17239     iBin--;
17240     newSize = 1 << iBin;
17241     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17242     memsys5Link(i+newSize, iBin);
17243   }
17244   mem5.aCtrl[i] = iLogsize;
17245 
17246   /* Update allocator performance statistics. */
17247   mem5.nAlloc++;
17248   mem5.totalAlloc += iFullSz;
17249   mem5.totalExcess += iFullSz - nByte;
17250   mem5.currentCount++;
17251   mem5.currentOut += iFullSz;
17252   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17253   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17254 
17255   /* Return a pointer to the allocated memory. */
17256   return (void*)&mem5.zPool[i*mem5.szAtom];
17257 }
17258 
17259 /*
17260 ** Free an outstanding memory allocation.
17261 */
17262 static void memsys5FreeUnsafe(void *pOld){
17263   u32 size, iLogsize;
17264   int iBlock;
17265 
17266   /* Set iBlock to the index of the block pointed to by pOld in
17267   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17268   */
17269   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17270 
17271   /* Check that the pointer pOld points to a valid, non-free block. */
17272   assert( iBlock>=0 && iBlock<mem5.nBlock );
17273   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17274   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17275 
17276   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17277   size = 1<<iLogsize;
17278   assert( iBlock+size-1<(u32)mem5.nBlock );
17279 
17280   mem5.aCtrl[iBlock] |= CTRL_FREE;
17281   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17282   assert( mem5.currentCount>0 );
17283   assert( mem5.currentOut>=(size*mem5.szAtom) );
17284   mem5.currentCount--;
17285   mem5.currentOut -= size*mem5.szAtom;
17286   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17287   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17288 
17289   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17290   while( ALWAYS(iLogsize<LOGMAX) ){
17291     int iBuddy;
17292     if( (iBlock>>iLogsize) & 1 ){
17293       iBuddy = iBlock - size;
17294     }else{
17295       iBuddy = iBlock + size;
17296     }
17297     assert( iBuddy>=0 );
17298     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17299     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17300     memsys5Unlink(iBuddy, iLogsize);
17301     iLogsize++;
17302     if( iBuddy<iBlock ){
17303       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17304       mem5.aCtrl[iBlock] = 0;
17305       iBlock = iBuddy;
17306     }else{
17307       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17308       mem5.aCtrl[iBuddy] = 0;
17309     }
17310     size *= 2;
17311   }
17312   memsys5Link(iBlock, iLogsize);
17313 }
17314 
17315 /*
17316 ** Allocate nBytes of memory
17317 */
17318 static void *memsys5Malloc(int nBytes){
17319   sqlite3_int64 *p = 0;
17320   if( nBytes>0 ){
17321     memsys5Enter();
17322     p = memsys5MallocUnsafe(nBytes);
17323     memsys5Leave();
17324   }
17325   return (void*)p;
17326 }
17327 
17328 /*
17329 ** Free memory.
17330 **
17331 ** The outer layer memory allocator prevents this routine from
17332 ** being called with pPrior==0.
17333 */
17334 static void memsys5Free(void *pPrior){
17335   assert( pPrior!=0 );
17336   memsys5Enter();
17337   memsys5FreeUnsafe(pPrior);
17338   memsys5Leave();
17339 }
17340 
17341 /*
17342 ** Change the size of an existing memory allocation.
17343 **
17344 ** The outer layer memory allocator prevents this routine from
17345 ** being called with pPrior==0.
17346 **
17347 ** nBytes is always a value obtained from a prior call to
17348 ** memsys5Round().  Hence nBytes is always a non-negative power
17349 ** of two.  If nBytes==0 that means that an oversize allocation
17350 ** (an allocation larger than 0x40000000) was requested and this
17351 ** routine should return 0 without freeing pPrior.
17352 */
17353 static void *memsys5Realloc(void *pPrior, int nBytes){
17354   int nOld;
17355   void *p;
17356   assert( pPrior!=0 );
17357   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17358   assert( nBytes>=0 );
17359   if( nBytes==0 ){
17360     return 0;
17361   }
17362   nOld = memsys5Size(pPrior);
17363   if( nBytes<=nOld ){
17364     return pPrior;
17365   }
17366   memsys5Enter();
17367   p = memsys5MallocUnsafe(nBytes);
17368   if( p ){
17369     memcpy(p, pPrior, nOld);
17370     memsys5FreeUnsafe(pPrior);
17371   }
17372   memsys5Leave();
17373   return p;
17374 }
17375 
17376 /*
17377 ** Round up a request size to the next valid allocation size.  If
17378 ** the allocation is too large to be handled by this allocation system,
17379 ** return 0.
17380 **
17381 ** All allocations must be a power of two and must be expressed by a
17382 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17383 ** or 1073741824 bytes.
17384 */
17385 static int memsys5Roundup(int n){
17386   int iFullSz;
17387   if( n > 0x40000000 ) return 0;
17388   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17389   return iFullSz;
17390 }
17391 
17392 /*
17393 ** Return the ceiling of the logarithm base 2 of iValue.
17394 **
17395 ** Examples:   memsys5Log(1) -> 0
17396 **             memsys5Log(2) -> 1
17397 **             memsys5Log(4) -> 2
17398 **             memsys5Log(5) -> 3
17399 **             memsys5Log(8) -> 3
17400 **             memsys5Log(9) -> 4
17401 */
17402 static int memsys5Log(int iValue){
17403   int iLog;
17404   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17405   return iLog;
17406 }
17407 
17408 /*
17409 ** Initialize the memory allocator.
17410 **
17411 ** This routine is not threadsafe.  The caller must be holding a mutex
17412 ** to prevent multiple threads from entering at the same time.
17413 */
17414 static int memsys5Init(void *NotUsed){
17415   int ii;            /* Loop counter */
17416   int nByte;         /* Number of bytes of memory available to this allocator */
17417   u8 *zByte;         /* Memory usable by this allocator */
17418   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17419   int iOffset;       /* An offset into mem5.aCtrl[] */
17420 
17421   UNUSED_PARAMETER(NotUsed);
17422 
17423   /* For the purposes of this routine, disable the mutex */
17424   mem5.mutex = 0;
17425 
17426   /* The size of a Mem5Link object must be a power of two.  Verify that
17427   ** this is case.
17428   */
17429   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17430 
17431   nByte = sqlite3GlobalConfig.nHeap;
17432   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17433   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17434 
17435   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17436   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17437   mem5.szAtom = (1<<nMinLog);
17438   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17439     mem5.szAtom = mem5.szAtom << 1;
17440   }
17441 
17442   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17443   mem5.zPool = zByte;
17444   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17445 
17446   for(ii=0; ii<=LOGMAX; ii++){
17447     mem5.aiFreelist[ii] = -1;
17448   }
17449 
17450   iOffset = 0;
17451   for(ii=LOGMAX; ii>=0; ii--){
17452     int nAlloc = (1<<ii);
17453     if( (iOffset+nAlloc)<=mem5.nBlock ){
17454       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17455       memsys5Link(iOffset, ii);
17456       iOffset += nAlloc;
17457     }
17458     assert((iOffset+nAlloc)>mem5.nBlock);
17459   }
17460 
17461   /* If a mutex is required for normal operation, allocate one */
17462   if( sqlite3GlobalConfig.bMemstat==0 ){
17463     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17464   }
17465 
17466   return SQLITE_OK;
17467 }
17468 
17469 /*
17470 ** Deinitialize this module.
17471 */
17472 static void memsys5Shutdown(void *NotUsed){
17473   UNUSED_PARAMETER(NotUsed);
17474   mem5.mutex = 0;
17475   return;
17476 }
17477 
17478 #ifdef SQLITE_TEST
17479 /*
17480 ** Open the file indicated and write a log of all unfreed memory
17481 ** allocations into that log.
17482 */
17483 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17484   FILE *out;
17485   int i, j, n;
17486   int nMinLog;
17487 
17488   if( zFilename==0 || zFilename[0]==0 ){
17489     out = stdout;
17490   }else{
17491     out = fopen(zFilename, "w");
17492     if( out==0 ){
17493       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17494                       zFilename);
17495       return;
17496     }
17497   }
17498   memsys5Enter();
17499   nMinLog = memsys5Log(mem5.szAtom);
17500   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17501     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17502     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17503   }
17504   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17505   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17506   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17507   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17508   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17509   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17510   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17511   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17512   memsys5Leave();
17513   if( out==stdout ){
17514     fflush(stdout);
17515   }else{
17516     fclose(out);
17517   }
17518 }
17519 #endif
17520 
17521 /*
17522 ** This routine is the only routine in this file with external
17523 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17524 ** struct populated with the memsys5 methods.
17525 */
17526 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17527   static const sqlite3_mem_methods memsys5Methods = {
17528      memsys5Malloc,
17529      memsys5Free,
17530      memsys5Realloc,
17531      memsys5Size,
17532      memsys5Roundup,
17533      memsys5Init,
17534      memsys5Shutdown,
17535      0
17536   };
17537   return &memsys5Methods;
17538 }
17539 
17540 #endif /* SQLITE_ENABLE_MEMSYS5 */
17541 
17542 /************** End of mem5.c ************************************************/
17543 /************** Begin file mutex.c *******************************************/
17544 /*
17545 ** 2007 August 14
17546 **
17547 ** The author disclaims copyright to this source code.  In place of
17548 ** a legal notice, here is a blessing:
17549 **
17550 **    May you do good and not evil.
17551 **    May you find forgiveness for yourself and forgive others.
17552 **    May you share freely, never taking more than you give.
17553 **
17554 *************************************************************************
17555 ** This file contains the C functions that implement mutexes.
17556 **
17557 ** This file contains code that is common across all mutex implementations.
17558 */
17559 
17560 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17561 /*
17562 ** For debugging purposes, record when the mutex subsystem is initialized
17563 ** and uninitialized so that we can assert() if there is an attempt to
17564 ** allocate a mutex while the system is uninitialized.
17565 */
17566 static SQLITE_WSD int mutexIsInit = 0;
17567 #endif /* SQLITE_DEBUG */
17568 
17569 
17570 #ifndef SQLITE_MUTEX_OMIT
17571 /*
17572 ** Initialize the mutex system.
17573 */
17574 SQLITE_PRIVATE int sqlite3MutexInit(void){
17575   int rc = SQLITE_OK;
17576   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17577     /* If the xMutexAlloc method has not been set, then the user did not
17578     ** install a mutex implementation via sqlite3_config() prior to
17579     ** sqlite3_initialize() being called. This block copies pointers to
17580     ** the default implementation into the sqlite3GlobalConfig structure.
17581     */
17582     sqlite3_mutex_methods const *pFrom;
17583     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17584 
17585     if( sqlite3GlobalConfig.bCoreMutex ){
17586       pFrom = sqlite3DefaultMutex();
17587     }else{
17588       pFrom = sqlite3NoopMutex();
17589     }
17590     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17591     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17592            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17593     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17594   }
17595   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17596 
17597 #ifdef SQLITE_DEBUG
17598   GLOBAL(int, mutexIsInit) = 1;
17599 #endif
17600 
17601   return rc;
17602 }
17603 
17604 /*
17605 ** Shutdown the mutex system. This call frees resources allocated by
17606 ** sqlite3MutexInit().
17607 */
17608 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17609   int rc = SQLITE_OK;
17610   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17611     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17612   }
17613 
17614 #ifdef SQLITE_DEBUG
17615   GLOBAL(int, mutexIsInit) = 0;
17616 #endif
17617 
17618   return rc;
17619 }
17620 
17621 /*
17622 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17623 */
17624 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17625 #ifndef SQLITE_OMIT_AUTOINIT
17626   if( sqlite3_initialize() ) return 0;
17627 #endif
17628   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17629 }
17630 
17631 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17632   if( !sqlite3GlobalConfig.bCoreMutex ){
17633     return 0;
17634   }
17635   assert( GLOBAL(int, mutexIsInit) );
17636   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17637 }
17638 
17639 /*
17640 ** Free a dynamic mutex.
17641 */
17642 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17643   if( p ){
17644     sqlite3GlobalConfig.mutex.xMutexFree(p);
17645   }
17646 }
17647 
17648 /*
17649 ** Obtain the mutex p. If some other thread already has the mutex, block
17650 ** until it can be obtained.
17651 */
17652 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17653   if( p ){
17654     sqlite3GlobalConfig.mutex.xMutexEnter(p);
17655   }
17656 }
17657 
17658 /*
17659 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17660 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17661 */
17662 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17663   int rc = SQLITE_OK;
17664   if( p ){
17665     return sqlite3GlobalConfig.mutex.xMutexTry(p);
17666   }
17667   return rc;
17668 }
17669 
17670 /*
17671 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17672 ** entered by the same thread.  The behavior is undefined if the mutex
17673 ** is not currently entered. If a NULL pointer is passed as an argument
17674 ** this function is a no-op.
17675 */
17676 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17677   if( p ){
17678     sqlite3GlobalConfig.mutex.xMutexLeave(p);
17679   }
17680 }
17681 
17682 #ifndef NDEBUG
17683 /*
17684 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17685 ** intended for use inside assert() statements.
17686 */
17687 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17688   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17689 }
17690 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17691   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17692 }
17693 #endif
17694 
17695 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17696 
17697 /************** End of mutex.c ***********************************************/
17698 /************** Begin file mutex_noop.c **************************************/
17699 /*
17700 ** 2008 October 07
17701 **
17702 ** The author disclaims copyright to this source code.  In place of
17703 ** a legal notice, here is a blessing:
17704 **
17705 **    May you do good and not evil.
17706 **    May you find forgiveness for yourself and forgive others.
17707 **    May you share freely, never taking more than you give.
17708 **
17709 *************************************************************************
17710 ** This file contains the C functions that implement mutexes.
17711 **
17712 ** This implementation in this file does not provide any mutual
17713 ** exclusion and is thus suitable for use only in applications
17714 ** that use SQLite in a single thread.  The routines defined
17715 ** here are place-holders.  Applications can substitute working
17716 ** mutex routines at start-time using the
17717 **
17718 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17719 **
17720 ** interface.
17721 **
17722 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17723 ** that does error checking on mutexes to make sure they are being
17724 ** called correctly.
17725 */
17726 
17727 #ifndef SQLITE_MUTEX_OMIT
17728 
17729 #ifndef SQLITE_DEBUG
17730 /*
17731 ** Stub routines for all mutex methods.
17732 **
17733 ** This routines provide no mutual exclusion or error checking.
17734 */
17735 static int noopMutexInit(void){ return SQLITE_OK; }
17736 static int noopMutexEnd(void){ return SQLITE_OK; }
17737 static sqlite3_mutex *noopMutexAlloc(int id){
17738   UNUSED_PARAMETER(id);
17739   return (sqlite3_mutex*)8;
17740 }
17741 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17742 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17743 static int noopMutexTry(sqlite3_mutex *p){
17744   UNUSED_PARAMETER(p);
17745   return SQLITE_OK;
17746 }
17747 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17748 
17749 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17750   static const sqlite3_mutex_methods sMutex = {
17751     noopMutexInit,
17752     noopMutexEnd,
17753     noopMutexAlloc,
17754     noopMutexFree,
17755     noopMutexEnter,
17756     noopMutexTry,
17757     noopMutexLeave,
17758 
17759     0,
17760     0,
17761   };
17762 
17763   return &sMutex;
17764 }
17765 #endif /* !SQLITE_DEBUG */
17766 
17767 #ifdef SQLITE_DEBUG
17768 /*
17769 ** In this implementation, error checking is provided for testing
17770 ** and debugging purposes.  The mutexes still do not provide any
17771 ** mutual exclusion.
17772 */
17773 
17774 /*
17775 ** The mutex object
17776 */
17777 typedef struct sqlite3_debug_mutex {
17778   int id;     /* The mutex type */
17779   int cnt;    /* Number of entries without a matching leave */
17780 } sqlite3_debug_mutex;
17781 
17782 /*
17783 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17784 ** intended for use inside assert() statements.
17785 */
17786 static int debugMutexHeld(sqlite3_mutex *pX){
17787   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17788   return p==0 || p->cnt>0;
17789 }
17790 static int debugMutexNotheld(sqlite3_mutex *pX){
17791   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17792   return p==0 || p->cnt==0;
17793 }
17794 
17795 /*
17796 ** Initialize and deinitialize the mutex subsystem.
17797 */
17798 static int debugMutexInit(void){ return SQLITE_OK; }
17799 static int debugMutexEnd(void){ return SQLITE_OK; }
17800 
17801 /*
17802 ** The sqlite3_mutex_alloc() routine allocates a new
17803 ** mutex and returns a pointer to it.  If it returns NULL
17804 ** that means that a mutex could not be allocated.
17805 */
17806 static sqlite3_mutex *debugMutexAlloc(int id){
17807   static sqlite3_debug_mutex aStatic[6];
17808   sqlite3_debug_mutex *pNew = 0;
17809   switch( id ){
17810     case SQLITE_MUTEX_FAST:
17811     case SQLITE_MUTEX_RECURSIVE: {
17812       pNew = sqlite3Malloc(sizeof(*pNew));
17813       if( pNew ){
17814         pNew->id = id;
17815         pNew->cnt = 0;
17816       }
17817       break;
17818     }
17819     default: {
17820       assert( id-2 >= 0 );
17821       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17822       pNew = &aStatic[id-2];
17823       pNew->id = id;
17824       break;
17825     }
17826   }
17827   return (sqlite3_mutex*)pNew;
17828 }
17829 
17830 /*
17831 ** This routine deallocates a previously allocated mutex.
17832 */
17833 static void debugMutexFree(sqlite3_mutex *pX){
17834   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17835   assert( p->cnt==0 );
17836   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17837   sqlite3_free(p);
17838 }
17839 
17840 /*
17841 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17842 ** to enter a mutex.  If another thread is already within the mutex,
17843 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17844 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17845 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17846 ** be entered multiple times by the same thread.  In such cases the,
17847 ** mutex must be exited an equal number of times before another thread
17848 ** can enter.  If the same thread tries to enter any other kind of mutex
17849 ** more than once, the behavior is undefined.
17850 */
17851 static void debugMutexEnter(sqlite3_mutex *pX){
17852   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17853   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17854   p->cnt++;
17855 }
17856 static int debugMutexTry(sqlite3_mutex *pX){
17857   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17858   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17859   p->cnt++;
17860   return SQLITE_OK;
17861 }
17862 
17863 /*
17864 ** The sqlite3_mutex_leave() routine exits a mutex that was
17865 ** previously entered by the same thread.  The behavior
17866 ** is undefined if the mutex is not currently entered or
17867 ** is not currently allocated.  SQLite will never do either.
17868 */
17869 static void debugMutexLeave(sqlite3_mutex *pX){
17870   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17871   assert( debugMutexHeld(pX) );
17872   p->cnt--;
17873   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17874 }
17875 
17876 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17877   static const sqlite3_mutex_methods sMutex = {
17878     debugMutexInit,
17879     debugMutexEnd,
17880     debugMutexAlloc,
17881     debugMutexFree,
17882     debugMutexEnter,
17883     debugMutexTry,
17884     debugMutexLeave,
17885 
17886     debugMutexHeld,
17887     debugMutexNotheld
17888   };
17889 
17890   return &sMutex;
17891 }
17892 #endif /* SQLITE_DEBUG */
17893 
17894 /*
17895 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17896 ** is used regardless of the run-time threadsafety setting.
17897 */
17898 #ifdef SQLITE_MUTEX_NOOP
17899 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17900   return sqlite3NoopMutex();
17901 }
17902 #endif /* defined(SQLITE_MUTEX_NOOP) */
17903 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17904 
17905 /************** End of mutex_noop.c ******************************************/
17906 /************** Begin file mutex_unix.c **************************************/
17907 /*
17908 ** 2007 August 28
17909 **
17910 ** The author disclaims copyright to this source code.  In place of
17911 ** a legal notice, here is a blessing:
17912 **
17913 **    May you do good and not evil.
17914 **    May you find forgiveness for yourself and forgive others.
17915 **    May you share freely, never taking more than you give.
17916 **
17917 *************************************************************************
17918 ** This file contains the C functions that implement mutexes for pthreads
17919 */
17920 
17921 /*
17922 ** The code in this file is only used if we are compiling threadsafe
17923 ** under unix with pthreads.
17924 **
17925 ** Note that this implementation requires a version of pthreads that
17926 ** supports recursive mutexes.
17927 */
17928 #ifdef SQLITE_MUTEX_PTHREADS
17929 
17930 #include <pthread.h>
17931 
17932 /*
17933 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17934 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17935 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17936 */
17937 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17938 # define SQLITE_MUTEX_NREF 1
17939 #else
17940 # define SQLITE_MUTEX_NREF 0
17941 #endif
17942 
17943 /*
17944 ** Each recursive mutex is an instance of the following structure.
17945 */
17946 struct sqlite3_mutex {
17947   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17948 #if SQLITE_MUTEX_NREF
17949   int id;                    /* Mutex type */
17950   volatile int nRef;         /* Number of entrances */
17951   volatile pthread_t owner;  /* Thread that is within this mutex */
17952   int trace;                 /* True to trace changes */
17953 #endif
17954 };
17955 #if SQLITE_MUTEX_NREF
17956 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17957 #else
17958 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17959 #endif
17960 
17961 /*
17962 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17963 ** intended for use only inside assert() statements.  On some platforms,
17964 ** there might be race conditions that can cause these routines to
17965 ** deliver incorrect results.  In particular, if pthread_equal() is
17966 ** not an atomic operation, then these routines might delivery
17967 ** incorrect results.  On most platforms, pthread_equal() is a
17968 ** comparison of two integers and is therefore atomic.  But we are
17969 ** told that HPUX is not such a platform.  If so, then these routines
17970 ** will not always work correctly on HPUX.
17971 **
17972 ** On those platforms where pthread_equal() is not atomic, SQLite
17973 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17974 ** make sure no assert() statements are evaluated and hence these
17975 ** routines are never called.
17976 */
17977 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17978 static int pthreadMutexHeld(sqlite3_mutex *p){
17979   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17980 }
17981 static int pthreadMutexNotheld(sqlite3_mutex *p){
17982   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17983 }
17984 #endif
17985 
17986 /*
17987 ** Initialize and deinitialize the mutex subsystem.
17988 */
17989 static int pthreadMutexInit(void){ return SQLITE_OK; }
17990 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17991 
17992 /*
17993 ** The sqlite3_mutex_alloc() routine allocates a new
17994 ** mutex and returns a pointer to it.  If it returns NULL
17995 ** that means that a mutex could not be allocated.  SQLite
17996 ** will unwind its stack and return an error.  The argument
17997 ** to sqlite3_mutex_alloc() is one of these integer constants:
17998 **
17999 ** <ul>
18000 ** <li>  SQLITE_MUTEX_FAST
18001 ** <li>  SQLITE_MUTEX_RECURSIVE
18002 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18003 ** <li>  SQLITE_MUTEX_STATIC_MEM
18004 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18005 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18006 ** <li>  SQLITE_MUTEX_STATIC_LRU
18007 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18008 ** </ul>
18009 **
18010 ** The first two constants cause sqlite3_mutex_alloc() to create
18011 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18012 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18013 ** The mutex implementation does not need to make a distinction
18014 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18015 ** not want to.  But SQLite will only request a recursive mutex in
18016 ** cases where it really needs one.  If a faster non-recursive mutex
18017 ** implementation is available on the host platform, the mutex subsystem
18018 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18019 **
18020 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18021 ** a pointer to a static preexisting mutex.  Six static mutexes are
18022 ** used by the current version of SQLite.  Future versions of SQLite
18023 ** may add additional static mutexes.  Static mutexes are for internal
18024 ** use by SQLite only.  Applications that use SQLite mutexes should
18025 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18026 ** SQLITE_MUTEX_RECURSIVE.
18027 **
18028 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18029 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18030 ** returns a different mutex on every call.  But for the static
18031 ** mutex types, the same mutex is returned on every call that has
18032 ** the same type number.
18033 */
18034 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18035   static sqlite3_mutex staticMutexes[] = {
18036     SQLITE3_MUTEX_INITIALIZER,
18037     SQLITE3_MUTEX_INITIALIZER,
18038     SQLITE3_MUTEX_INITIALIZER,
18039     SQLITE3_MUTEX_INITIALIZER,
18040     SQLITE3_MUTEX_INITIALIZER,
18041     SQLITE3_MUTEX_INITIALIZER
18042   };
18043   sqlite3_mutex *p;
18044   switch( iType ){
18045     case SQLITE_MUTEX_RECURSIVE: {
18046       p = sqlite3MallocZero( sizeof(*p) );
18047       if( p ){
18048 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18049         /* If recursive mutexes are not available, we will have to
18050         ** build our own.  See below. */
18051         pthread_mutex_init(&p->mutex, 0);
18052 #else
18053         /* Use a recursive mutex if it is available */
18054         pthread_mutexattr_t recursiveAttr;
18055         pthread_mutexattr_init(&recursiveAttr);
18056         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18057         pthread_mutex_init(&p->mutex, &recursiveAttr);
18058         pthread_mutexattr_destroy(&recursiveAttr);
18059 #endif
18060 #if SQLITE_MUTEX_NREF
18061         p->id = iType;
18062 #endif
18063       }
18064       break;
18065     }
18066     case SQLITE_MUTEX_FAST: {
18067       p = sqlite3MallocZero( sizeof(*p) );
18068       if( p ){
18069 #if SQLITE_MUTEX_NREF
18070         p->id = iType;
18071 #endif
18072         pthread_mutex_init(&p->mutex, 0);
18073       }
18074       break;
18075     }
18076     default: {
18077       assert( iType-2 >= 0 );
18078       assert( iType-2 < ArraySize(staticMutexes) );
18079       p = &staticMutexes[iType-2];
18080 #if SQLITE_MUTEX_NREF
18081       p->id = iType;
18082 #endif
18083       break;
18084     }
18085   }
18086   return p;
18087 }
18088 
18089 
18090 /*
18091 ** This routine deallocates a previously
18092 ** allocated mutex.  SQLite is careful to deallocate every
18093 ** mutex that it allocates.
18094 */
18095 static void pthreadMutexFree(sqlite3_mutex *p){
18096   assert( p->nRef==0 );
18097   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18098   pthread_mutex_destroy(&p->mutex);
18099   sqlite3_free(p);
18100 }
18101 
18102 /*
18103 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18104 ** to enter a mutex.  If another thread is already within the mutex,
18105 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18106 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18107 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18108 ** be entered multiple times by the same thread.  In such cases the,
18109 ** mutex must be exited an equal number of times before another thread
18110 ** can enter.  If the same thread tries to enter any other kind of mutex
18111 ** more than once, the behavior is undefined.
18112 */
18113 static void pthreadMutexEnter(sqlite3_mutex *p){
18114   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18115 
18116 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18117   /* If recursive mutexes are not available, then we have to grow
18118   ** our own.  This implementation assumes that pthread_equal()
18119   ** is atomic - that it cannot be deceived into thinking self
18120   ** and p->owner are equal if p->owner changes between two values
18121   ** that are not equal to self while the comparison is taking place.
18122   ** This implementation also assumes a coherent cache - that
18123   ** separate processes cannot read different values from the same
18124   ** address at the same time.  If either of these two conditions
18125   ** are not met, then the mutexes will fail and problems will result.
18126   */
18127   {
18128     pthread_t self = pthread_self();
18129     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18130       p->nRef++;
18131     }else{
18132       pthread_mutex_lock(&p->mutex);
18133       assert( p->nRef==0 );
18134       p->owner = self;
18135       p->nRef = 1;
18136     }
18137   }
18138 #else
18139   /* Use the built-in recursive mutexes if they are available.
18140   */
18141   pthread_mutex_lock(&p->mutex);
18142 #if SQLITE_MUTEX_NREF
18143   assert( p->nRef>0 || p->owner==0 );
18144   p->owner = pthread_self();
18145   p->nRef++;
18146 #endif
18147 #endif
18148 
18149 #ifdef SQLITE_DEBUG
18150   if( p->trace ){
18151     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18152   }
18153 #endif
18154 }
18155 static int pthreadMutexTry(sqlite3_mutex *p){
18156   int rc;
18157   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18158 
18159 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18160   /* If recursive mutexes are not available, then we have to grow
18161   ** our own.  This implementation assumes that pthread_equal()
18162   ** is atomic - that it cannot be deceived into thinking self
18163   ** and p->owner are equal if p->owner changes between two values
18164   ** that are not equal to self while the comparison is taking place.
18165   ** This implementation also assumes a coherent cache - that
18166   ** separate processes cannot read different values from the same
18167   ** address at the same time.  If either of these two conditions
18168   ** are not met, then the mutexes will fail and problems will result.
18169   */
18170   {
18171     pthread_t self = pthread_self();
18172     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18173       p->nRef++;
18174       rc = SQLITE_OK;
18175     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18176       assert( p->nRef==0 );
18177       p->owner = self;
18178       p->nRef = 1;
18179       rc = SQLITE_OK;
18180     }else{
18181       rc = SQLITE_BUSY;
18182     }
18183   }
18184 #else
18185   /* Use the built-in recursive mutexes if they are available.
18186   */
18187   if( pthread_mutex_trylock(&p->mutex)==0 ){
18188 #if SQLITE_MUTEX_NREF
18189     p->owner = pthread_self();
18190     p->nRef++;
18191 #endif
18192     rc = SQLITE_OK;
18193   }else{
18194     rc = SQLITE_BUSY;
18195   }
18196 #endif
18197 
18198 #ifdef SQLITE_DEBUG
18199   if( rc==SQLITE_OK && p->trace ){
18200     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18201   }
18202 #endif
18203   return rc;
18204 }
18205 
18206 /*
18207 ** The sqlite3_mutex_leave() routine exits a mutex that was
18208 ** previously entered by the same thread.  The behavior
18209 ** is undefined if the mutex is not currently entered or
18210 ** is not currently allocated.  SQLite will never do either.
18211 */
18212 static void pthreadMutexLeave(sqlite3_mutex *p){
18213   assert( pthreadMutexHeld(p) );
18214 #if SQLITE_MUTEX_NREF
18215   p->nRef--;
18216   if( p->nRef==0 ) p->owner = 0;
18217 #endif
18218   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18219 
18220 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18221   if( p->nRef==0 ){
18222     pthread_mutex_unlock(&p->mutex);
18223   }
18224 #else
18225   pthread_mutex_unlock(&p->mutex);
18226 #endif
18227 
18228 #ifdef SQLITE_DEBUG
18229   if( p->trace ){
18230     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18231   }
18232 #endif
18233 }
18234 
18235 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18236   static const sqlite3_mutex_methods sMutex = {
18237     pthreadMutexInit,
18238     pthreadMutexEnd,
18239     pthreadMutexAlloc,
18240     pthreadMutexFree,
18241     pthreadMutexEnter,
18242     pthreadMutexTry,
18243     pthreadMutexLeave,
18244 #ifdef SQLITE_DEBUG
18245     pthreadMutexHeld,
18246     pthreadMutexNotheld
18247 #else
18248     0,
18249     0
18250 #endif
18251   };
18252 
18253   return &sMutex;
18254 }
18255 
18256 #endif /* SQLITE_MUTEX_PTHREADS */
18257 
18258 /************** End of mutex_unix.c ******************************************/
18259 /************** Begin file mutex_w32.c ***************************************/
18260 /*
18261 ** 2007 August 14
18262 **
18263 ** The author disclaims copyright to this source code.  In place of
18264 ** a legal notice, here is a blessing:
18265 **
18266 **    May you do good and not evil.
18267 **    May you find forgiveness for yourself and forgive others.
18268 **    May you share freely, never taking more than you give.
18269 **
18270 *************************************************************************
18271 ** This file contains the C functions that implement mutexes for win32
18272 */
18273 
18274 /*
18275 ** The code in this file is only used if we are compiling multithreaded
18276 ** on a win32 system.
18277 */
18278 #ifdef SQLITE_MUTEX_W32
18279 
18280 /*
18281 ** Each recursive mutex is an instance of the following structure.
18282 */
18283 struct sqlite3_mutex {
18284   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18285   int id;                    /* Mutex type */
18286 #ifdef SQLITE_DEBUG
18287   volatile int nRef;         /* Number of enterances */
18288   volatile DWORD owner;      /* Thread holding this mutex */
18289   int trace;                 /* True to trace changes */
18290 #endif
18291 };
18292 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18293 #ifdef SQLITE_DEBUG
18294 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18295 #else
18296 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18297 #endif
18298 
18299 /*
18300 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18301 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18302 **
18303 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18304 ** the LockFileEx() API.  But we can still statically link against that
18305 ** API as long as we don't call it win running Win95/98/ME.  A call to
18306 ** this routine is used to determine if the host is Win95/98/ME or
18307 ** WinNT/2K/XP so that we will know whether or not we can safely call
18308 ** the LockFileEx() API.
18309 **
18310 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18311 ** which is only available if your application was compiled with
18312 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18313 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
18314 ** this out as well.
18315 */
18316 #if 0
18317 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18318 # define mutexIsNT()  (1)
18319 #else
18320   static int mutexIsNT(void){
18321     static int osType = 0;
18322     if( osType==0 ){
18323       OSVERSIONINFO sInfo;
18324       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18325       GetVersionEx(&sInfo);
18326       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18327     }
18328     return osType==2;
18329   }
18330 #endif /* SQLITE_OS_WINCE */
18331 #endif
18332 
18333 #ifdef SQLITE_DEBUG
18334 /*
18335 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18336 ** intended for use only inside assert() statements.
18337 */
18338 static int winMutexHeld(sqlite3_mutex *p){
18339   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18340 }
18341 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18342   return p->nRef==0 || p->owner!=tid;
18343 }
18344 static int winMutexNotheld(sqlite3_mutex *p){
18345   DWORD tid = GetCurrentThreadId();
18346   return winMutexNotheld2(p, tid);
18347 }
18348 #endif
18349 
18350 
18351 /*
18352 ** Initialize and deinitialize the mutex subsystem.
18353 */
18354 static sqlite3_mutex winMutex_staticMutexes[6] = {
18355   SQLITE3_MUTEX_INITIALIZER,
18356   SQLITE3_MUTEX_INITIALIZER,
18357   SQLITE3_MUTEX_INITIALIZER,
18358   SQLITE3_MUTEX_INITIALIZER,
18359   SQLITE3_MUTEX_INITIALIZER,
18360   SQLITE3_MUTEX_INITIALIZER
18361 };
18362 static int winMutex_isInit = 0;
18363 /* As winMutexInit() and winMutexEnd() are called as part
18364 ** of the sqlite3_initialize and sqlite3_shutdown()
18365 ** processing, the "interlocked" magic is probably not
18366 ** strictly necessary.
18367 */
18368 static long winMutex_lock = 0;
18369 
18370 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18371 
18372 static int winMutexInit(void){
18373   /* The first to increment to 1 does actual initialization */
18374   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18375     int i;
18376     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18377 #if SQLITE_OS_WINRT
18378       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18379 #else
18380       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18381 #endif
18382     }
18383     winMutex_isInit = 1;
18384   }else{
18385     /* Someone else is in the process of initing the static mutexes */
18386     while( !winMutex_isInit ){
18387       sqlite3_win32_sleep(1);
18388     }
18389   }
18390   return SQLITE_OK;
18391 }
18392 
18393 static int winMutexEnd(void){
18394   /* The first to decrement to 0 does actual shutdown
18395   ** (which should be the last to shutdown.) */
18396   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18397     if( winMutex_isInit==1 ){
18398       int i;
18399       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18400         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18401       }
18402       winMutex_isInit = 0;
18403     }
18404   }
18405   return SQLITE_OK;
18406 }
18407 
18408 /*
18409 ** The sqlite3_mutex_alloc() routine allocates a new
18410 ** mutex and returns a pointer to it.  If it returns NULL
18411 ** that means that a mutex could not be allocated.  SQLite
18412 ** will unwind its stack and return an error.  The argument
18413 ** to sqlite3_mutex_alloc() is one of these integer constants:
18414 **
18415 ** <ul>
18416 ** <li>  SQLITE_MUTEX_FAST
18417 ** <li>  SQLITE_MUTEX_RECURSIVE
18418 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18419 ** <li>  SQLITE_MUTEX_STATIC_MEM
18420 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18421 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18422 ** <li>  SQLITE_MUTEX_STATIC_LRU
18423 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18424 ** </ul>
18425 **
18426 ** The first two constants cause sqlite3_mutex_alloc() to create
18427 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18428 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18429 ** The mutex implementation does not need to make a distinction
18430 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18431 ** not want to.  But SQLite will only request a recursive mutex in
18432 ** cases where it really needs one.  If a faster non-recursive mutex
18433 ** implementation is available on the host platform, the mutex subsystem
18434 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18435 **
18436 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18437 ** a pointer to a static preexisting mutex.  Six static mutexes are
18438 ** used by the current version of SQLite.  Future versions of SQLite
18439 ** may add additional static mutexes.  Static mutexes are for internal
18440 ** use by SQLite only.  Applications that use SQLite mutexes should
18441 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18442 ** SQLITE_MUTEX_RECURSIVE.
18443 **
18444 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18445 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18446 ** returns a different mutex on every call.  But for the static
18447 ** mutex types, the same mutex is returned on every call that has
18448 ** the same type number.
18449 */
18450 static sqlite3_mutex *winMutexAlloc(int iType){
18451   sqlite3_mutex *p;
18452 
18453   switch( iType ){
18454     case SQLITE_MUTEX_FAST:
18455     case SQLITE_MUTEX_RECURSIVE: {
18456       p = sqlite3MallocZero( sizeof(*p) );
18457       if( p ){
18458 #ifdef SQLITE_DEBUG
18459         p->id = iType;
18460 #endif
18461 #if SQLITE_OS_WINRT
18462         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18463 #else
18464         InitializeCriticalSection(&p->mutex);
18465 #endif
18466       }
18467       break;
18468     }
18469     default: {
18470       assert( winMutex_isInit==1 );
18471       assert( iType-2 >= 0 );
18472       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18473       p = &winMutex_staticMutexes[iType-2];
18474 #ifdef SQLITE_DEBUG
18475       p->id = iType;
18476 #endif
18477       break;
18478     }
18479   }
18480   return p;
18481 }
18482 
18483 
18484 /*
18485 ** This routine deallocates a previously
18486 ** allocated mutex.  SQLite is careful to deallocate every
18487 ** mutex that it allocates.
18488 */
18489 static void winMutexFree(sqlite3_mutex *p){
18490   assert( p );
18491   assert( p->nRef==0 && p->owner==0 );
18492   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18493   DeleteCriticalSection(&p->mutex);
18494   sqlite3_free(p);
18495 }
18496 
18497 /*
18498 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18499 ** to enter a mutex.  If another thread is already within the mutex,
18500 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18501 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18502 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18503 ** be entered multiple times by the same thread.  In such cases the,
18504 ** mutex must be exited an equal number of times before another thread
18505 ** can enter.  If the same thread tries to enter any other kind of mutex
18506 ** more than once, the behavior is undefined.
18507 */
18508 static void winMutexEnter(sqlite3_mutex *p){
18509 #ifdef SQLITE_DEBUG
18510   DWORD tid = GetCurrentThreadId();
18511   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18512 #endif
18513   EnterCriticalSection(&p->mutex);
18514 #ifdef SQLITE_DEBUG
18515   assert( p->nRef>0 || p->owner==0 );
18516   p->owner = tid;
18517   p->nRef++;
18518   if( p->trace ){
18519     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18520   }
18521 #endif
18522 }
18523 static int winMutexTry(sqlite3_mutex *p){
18524 #ifndef NDEBUG
18525   DWORD tid = GetCurrentThreadId();
18526 #endif
18527   int rc = SQLITE_BUSY;
18528   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18529   /*
18530   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18531   ** is used it is merely an optimization.  So it is OK for it to always
18532   ** fail.
18533   **
18534   ** The TryEnterCriticalSection() interface is only available on WinNT.
18535   ** And some windows compilers complain if you try to use it without
18536   ** first doing some #defines that prevent SQLite from building on Win98.
18537   ** For that reason, we will omit this optimization for now.  See
18538   ** ticket #2685.
18539   */
18540 #if 0
18541   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18542     p->owner = tid;
18543     p->nRef++;
18544     rc = SQLITE_OK;
18545   }
18546 #else
18547   UNUSED_PARAMETER(p);
18548 #endif
18549 #ifdef SQLITE_DEBUG
18550   if( rc==SQLITE_OK && p->trace ){
18551     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18552   }
18553 #endif
18554   return rc;
18555 }
18556 
18557 /*
18558 ** The sqlite3_mutex_leave() routine exits a mutex that was
18559 ** previously entered by the same thread.  The behavior
18560 ** is undefined if the mutex is not currently entered or
18561 ** is not currently allocated.  SQLite will never do either.
18562 */
18563 static void winMutexLeave(sqlite3_mutex *p){
18564 #ifndef NDEBUG
18565   DWORD tid = GetCurrentThreadId();
18566   assert( p->nRef>0 );
18567   assert( p->owner==tid );
18568   p->nRef--;
18569   if( p->nRef==0 ) p->owner = 0;
18570   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18571 #endif
18572   LeaveCriticalSection(&p->mutex);
18573 #ifdef SQLITE_DEBUG
18574   if( p->trace ){
18575     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18576   }
18577 #endif
18578 }
18579 
18580 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18581   static const sqlite3_mutex_methods sMutex = {
18582     winMutexInit,
18583     winMutexEnd,
18584     winMutexAlloc,
18585     winMutexFree,
18586     winMutexEnter,
18587     winMutexTry,
18588     winMutexLeave,
18589 #ifdef SQLITE_DEBUG
18590     winMutexHeld,
18591     winMutexNotheld
18592 #else
18593     0,
18594     0
18595 #endif
18596   };
18597 
18598   return &sMutex;
18599 }
18600 #endif /* SQLITE_MUTEX_W32 */
18601 
18602 /************** End of mutex_w32.c *******************************************/
18603 /************** Begin file malloc.c ******************************************/
18604 /*
18605 ** 2001 September 15
18606 **
18607 ** The author disclaims copyright to this source code.  In place of
18608 ** a legal notice, here is a blessing:
18609 **
18610 **    May you do good and not evil.
18611 **    May you find forgiveness for yourself and forgive others.
18612 **    May you share freely, never taking more than you give.
18613 **
18614 *************************************************************************
18615 **
18616 ** Memory allocation functions used throughout sqlite.
18617 */
18618 /* #include <stdarg.h> */
18619 
18620 /*
18621 ** Attempt to release up to n bytes of non-essential memory currently
18622 ** held by SQLite. An example of non-essential memory is memory used to
18623 ** cache database pages that are not currently in use.
18624 */
18625 SQLITE_API int sqlite3_release_memory(int n){
18626 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18627   return sqlite3PcacheReleaseMemory(n);
18628 #else
18629   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18630   ** is a no-op returning zero if SQLite is not compiled with
18631   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18632   UNUSED_PARAMETER(n);
18633   return 0;
18634 #endif
18635 }
18636 
18637 /*
18638 ** An instance of the following object records the location of
18639 ** each unused scratch buffer.
18640 */
18641 typedef struct ScratchFreeslot {
18642   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18643 } ScratchFreeslot;
18644 
18645 /*
18646 ** State information local to the memory allocation subsystem.
18647 */
18648 static SQLITE_WSD struct Mem0Global {
18649   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18650 
18651   /*
18652   ** The alarm callback and its arguments.  The mem0.mutex lock will
18653   ** be held while the callback is running.  Recursive calls into
18654   ** the memory subsystem are allowed, but no new callbacks will be
18655   ** issued.
18656   */
18657   sqlite3_int64 alarmThreshold;
18658   void (*alarmCallback)(void*, sqlite3_int64,int);
18659   void *alarmArg;
18660 
18661   /*
18662   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18663   ** (so that a range test can be used to determine if an allocation
18664   ** being freed came from pScratch) and a pointer to the list of
18665   ** unused scratch allocations.
18666   */
18667   void *pScratchEnd;
18668   ScratchFreeslot *pScratchFree;
18669   u32 nScratchFree;
18670 
18671   /*
18672   ** True if heap is nearly "full" where "full" is defined by the
18673   ** sqlite3_soft_heap_limit() setting.
18674   */
18675   int nearlyFull;
18676 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18677 
18678 #define mem0 GLOBAL(struct Mem0Global, mem0)
18679 
18680 /*
18681 ** This routine runs when the memory allocator sees that the
18682 ** total memory allocation is about to exceed the soft heap
18683 ** limit.
18684 */
18685 static void softHeapLimitEnforcer(
18686   void *NotUsed,
18687   sqlite3_int64 NotUsed2,
18688   int allocSize
18689 ){
18690   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18691   sqlite3_release_memory(allocSize);
18692 }
18693 
18694 /*
18695 ** Change the alarm callback
18696 */
18697 static int sqlite3MemoryAlarm(
18698   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18699   void *pArg,
18700   sqlite3_int64 iThreshold
18701 ){
18702   int nUsed;
18703   sqlite3_mutex_enter(mem0.mutex);
18704   mem0.alarmCallback = xCallback;
18705   mem0.alarmArg = pArg;
18706   mem0.alarmThreshold = iThreshold;
18707   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18708   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18709   sqlite3_mutex_leave(mem0.mutex);
18710   return SQLITE_OK;
18711 }
18712 
18713 #ifndef SQLITE_OMIT_DEPRECATED
18714 /*
18715 ** Deprecated external interface.  Internal/core SQLite code
18716 ** should call sqlite3MemoryAlarm.
18717 */
18718 SQLITE_API int sqlite3_memory_alarm(
18719   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18720   void *pArg,
18721   sqlite3_int64 iThreshold
18722 ){
18723   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18724 }
18725 #endif
18726 
18727 /*
18728 ** Set the soft heap-size limit for the library. Passing a zero or
18729 ** negative value indicates no limit.
18730 */
18731 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18732   sqlite3_int64 priorLimit;
18733   sqlite3_int64 excess;
18734 #ifndef SQLITE_OMIT_AUTOINIT
18735   int rc = sqlite3_initialize();
18736   if( rc ) return -1;
18737 #endif
18738   sqlite3_mutex_enter(mem0.mutex);
18739   priorLimit = mem0.alarmThreshold;
18740   sqlite3_mutex_leave(mem0.mutex);
18741   if( n<0 ) return priorLimit;
18742   if( n>0 ){
18743     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18744   }else{
18745     sqlite3MemoryAlarm(0, 0, 0);
18746   }
18747   excess = sqlite3_memory_used() - n;
18748   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18749   return priorLimit;
18750 }
18751 SQLITE_API void sqlite3_soft_heap_limit(int n){
18752   if( n<0 ) n = 0;
18753   sqlite3_soft_heap_limit64(n);
18754 }
18755 
18756 /*
18757 ** Initialize the memory allocation subsystem.
18758 */
18759 SQLITE_PRIVATE int sqlite3MallocInit(void){
18760   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18761     sqlite3MemSetDefault();
18762   }
18763   memset(&mem0, 0, sizeof(mem0));
18764   if( sqlite3GlobalConfig.bCoreMutex ){
18765     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18766   }
18767   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18768       && sqlite3GlobalConfig.nScratch>0 ){
18769     int i, n, sz;
18770     ScratchFreeslot *pSlot;
18771     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18772     sqlite3GlobalConfig.szScratch = sz;
18773     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18774     n = sqlite3GlobalConfig.nScratch;
18775     mem0.pScratchFree = pSlot;
18776     mem0.nScratchFree = n;
18777     for(i=0; i<n-1; i++){
18778       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18779       pSlot = pSlot->pNext;
18780     }
18781     pSlot->pNext = 0;
18782     mem0.pScratchEnd = (void*)&pSlot[1];
18783   }else{
18784     mem0.pScratchEnd = 0;
18785     sqlite3GlobalConfig.pScratch = 0;
18786     sqlite3GlobalConfig.szScratch = 0;
18787     sqlite3GlobalConfig.nScratch = 0;
18788   }
18789   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18790       || sqlite3GlobalConfig.nPage<1 ){
18791     sqlite3GlobalConfig.pPage = 0;
18792     sqlite3GlobalConfig.szPage = 0;
18793     sqlite3GlobalConfig.nPage = 0;
18794   }
18795   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18796 }
18797 
18798 /*
18799 ** Return true if the heap is currently under memory pressure - in other
18800 ** words if the amount of heap used is close to the limit set by
18801 ** sqlite3_soft_heap_limit().
18802 */
18803 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18804   return mem0.nearlyFull;
18805 }
18806 
18807 /*
18808 ** Deinitialize the memory allocation subsystem.
18809 */
18810 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18811   if( sqlite3GlobalConfig.m.xShutdown ){
18812     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18813   }
18814   memset(&mem0, 0, sizeof(mem0));
18815 }
18816 
18817 /*
18818 ** Return the amount of memory currently checked out.
18819 */
18820 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18821   int n, mx;
18822   sqlite3_int64 res;
18823   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18824   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18825   return res;
18826 }
18827 
18828 /*
18829 ** Return the maximum amount of memory that has ever been
18830 ** checked out since either the beginning of this process
18831 ** or since the most recent reset.
18832 */
18833 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18834   int n, mx;
18835   sqlite3_int64 res;
18836   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18837   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18838   return res;
18839 }
18840 
18841 /*
18842 ** Trigger the alarm
18843 */
18844 static void sqlite3MallocAlarm(int nByte){
18845   void (*xCallback)(void*,sqlite3_int64,int);
18846   sqlite3_int64 nowUsed;
18847   void *pArg;
18848   if( mem0.alarmCallback==0 ) return;
18849   xCallback = mem0.alarmCallback;
18850   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18851   pArg = mem0.alarmArg;
18852   mem0.alarmCallback = 0;
18853   sqlite3_mutex_leave(mem0.mutex);
18854   xCallback(pArg, nowUsed, nByte);
18855   sqlite3_mutex_enter(mem0.mutex);
18856   mem0.alarmCallback = xCallback;
18857   mem0.alarmArg = pArg;
18858 }
18859 
18860 /*
18861 ** Do a memory allocation with statistics and alarms.  Assume the
18862 ** lock is already held.
18863 */
18864 static int mallocWithAlarm(int n, void **pp){
18865   int nFull;
18866   void *p;
18867   assert( sqlite3_mutex_held(mem0.mutex) );
18868   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18869   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18870   if( mem0.alarmCallback!=0 ){
18871     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18872     if( nUsed >= mem0.alarmThreshold - nFull ){
18873       mem0.nearlyFull = 1;
18874       sqlite3MallocAlarm(nFull);
18875     }else{
18876       mem0.nearlyFull = 0;
18877     }
18878   }
18879   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18880 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18881   if( p==0 && mem0.alarmCallback ){
18882     sqlite3MallocAlarm(nFull);
18883     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18884   }
18885 #endif
18886   if( p ){
18887     nFull = sqlite3MallocSize(p);
18888     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18889     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18890   }
18891   *pp = p;
18892   return nFull;
18893 }
18894 
18895 /*
18896 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18897 ** assumes the memory subsystem has already been initialized.
18898 */
18899 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18900   void *p;
18901   if( n<=0               /* IMP: R-65312-04917 */
18902    || n>=0x7fffff00
18903   ){
18904     /* A memory allocation of a number of bytes which is near the maximum
18905     ** signed integer value might cause an integer overflow inside of the
18906     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18907     ** 255 bytes of overhead.  SQLite itself will never use anything near
18908     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18909     p = 0;
18910   }else if( sqlite3GlobalConfig.bMemstat ){
18911     sqlite3_mutex_enter(mem0.mutex);
18912     mallocWithAlarm(n, &p);
18913     sqlite3_mutex_leave(mem0.mutex);
18914   }else{
18915     p = sqlite3GlobalConfig.m.xMalloc(n);
18916   }
18917   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18918   return p;
18919 }
18920 
18921 /*
18922 ** This version of the memory allocation is for use by the application.
18923 ** First make sure the memory subsystem is initialized, then do the
18924 ** allocation.
18925 */
18926 SQLITE_API void *sqlite3_malloc(int n){
18927 #ifndef SQLITE_OMIT_AUTOINIT
18928   if( sqlite3_initialize() ) return 0;
18929 #endif
18930   return sqlite3Malloc(n);
18931 }
18932 
18933 /*
18934 ** Each thread may only have a single outstanding allocation from
18935 ** xScratchMalloc().  We verify this constraint in the single-threaded
18936 ** case by setting scratchAllocOut to 1 when an allocation
18937 ** is outstanding clearing it when the allocation is freed.
18938 */
18939 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18940 static int scratchAllocOut = 0;
18941 #endif
18942 
18943 
18944 /*
18945 ** Allocate memory that is to be used and released right away.
18946 ** This routine is similar to alloca() in that it is not intended
18947 ** for situations where the memory might be held long-term.  This
18948 ** routine is intended to get memory to old large transient data
18949 ** structures that would not normally fit on the stack of an
18950 ** embedded processor.
18951 */
18952 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18953   void *p;
18954   assert( n>0 );
18955 
18956   sqlite3_mutex_enter(mem0.mutex);
18957   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18958     p = mem0.pScratchFree;
18959     mem0.pScratchFree = mem0.pScratchFree->pNext;
18960     mem0.nScratchFree--;
18961     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18962     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18963     sqlite3_mutex_leave(mem0.mutex);
18964   }else{
18965     if( sqlite3GlobalConfig.bMemstat ){
18966       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18967       n = mallocWithAlarm(n, &p);
18968       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18969       sqlite3_mutex_leave(mem0.mutex);
18970     }else{
18971       sqlite3_mutex_leave(mem0.mutex);
18972       p = sqlite3GlobalConfig.m.xMalloc(n);
18973     }
18974     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18975   }
18976   assert( sqlite3_mutex_notheld(mem0.mutex) );
18977 
18978 
18979 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18980   /* Verify that no more than two scratch allocations per thread
18981   ** are outstanding at one time.  (This is only checked in the
18982   ** single-threaded case since checking in the multi-threaded case
18983   ** would be much more complicated.) */
18984   assert( scratchAllocOut<=1 );
18985   if( p ) scratchAllocOut++;
18986 #endif
18987 
18988   return p;
18989 }
18990 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18991   if( p ){
18992 
18993 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18994     /* Verify that no more than two scratch allocation per thread
18995     ** is outstanding at one time.  (This is only checked in the
18996     ** single-threaded case since checking in the multi-threaded case
18997     ** would be much more complicated.) */
18998     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18999     scratchAllocOut--;
19000 #endif
19001 
19002     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19003       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19004       ScratchFreeslot *pSlot;
19005       pSlot = (ScratchFreeslot*)p;
19006       sqlite3_mutex_enter(mem0.mutex);
19007       pSlot->pNext = mem0.pScratchFree;
19008       mem0.pScratchFree = pSlot;
19009       mem0.nScratchFree++;
19010       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19011       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19012       sqlite3_mutex_leave(mem0.mutex);
19013     }else{
19014       /* Release memory back to the heap */
19015       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19016       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19017       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19018       if( sqlite3GlobalConfig.bMemstat ){
19019         int iSize = sqlite3MallocSize(p);
19020         sqlite3_mutex_enter(mem0.mutex);
19021         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19022         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19023         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19024         sqlite3GlobalConfig.m.xFree(p);
19025         sqlite3_mutex_leave(mem0.mutex);
19026       }else{
19027         sqlite3GlobalConfig.m.xFree(p);
19028       }
19029     }
19030   }
19031 }
19032 
19033 /*
19034 ** TRUE if p is a lookaside memory allocation from db
19035 */
19036 #ifndef SQLITE_OMIT_LOOKASIDE
19037 static int isLookaside(sqlite3 *db, void *p){
19038   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19039 }
19040 #else
19041 #define isLookaside(A,B) 0
19042 #endif
19043 
19044 /*
19045 ** Return the size of a memory allocation previously obtained from
19046 ** sqlite3Malloc() or sqlite3_malloc().
19047 */
19048 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19049   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19050   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19051   return sqlite3GlobalConfig.m.xSize(p);
19052 }
19053 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19054   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19055   if( db && isLookaside(db, p) ){
19056     return db->lookaside.sz;
19057   }else{
19058     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19059     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19060     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19061     return sqlite3GlobalConfig.m.xSize(p);
19062   }
19063 }
19064 
19065 /*
19066 ** Free memory previously obtained from sqlite3Malloc().
19067 */
19068 SQLITE_API void sqlite3_free(void *p){
19069   if( p==0 ) return;  /* IMP: R-49053-54554 */
19070   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19071   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19072   if( sqlite3GlobalConfig.bMemstat ){
19073     sqlite3_mutex_enter(mem0.mutex);
19074     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19075     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19076     sqlite3GlobalConfig.m.xFree(p);
19077     sqlite3_mutex_leave(mem0.mutex);
19078   }else{
19079     sqlite3GlobalConfig.m.xFree(p);
19080   }
19081 }
19082 
19083 /*
19084 ** Free memory that might be associated with a particular database
19085 ** connection.
19086 */
19087 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19088   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19089   if( db ){
19090     if( db->pnBytesFreed ){
19091       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19092       return;
19093     }
19094     if( isLookaside(db, p) ){
19095       LookasideSlot *pBuf = (LookasideSlot*)p;
19096 #if SQLITE_DEBUG
19097       /* Trash all content in the buffer being freed */
19098       memset(p, 0xaa, db->lookaside.sz);
19099 #endif
19100       pBuf->pNext = db->lookaside.pFree;
19101       db->lookaside.pFree = pBuf;
19102       db->lookaside.nOut--;
19103       return;
19104     }
19105   }
19106   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19107   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19108   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19109   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19110   sqlite3_free(p);
19111 }
19112 
19113 /*
19114 ** Change the size of an existing memory allocation
19115 */
19116 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19117   int nOld, nNew, nDiff;
19118   void *pNew;
19119   if( pOld==0 ){
19120     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19121   }
19122   if( nBytes<=0 ){
19123     sqlite3_free(pOld); /* IMP: R-31593-10574 */
19124     return 0;
19125   }
19126   if( nBytes>=0x7fffff00 ){
19127     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19128     return 0;
19129   }
19130   nOld = sqlite3MallocSize(pOld);
19131   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19132   ** argument to xRealloc is always a value returned by a prior call to
19133   ** xRoundup. */
19134   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19135   if( nOld==nNew ){
19136     pNew = pOld;
19137   }else if( sqlite3GlobalConfig.bMemstat ){
19138     sqlite3_mutex_enter(mem0.mutex);
19139     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19140     nDiff = nNew - nOld;
19141     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19142           mem0.alarmThreshold-nDiff ){
19143       sqlite3MallocAlarm(nDiff);
19144     }
19145     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19146     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19147     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19148     if( pNew==0 && mem0.alarmCallback ){
19149       sqlite3MallocAlarm(nBytes);
19150       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19151     }
19152     if( pNew ){
19153       nNew = sqlite3MallocSize(pNew);
19154       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19155     }
19156     sqlite3_mutex_leave(mem0.mutex);
19157   }else{
19158     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19159   }
19160   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19161   return pNew;
19162 }
19163 
19164 /*
19165 ** The public interface to sqlite3Realloc.  Make sure that the memory
19166 ** subsystem is initialized prior to invoking sqliteRealloc.
19167 */
19168 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19169 #ifndef SQLITE_OMIT_AUTOINIT
19170   if( sqlite3_initialize() ) return 0;
19171 #endif
19172   return sqlite3Realloc(pOld, n);
19173 }
19174 
19175 
19176 /*
19177 ** Allocate and zero memory.
19178 */
19179 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19180   void *p = sqlite3Malloc(n);
19181   if( p ){
19182     memset(p, 0, n);
19183   }
19184   return p;
19185 }
19186 
19187 /*
19188 ** Allocate and zero memory.  If the allocation fails, make
19189 ** the mallocFailed flag in the connection pointer.
19190 */
19191 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19192   void *p = sqlite3DbMallocRaw(db, n);
19193   if( p ){
19194     memset(p, 0, n);
19195   }
19196   return p;
19197 }
19198 
19199 /*
19200 ** Allocate and zero memory.  If the allocation fails, make
19201 ** the mallocFailed flag in the connection pointer.
19202 **
19203 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19204 ** failure on the same database connection) then always return 0.
19205 ** Hence for a particular database connection, once malloc starts
19206 ** failing, it fails consistently until mallocFailed is reset.
19207 ** This is an important assumption.  There are many places in the
19208 ** code that do things like this:
19209 **
19210 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19211 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19212 **         if( b ) a[10] = 9;
19213 **
19214 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19215 ** that all prior mallocs (ex: "a") worked too.
19216 */
19217 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19218   void *p;
19219   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19220   assert( db==0 || db->pnBytesFreed==0 );
19221 #ifndef SQLITE_OMIT_LOOKASIDE
19222   if( db ){
19223     LookasideSlot *pBuf;
19224     if( db->mallocFailed ){
19225       return 0;
19226     }
19227     if( db->lookaside.bEnabled ){
19228       if( n>db->lookaside.sz ){
19229         db->lookaside.anStat[1]++;
19230       }else if( (pBuf = db->lookaside.pFree)==0 ){
19231         db->lookaside.anStat[2]++;
19232       }else{
19233         db->lookaside.pFree = pBuf->pNext;
19234         db->lookaside.nOut++;
19235         db->lookaside.anStat[0]++;
19236         if( db->lookaside.nOut>db->lookaside.mxOut ){
19237           db->lookaside.mxOut = db->lookaside.nOut;
19238         }
19239         return (void*)pBuf;
19240       }
19241     }
19242   }
19243 #else
19244   if( db && db->mallocFailed ){
19245     return 0;
19246   }
19247 #endif
19248   p = sqlite3Malloc(n);
19249   if( !p && db ){
19250     db->mallocFailed = 1;
19251   }
19252   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19253          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19254   return p;
19255 }
19256 
19257 /*
19258 ** Resize the block of memory pointed to by p to n bytes. If the
19259 ** resize fails, set the mallocFailed flag in the connection object.
19260 */
19261 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19262   void *pNew = 0;
19263   assert( db!=0 );
19264   assert( sqlite3_mutex_held(db->mutex) );
19265   if( db->mallocFailed==0 ){
19266     if( p==0 ){
19267       return sqlite3DbMallocRaw(db, n);
19268     }
19269     if( isLookaside(db, p) ){
19270       if( n<=db->lookaside.sz ){
19271         return p;
19272       }
19273       pNew = sqlite3DbMallocRaw(db, n);
19274       if( pNew ){
19275         memcpy(pNew, p, db->lookaside.sz);
19276         sqlite3DbFree(db, p);
19277       }
19278     }else{
19279       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19280       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19281       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19282       pNew = sqlite3_realloc(p, n);
19283       if( !pNew ){
19284         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19285         db->mallocFailed = 1;
19286       }
19287       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
19288             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19289     }
19290   }
19291   return pNew;
19292 }
19293 
19294 /*
19295 ** Attempt to reallocate p.  If the reallocation fails, then free p
19296 ** and set the mallocFailed flag in the database connection.
19297 */
19298 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19299   void *pNew;
19300   pNew = sqlite3DbRealloc(db, p, n);
19301   if( !pNew ){
19302     sqlite3DbFree(db, p);
19303   }
19304   return pNew;
19305 }
19306 
19307 /*
19308 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
19309 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19310 ** is because when memory debugging is turned on, these two functions are
19311 ** called via macros that record the current file and line number in the
19312 ** ThreadData structure.
19313 */
19314 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19315   char *zNew;
19316   size_t n;
19317   if( z==0 ){
19318     return 0;
19319   }
19320   n = sqlite3Strlen30(z) + 1;
19321   assert( (n&0x7fffffff)==n );
19322   zNew = sqlite3DbMallocRaw(db, (int)n);
19323   if( zNew ){
19324     memcpy(zNew, z, n);
19325   }
19326   return zNew;
19327 }
19328 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19329   char *zNew;
19330   if( z==0 ){
19331     return 0;
19332   }
19333   assert( (n&0x7fffffff)==n );
19334   zNew = sqlite3DbMallocRaw(db, n+1);
19335   if( zNew ){
19336     memcpy(zNew, z, n);
19337     zNew[n] = 0;
19338   }
19339   return zNew;
19340 }
19341 
19342 /*
19343 ** Create a string from the zFromat argument and the va_list that follows.
19344 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19345 ** point to that string.
19346 */
19347 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19348   va_list ap;
19349   char *z;
19350 
19351   va_start(ap, zFormat);
19352   z = sqlite3VMPrintf(db, zFormat, ap);
19353   va_end(ap);
19354   sqlite3DbFree(db, *pz);
19355   *pz = z;
19356 }
19357 
19358 
19359 /*
19360 ** This function must be called before exiting any API function (i.e.
19361 ** returning control to the user) that has called sqlite3_malloc or
19362 ** sqlite3_realloc.
19363 **
19364 ** The returned value is normally a copy of the second argument to this
19365 ** function. However, if a malloc() failure has occurred since the previous
19366 ** invocation SQLITE_NOMEM is returned instead.
19367 **
19368 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19369 ** then the connection error-code (the value returned by sqlite3_errcode())
19370 ** is set to SQLITE_NOMEM.
19371 */
19372 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19373   /* If the db handle is not NULL, then we must hold the connection handle
19374   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
19375   ** is unsafe, as is the call to sqlite3Error().
19376   */
19377   assert( !db || sqlite3_mutex_held(db->mutex) );
19378   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19379     sqlite3Error(db, SQLITE_NOMEM, 0);
19380     db->mallocFailed = 0;
19381     rc = SQLITE_NOMEM;
19382   }
19383   return rc & (db ? db->errMask : 0xff);
19384 }
19385 
19386 /************** End of malloc.c **********************************************/
19387 /************** Begin file printf.c ******************************************/
19388 /*
19389 ** The "printf" code that follows dates from the 1980's.  It is in
19390 ** the public domain.  The original comments are included here for
19391 ** completeness.  They are very out-of-date but might be useful as
19392 ** an historical reference.  Most of the "enhancements" have been backed
19393 ** out so that the functionality is now the same as standard printf().
19394 **
19395 **************************************************************************
19396 **
19397 ** This file contains code for a set of "printf"-like routines.  These
19398 ** routines format strings much like the printf() from the standard C
19399 ** library, though the implementation here has enhancements to support
19400 ** SQLlite.
19401 */
19402 
19403 /*
19404 ** Conversion types fall into various categories as defined by the
19405 ** following enumeration.
19406 */
19407 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19408 #define etFLOAT       2 /* Floating point.  %f */
19409 #define etEXP         3 /* Exponentional notation. %e and %E */
19410 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19411 #define etSIZE        5 /* Return number of characters processed so far. %n */
19412 #define etSTRING      6 /* Strings. %s */
19413 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19414 #define etPERCENT     8 /* Percent symbol. %% */
19415 #define etCHARX       9 /* Characters. %c */
19416 /* The rest are extensions, not normally found in printf() */
19417 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19418 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19419                           NULL pointers replaced by SQL NULL.  %Q */
19420 #define etTOKEN      12 /* a pointer to a Token structure */
19421 #define etSRCLIST    13 /* a pointer to a SrcList */
19422 #define etPOINTER    14 /* The %p conversion */
19423 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19424 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19425 
19426 #define etINVALID     0 /* Any unrecognized conversion type */
19427 
19428 
19429 /*
19430 ** An "etByte" is an 8-bit unsigned value.
19431 */
19432 typedef unsigned char etByte;
19433 
19434 /*
19435 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19436 ** by an instance of the following structure
19437 */
19438 typedef struct et_info {   /* Information about each format field */
19439   char fmttype;            /* The format field code letter */
19440   etByte base;             /* The base for radix conversion */
19441   etByte flags;            /* One or more of FLAG_ constants below */
19442   etByte type;             /* Conversion paradigm */
19443   etByte charset;          /* Offset into aDigits[] of the digits string */
19444   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19445 } et_info;
19446 
19447 /*
19448 ** Allowed values for et_info.flags
19449 */
19450 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19451 #define FLAG_INTERN  2     /* True if for internal use only */
19452 #define FLAG_STRING  4     /* Allow infinity precision */
19453 
19454 
19455 /*
19456 ** The following table is searched linearly, so it is good to put the
19457 ** most frequently used conversion types first.
19458 */
19459 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19460 static const char aPrefix[] = "-x0\000X0";
19461 static const et_info fmtinfo[] = {
19462   {  'd', 10, 1, etRADIX,      0,  0 },
19463   {  's',  0, 4, etSTRING,     0,  0 },
19464   {  'g',  0, 1, etGENERIC,    30, 0 },
19465   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19466   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19467   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19468   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19469   {  'c',  0, 0, etCHARX,      0,  0 },
19470   {  'o',  8, 0, etRADIX,      0,  2 },
19471   {  'u', 10, 0, etRADIX,      0,  0 },
19472   {  'x', 16, 0, etRADIX,      16, 1 },
19473   {  'X', 16, 0, etRADIX,      0,  4 },
19474 #ifndef SQLITE_OMIT_FLOATING_POINT
19475   {  'f',  0, 1, etFLOAT,      0,  0 },
19476   {  'e',  0, 1, etEXP,        30, 0 },
19477   {  'E',  0, 1, etEXP,        14, 0 },
19478   {  'G',  0, 1, etGENERIC,    14, 0 },
19479 #endif
19480   {  'i', 10, 1, etRADIX,      0,  0 },
19481   {  'n',  0, 0, etSIZE,       0,  0 },
19482   {  '%',  0, 0, etPERCENT,    0,  0 },
19483   {  'p', 16, 0, etPOINTER,    0,  1 },
19484 
19485 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19486 ** use only */
19487   {  'T',  0, 2, etTOKEN,      0,  0 },
19488   {  'S',  0, 2, etSRCLIST,    0,  0 },
19489   {  'r', 10, 3, etORDINAL,    0,  0 },
19490 };
19491 
19492 /*
19493 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19494 ** conversions will work.
19495 */
19496 #ifndef SQLITE_OMIT_FLOATING_POINT
19497 /*
19498 ** "*val" is a double such that 0.1 <= *val < 10.0
19499 ** Return the ascii code for the leading digit of *val, then
19500 ** multiply "*val" by 10.0 to renormalize.
19501 **
19502 ** Example:
19503 **     input:     *val = 3.14159
19504 **     output:    *val = 1.4159    function return = '3'
19505 **
19506 ** The counter *cnt is incremented each time.  After counter exceeds
19507 ** 16 (the number of significant digits in a 64-bit float) '0' is
19508 ** always returned.
19509 */
19510 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19511   int digit;
19512   LONGDOUBLE_TYPE d;
19513   if( (*cnt)<=0 ) return '0';
19514   (*cnt)--;
19515   digit = (int)*val;
19516   d = digit;
19517   digit += '0';
19518   *val = (*val - d)*10.0;
19519   return (char)digit;
19520 }
19521 #endif /* SQLITE_OMIT_FLOATING_POINT */
19522 
19523 /*
19524 ** Append N space characters to the given string buffer.
19525 */
19526 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19527   static const char zSpaces[] = "                             ";
19528   while( N>=(int)sizeof(zSpaces)-1 ){
19529     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19530     N -= sizeof(zSpaces)-1;
19531   }
19532   if( N>0 ){
19533     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19534   }
19535 }
19536 
19537 /*
19538 ** On machines with a small stack size, you can redefine the
19539 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19540 */
19541 #ifndef SQLITE_PRINT_BUF_SIZE
19542 # define SQLITE_PRINT_BUF_SIZE 70
19543 #endif
19544 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19545 
19546 /*
19547 ** Render a string given by "fmt" into the StrAccum object.
19548 */
19549 SQLITE_PRIVATE void sqlite3VXPrintf(
19550   StrAccum *pAccum,                  /* Accumulate results here */
19551   int useExtended,                   /* Allow extended %-conversions */
19552   const char *fmt,                   /* Format string */
19553   va_list ap                         /* arguments */
19554 ){
19555   int c;                     /* Next character in the format string */
19556   char *bufpt;               /* Pointer to the conversion buffer */
19557   int precision;             /* Precision of the current field */
19558   int length;                /* Length of the field */
19559   int idx;                   /* A general purpose loop counter */
19560   int width;                 /* Width of the current field */
19561   etByte flag_leftjustify;   /* True if "-" flag is present */
19562   etByte flag_plussign;      /* True if "+" flag is present */
19563   etByte flag_blanksign;     /* True if " " flag is present */
19564   etByte flag_alternateform; /* True if "#" flag is present */
19565   etByte flag_altform2;      /* True if "!" flag is present */
19566   etByte flag_zeropad;       /* True if field width constant starts with zero */
19567   etByte flag_long;          /* True if "l" flag is present */
19568   etByte flag_longlong;      /* True if the "ll" flag is present */
19569   etByte done;               /* Loop termination flag */
19570   etByte xtype = 0;          /* Conversion paradigm */
19571   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19572   sqlite_uint64 longvalue;   /* Value for integer types */
19573   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19574   const et_info *infop;      /* Pointer to the appropriate info structure */
19575   char *zOut;                /* Rendering buffer */
19576   int nOut;                  /* Size of the rendering buffer */
19577   char *zExtra;              /* Malloced memory used by some conversion */
19578 #ifndef SQLITE_OMIT_FLOATING_POINT
19579   int  exp, e2;              /* exponent of real numbers */
19580   int nsd;                   /* Number of significant digits returned */
19581   double rounder;            /* Used for rounding floating point values */
19582   etByte flag_dp;            /* True if decimal point should be shown */
19583   etByte flag_rtz;           /* True if trailing zeros should be removed */
19584 #endif
19585   char buf[etBUFSIZE];       /* Conversion buffer */
19586 
19587   bufpt = 0;
19588   for(; (c=(*fmt))!=0; ++fmt){
19589     if( c!='%' ){
19590       int amt;
19591       bufpt = (char *)fmt;
19592       amt = 1;
19593       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19594       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19595       if( c==0 ) break;
19596     }
19597     if( (c=(*++fmt))==0 ){
19598       sqlite3StrAccumAppend(pAccum, "%", 1);
19599       break;
19600     }
19601     /* Find out what flags are present */
19602     flag_leftjustify = flag_plussign = flag_blanksign =
19603      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19604     done = 0;
19605     do{
19606       switch( c ){
19607         case '-':   flag_leftjustify = 1;     break;
19608         case '+':   flag_plussign = 1;        break;
19609         case ' ':   flag_blanksign = 1;       break;
19610         case '#':   flag_alternateform = 1;   break;
19611         case '!':   flag_altform2 = 1;        break;
19612         case '0':   flag_zeropad = 1;         break;
19613         default:    done = 1;                 break;
19614       }
19615     }while( !done && (c=(*++fmt))!=0 );
19616     /* Get the field width */
19617     width = 0;
19618     if( c=='*' ){
19619       width = va_arg(ap,int);
19620       if( width<0 ){
19621         flag_leftjustify = 1;
19622         width = -width;
19623       }
19624       c = *++fmt;
19625     }else{
19626       while( c>='0' && c<='9' ){
19627         width = width*10 + c - '0';
19628         c = *++fmt;
19629       }
19630     }
19631     /* Get the precision */
19632     if( c=='.' ){
19633       precision = 0;
19634       c = *++fmt;
19635       if( c=='*' ){
19636         precision = va_arg(ap,int);
19637         if( precision<0 ) precision = -precision;
19638         c = *++fmt;
19639       }else{
19640         while( c>='0' && c<='9' ){
19641           precision = precision*10 + c - '0';
19642           c = *++fmt;
19643         }
19644       }
19645     }else{
19646       precision = -1;
19647     }
19648     /* Get the conversion type modifier */
19649     if( c=='l' ){
19650       flag_long = 1;
19651       c = *++fmt;
19652       if( c=='l' ){
19653         flag_longlong = 1;
19654         c = *++fmt;
19655       }else{
19656         flag_longlong = 0;
19657       }
19658     }else{
19659       flag_long = flag_longlong = 0;
19660     }
19661     /* Fetch the info entry for the field */
19662     infop = &fmtinfo[0];
19663     xtype = etINVALID;
19664     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19665       if( c==fmtinfo[idx].fmttype ){
19666         infop = &fmtinfo[idx];
19667         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19668           xtype = infop->type;
19669         }else{
19670           return;
19671         }
19672         break;
19673       }
19674     }
19675     zExtra = 0;
19676 
19677     /*
19678     ** At this point, variables are initialized as follows:
19679     **
19680     **   flag_alternateform          TRUE if a '#' is present.
19681     **   flag_altform2               TRUE if a '!' is present.
19682     **   flag_plussign               TRUE if a '+' is present.
19683     **   flag_leftjustify            TRUE if a '-' is present or if the
19684     **                               field width was negative.
19685     **   flag_zeropad                TRUE if the width began with 0.
19686     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19687     **                               the conversion character.
19688     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19689     **                               the conversion character.
19690     **   flag_blanksign              TRUE if a ' ' is present.
19691     **   width                       The specified field width.  This is
19692     **                               always non-negative.  Zero is the default.
19693     **   precision                   The specified precision.  The default
19694     **                               is -1.
19695     **   xtype                       The class of the conversion.
19696     **   infop                       Pointer to the appropriate info struct.
19697     */
19698     switch( xtype ){
19699       case etPOINTER:
19700         flag_longlong = sizeof(char*)==sizeof(i64);
19701         flag_long = sizeof(char*)==sizeof(long int);
19702         /* Fall through into the next case */
19703       case etORDINAL:
19704       case etRADIX:
19705         if( infop->flags & FLAG_SIGNED ){
19706           i64 v;
19707           if( flag_longlong ){
19708             v = va_arg(ap,i64);
19709           }else if( flag_long ){
19710             v = va_arg(ap,long int);
19711           }else{
19712             v = va_arg(ap,int);
19713           }
19714           if( v<0 ){
19715             if( v==SMALLEST_INT64 ){
19716               longvalue = ((u64)1)<<63;
19717             }else{
19718               longvalue = -v;
19719             }
19720             prefix = '-';
19721           }else{
19722             longvalue = v;
19723             if( flag_plussign )        prefix = '+';
19724             else if( flag_blanksign )  prefix = ' ';
19725             else                       prefix = 0;
19726           }
19727         }else{
19728           if( flag_longlong ){
19729             longvalue = va_arg(ap,u64);
19730           }else if( flag_long ){
19731             longvalue = va_arg(ap,unsigned long int);
19732           }else{
19733             longvalue = va_arg(ap,unsigned int);
19734           }
19735           prefix = 0;
19736         }
19737         if( longvalue==0 ) flag_alternateform = 0;
19738         if( flag_zeropad && precision<width-(prefix!=0) ){
19739           precision = width-(prefix!=0);
19740         }
19741         if( precision<etBUFSIZE-10 ){
19742           nOut = etBUFSIZE;
19743           zOut = buf;
19744         }else{
19745           nOut = precision + 10;
19746           zOut = zExtra = sqlite3Malloc( nOut );
19747           if( zOut==0 ){
19748             pAccum->mallocFailed = 1;
19749             return;
19750           }
19751         }
19752         bufpt = &zOut[nOut-1];
19753         if( xtype==etORDINAL ){
19754           static const char zOrd[] = "thstndrd";
19755           int x = (int)(longvalue % 10);
19756           if( x>=4 || (longvalue/10)%10==1 ){
19757             x = 0;
19758           }
19759           *(--bufpt) = zOrd[x*2+1];
19760           *(--bufpt) = zOrd[x*2];
19761         }
19762         {
19763           register const char *cset;      /* Use registers for speed */
19764           register int base;
19765           cset = &aDigits[infop->charset];
19766           base = infop->base;
19767           do{                                           /* Convert to ascii */
19768             *(--bufpt) = cset[longvalue%base];
19769             longvalue = longvalue/base;
19770           }while( longvalue>0 );
19771         }
19772         length = (int)(&zOut[nOut-1]-bufpt);
19773         for(idx=precision-length; idx>0; idx--){
19774           *(--bufpt) = '0';                             /* Zero pad */
19775         }
19776         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19777         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19778           const char *pre;
19779           char x;
19780           pre = &aPrefix[infop->prefix];
19781           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19782         }
19783         length = (int)(&zOut[nOut-1]-bufpt);
19784         break;
19785       case etFLOAT:
19786       case etEXP:
19787       case etGENERIC:
19788         realvalue = va_arg(ap,double);
19789 #ifdef SQLITE_OMIT_FLOATING_POINT
19790         length = 0;
19791 #else
19792         if( precision<0 ) precision = 6;         /* Set default precision */
19793         if( realvalue<0.0 ){
19794           realvalue = -realvalue;
19795           prefix = '-';
19796         }else{
19797           if( flag_plussign )          prefix = '+';
19798           else if( flag_blanksign )    prefix = ' ';
19799           else                         prefix = 0;
19800         }
19801         if( xtype==etGENERIC && precision>0 ) precision--;
19802 #if 0
19803         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19804         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19805 #else
19806         /* It makes more sense to use 0.5 */
19807         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19808 #endif
19809         if( xtype==etFLOAT ) realvalue += rounder;
19810         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19811         exp = 0;
19812         if( sqlite3IsNaN((double)realvalue) ){
19813           bufpt = "NaN";
19814           length = 3;
19815           break;
19816         }
19817         if( realvalue>0.0 ){
19818           LONGDOUBLE_TYPE scale = 1.0;
19819           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19820           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19821           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19822           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19823           realvalue /= scale;
19824           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19825           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19826           if( exp>350 ){
19827             if( prefix=='-' ){
19828               bufpt = "-Inf";
19829             }else if( prefix=='+' ){
19830               bufpt = "+Inf";
19831             }else{
19832               bufpt = "Inf";
19833             }
19834             length = sqlite3Strlen30(bufpt);
19835             break;
19836           }
19837         }
19838         bufpt = buf;
19839         /*
19840         ** If the field type is etGENERIC, then convert to either etEXP
19841         ** or etFLOAT, as appropriate.
19842         */
19843         if( xtype!=etFLOAT ){
19844           realvalue += rounder;
19845           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19846         }
19847         if( xtype==etGENERIC ){
19848           flag_rtz = !flag_alternateform;
19849           if( exp<-4 || exp>precision ){
19850             xtype = etEXP;
19851           }else{
19852             precision = precision - exp;
19853             xtype = etFLOAT;
19854           }
19855         }else{
19856           flag_rtz = flag_altform2;
19857         }
19858         if( xtype==etEXP ){
19859           e2 = 0;
19860         }else{
19861           e2 = exp;
19862         }
19863         if( e2+precision+width > etBUFSIZE - 15 ){
19864           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19865           if( bufpt==0 ){
19866             pAccum->mallocFailed = 1;
19867             return;
19868           }
19869         }
19870         zOut = bufpt;
19871         nsd = 16 + flag_altform2*10;
19872         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19873         /* The sign in front of the number */
19874         if( prefix ){
19875           *(bufpt++) = prefix;
19876         }
19877         /* Digits prior to the decimal point */
19878         if( e2<0 ){
19879           *(bufpt++) = '0';
19880         }else{
19881           for(; e2>=0; e2--){
19882             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19883           }
19884         }
19885         /* The decimal point */
19886         if( flag_dp ){
19887           *(bufpt++) = '.';
19888         }
19889         /* "0" digits after the decimal point but before the first
19890         ** significant digit of the number */
19891         for(e2++; e2<0; precision--, e2++){
19892           assert( precision>0 );
19893           *(bufpt++) = '0';
19894         }
19895         /* Significant digits after the decimal point */
19896         while( (precision--)>0 ){
19897           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19898         }
19899         /* Remove trailing zeros and the "." if no digits follow the "." */
19900         if( flag_rtz && flag_dp ){
19901           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19902           assert( bufpt>zOut );
19903           if( bufpt[-1]=='.' ){
19904             if( flag_altform2 ){
19905               *(bufpt++) = '0';
19906             }else{
19907               *(--bufpt) = 0;
19908             }
19909           }
19910         }
19911         /* Add the "eNNN" suffix */
19912         if( xtype==etEXP ){
19913           *(bufpt++) = aDigits[infop->charset];
19914           if( exp<0 ){
19915             *(bufpt++) = '-'; exp = -exp;
19916           }else{
19917             *(bufpt++) = '+';
19918           }
19919           if( exp>=100 ){
19920             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19921             exp %= 100;
19922           }
19923           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19924           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19925         }
19926         *bufpt = 0;
19927 
19928         /* The converted number is in buf[] and zero terminated. Output it.
19929         ** Note that the number is in the usual order, not reversed as with
19930         ** integer conversions. */
19931         length = (int)(bufpt-zOut);
19932         bufpt = zOut;
19933 
19934         /* Special case:  Add leading zeros if the flag_zeropad flag is
19935         ** set and we are not left justified */
19936         if( flag_zeropad && !flag_leftjustify && length < width){
19937           int i;
19938           int nPad = width - length;
19939           for(i=width; i>=nPad; i--){
19940             bufpt[i] = bufpt[i-nPad];
19941           }
19942           i = prefix!=0;
19943           while( nPad-- ) bufpt[i++] = '0';
19944           length = width;
19945         }
19946 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19947         break;
19948       case etSIZE:
19949         *(va_arg(ap,int*)) = pAccum->nChar;
19950         length = width = 0;
19951         break;
19952       case etPERCENT:
19953         buf[0] = '%';
19954         bufpt = buf;
19955         length = 1;
19956         break;
19957       case etCHARX:
19958         c = va_arg(ap,int);
19959         buf[0] = (char)c;
19960         if( precision>=0 ){
19961           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19962           length = precision;
19963         }else{
19964           length =1;
19965         }
19966         bufpt = buf;
19967         break;
19968       case etSTRING:
19969       case etDYNSTRING:
19970         bufpt = va_arg(ap,char*);
19971         if( bufpt==0 ){
19972           bufpt = "";
19973         }else if( xtype==etDYNSTRING ){
19974           zExtra = bufpt;
19975         }
19976         if( precision>=0 ){
19977           for(length=0; length<precision && bufpt[length]; length++){}
19978         }else{
19979           length = sqlite3Strlen30(bufpt);
19980         }
19981         break;
19982       case etSQLESCAPE:
19983       case etSQLESCAPE2:
19984       case etSQLESCAPE3: {
19985         int i, j, k, n, isnull;
19986         int needQuote;
19987         char ch;
19988         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19989         char *escarg = va_arg(ap,char*);
19990         isnull = escarg==0;
19991         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19992         k = precision;
19993         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19994           if( ch==q )  n++;
19995         }
19996         needQuote = !isnull && xtype==etSQLESCAPE2;
19997         n += i + 1 + needQuote*2;
19998         if( n>etBUFSIZE ){
19999           bufpt = zExtra = sqlite3Malloc( n );
20000           if( bufpt==0 ){
20001             pAccum->mallocFailed = 1;
20002             return;
20003           }
20004         }else{
20005           bufpt = buf;
20006         }
20007         j = 0;
20008         if( needQuote ) bufpt[j++] = q;
20009         k = i;
20010         for(i=0; i<k; i++){
20011           bufpt[j++] = ch = escarg[i];
20012           if( ch==q ) bufpt[j++] = ch;
20013         }
20014         if( needQuote ) bufpt[j++] = q;
20015         bufpt[j] = 0;
20016         length = j;
20017         /* The precision in %q and %Q means how many input characters to
20018         ** consume, not the length of the output...
20019         ** if( precision>=0 && precision<length ) length = precision; */
20020         break;
20021       }
20022       case etTOKEN: {
20023         Token *pToken = va_arg(ap, Token*);
20024         if( pToken ){
20025           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20026         }
20027         length = width = 0;
20028         break;
20029       }
20030       case etSRCLIST: {
20031         SrcList *pSrc = va_arg(ap, SrcList*);
20032         int k = va_arg(ap, int);
20033         struct SrcList_item *pItem = &pSrc->a[k];
20034         assert( k>=0 && k<pSrc->nSrc );
20035         if( pItem->zDatabase ){
20036           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20037           sqlite3StrAccumAppend(pAccum, ".", 1);
20038         }
20039         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20040         length = width = 0;
20041         break;
20042       }
20043       default: {
20044         assert( xtype==etINVALID );
20045         return;
20046       }
20047     }/* End switch over the format type */
20048     /*
20049     ** The text of the conversion is pointed to by "bufpt" and is
20050     ** "length" characters long.  The field width is "width".  Do
20051     ** the output.
20052     */
20053     if( !flag_leftjustify ){
20054       register int nspace;
20055       nspace = width-length;
20056       if( nspace>0 ){
20057         sqlite3AppendSpace(pAccum, nspace);
20058       }
20059     }
20060     if( length>0 ){
20061       sqlite3StrAccumAppend(pAccum, bufpt, length);
20062     }
20063     if( flag_leftjustify ){
20064       register int nspace;
20065       nspace = width-length;
20066       if( nspace>0 ){
20067         sqlite3AppendSpace(pAccum, nspace);
20068       }
20069     }
20070     sqlite3_free(zExtra);
20071   }/* End for loop over the format string */
20072 } /* End of function */
20073 
20074 /*
20075 ** Append N bytes of text from z to the StrAccum object.
20076 */
20077 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20078   assert( z!=0 || N==0 );
20079   if( p->tooBig | p->mallocFailed ){
20080     testcase(p->tooBig);
20081     testcase(p->mallocFailed);
20082     return;
20083   }
20084   assert( p->zText!=0 || p->nChar==0 );
20085   if( N<0 ){
20086     N = sqlite3Strlen30(z);
20087   }
20088   if( N==0 || NEVER(z==0) ){
20089     return;
20090   }
20091   if( p->nChar+N >= p->nAlloc ){
20092     char *zNew;
20093     if( !p->useMalloc ){
20094       p->tooBig = 1;
20095       N = p->nAlloc - p->nChar - 1;
20096       if( N<=0 ){
20097         return;
20098       }
20099     }else{
20100       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20101       i64 szNew = p->nChar;
20102       szNew += N + 1;
20103       if( szNew > p->mxAlloc ){
20104         sqlite3StrAccumReset(p);
20105         p->tooBig = 1;
20106         return;
20107       }else{
20108         p->nAlloc = (int)szNew;
20109       }
20110       if( p->useMalloc==1 ){
20111         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20112       }else{
20113         zNew = sqlite3_realloc(zOld, p->nAlloc);
20114       }
20115       if( zNew ){
20116         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20117         p->zText = zNew;
20118       }else{
20119         p->mallocFailed = 1;
20120         sqlite3StrAccumReset(p);
20121         return;
20122       }
20123     }
20124   }
20125   assert( p->zText );
20126   memcpy(&p->zText[p->nChar], z, N);
20127   p->nChar += N;
20128 }
20129 
20130 /*
20131 ** Finish off a string by making sure it is zero-terminated.
20132 ** Return a pointer to the resulting string.  Return a NULL
20133 ** pointer if any kind of error was encountered.
20134 */
20135 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20136   if( p->zText ){
20137     p->zText[p->nChar] = 0;
20138     if( p->useMalloc && p->zText==p->zBase ){
20139       if( p->useMalloc==1 ){
20140         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20141       }else{
20142         p->zText = sqlite3_malloc(p->nChar+1);
20143       }
20144       if( p->zText ){
20145         memcpy(p->zText, p->zBase, p->nChar+1);
20146       }else{
20147         p->mallocFailed = 1;
20148       }
20149     }
20150   }
20151   return p->zText;
20152 }
20153 
20154 /*
20155 ** Reset an StrAccum string.  Reclaim all malloced memory.
20156 */
20157 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20158   if( p->zText!=p->zBase ){
20159     if( p->useMalloc==1 ){
20160       sqlite3DbFree(p->db, p->zText);
20161     }else{
20162       sqlite3_free(p->zText);
20163     }
20164   }
20165   p->zText = 0;
20166 }
20167 
20168 /*
20169 ** Initialize a string accumulator
20170 */
20171 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20172   p->zText = p->zBase = zBase;
20173   p->db = 0;
20174   p->nChar = 0;
20175   p->nAlloc = n;
20176   p->mxAlloc = mx;
20177   p->useMalloc = 1;
20178   p->tooBig = 0;
20179   p->mallocFailed = 0;
20180 }
20181 
20182 /*
20183 ** Print into memory obtained from sqliteMalloc().  Use the internal
20184 ** %-conversion extensions.
20185 */
20186 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20187   char *z;
20188   char zBase[SQLITE_PRINT_BUF_SIZE];
20189   StrAccum acc;
20190   assert( db!=0 );
20191   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20192                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20193   acc.db = db;
20194   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20195   z = sqlite3StrAccumFinish(&acc);
20196   if( acc.mallocFailed ){
20197     db->mallocFailed = 1;
20198   }
20199   return z;
20200 }
20201 
20202 /*
20203 ** Print into memory obtained from sqliteMalloc().  Use the internal
20204 ** %-conversion extensions.
20205 */
20206 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20207   va_list ap;
20208   char *z;
20209   va_start(ap, zFormat);
20210   z = sqlite3VMPrintf(db, zFormat, ap);
20211   va_end(ap);
20212   return z;
20213 }
20214 
20215 /*
20216 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20217 ** the string and before returnning.  This routine is intended to be used
20218 ** to modify an existing string.  For example:
20219 **
20220 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20221 **
20222 */
20223 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20224   va_list ap;
20225   char *z;
20226   va_start(ap, zFormat);
20227   z = sqlite3VMPrintf(db, zFormat, ap);
20228   va_end(ap);
20229   sqlite3DbFree(db, zStr);
20230   return z;
20231 }
20232 
20233 /*
20234 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20235 ** %-conversion extensions.
20236 */
20237 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20238   char *z;
20239   char zBase[SQLITE_PRINT_BUF_SIZE];
20240   StrAccum acc;
20241 #ifndef SQLITE_OMIT_AUTOINIT
20242   if( sqlite3_initialize() ) return 0;
20243 #endif
20244   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20245   acc.useMalloc = 2;
20246   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20247   z = sqlite3StrAccumFinish(&acc);
20248   return z;
20249 }
20250 
20251 /*
20252 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20253 ** %-conversion extensions.
20254 */
20255 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20256   va_list ap;
20257   char *z;
20258 #ifndef SQLITE_OMIT_AUTOINIT
20259   if( sqlite3_initialize() ) return 0;
20260 #endif
20261   va_start(ap, zFormat);
20262   z = sqlite3_vmprintf(zFormat, ap);
20263   va_end(ap);
20264   return z;
20265 }
20266 
20267 /*
20268 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20269 ** current locale settings.  This is important for SQLite because we
20270 ** are not able to use a "," as the decimal point in place of "." as
20271 ** specified by some locales.
20272 **
20273 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20274 ** from the snprintf() standard.  Unfortunately, it is too late to change
20275 ** this without breaking compatibility, so we just have to live with the
20276 ** mistake.
20277 **
20278 ** sqlite3_vsnprintf() is the varargs version.
20279 */
20280 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20281   StrAccum acc;
20282   if( n<=0 ) return zBuf;
20283   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20284   acc.useMalloc = 0;
20285   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20286   return sqlite3StrAccumFinish(&acc);
20287 }
20288 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20289   char *z;
20290   va_list ap;
20291   va_start(ap,zFormat);
20292   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20293   va_end(ap);
20294   return z;
20295 }
20296 
20297 /*
20298 ** This is the routine that actually formats the sqlite3_log() message.
20299 ** We house it in a separate routine from sqlite3_log() to avoid using
20300 ** stack space on small-stack systems when logging is disabled.
20301 **
20302 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20303 ** allocate memory because it might be called while the memory allocator
20304 ** mutex is held.
20305 */
20306 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20307   StrAccum acc;                          /* String accumulator */
20308   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20309 
20310   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20311   acc.useMalloc = 0;
20312   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20313   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20314                            sqlite3StrAccumFinish(&acc));
20315 }
20316 
20317 /*
20318 ** Format and write a message to the log if logging is enabled.
20319 */
20320 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20321   va_list ap;                             /* Vararg list */
20322   if( sqlite3GlobalConfig.xLog ){
20323     va_start(ap, zFormat);
20324     renderLogMsg(iErrCode, zFormat, ap);
20325     va_end(ap);
20326   }
20327 }
20328 
20329 #if defined(SQLITE_DEBUG)
20330 /*
20331 ** A version of printf() that understands %lld.  Used for debugging.
20332 ** The printf() built into some versions of windows does not understand %lld
20333 ** and segfaults if you give it a long long int.
20334 */
20335 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20336   va_list ap;
20337   StrAccum acc;
20338   char zBuf[500];
20339   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20340   acc.useMalloc = 0;
20341   va_start(ap,zFormat);
20342   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20343   va_end(ap);
20344   sqlite3StrAccumFinish(&acc);
20345   fprintf(stdout,"%s", zBuf);
20346   fflush(stdout);
20347 }
20348 #endif
20349 
20350 #ifndef SQLITE_OMIT_TRACE
20351 /*
20352 ** variable-argument wrapper around sqlite3VXPrintf().
20353 */
20354 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20355   va_list ap;
20356   va_start(ap,zFormat);
20357   sqlite3VXPrintf(p, 1, zFormat, ap);
20358   va_end(ap);
20359 }
20360 #endif
20361 
20362 /************** End of printf.c **********************************************/
20363 /************** Begin file random.c ******************************************/
20364 /*
20365 ** 2001 September 15
20366 **
20367 ** The author disclaims copyright to this source code.  In place of
20368 ** a legal notice, here is a blessing:
20369 **
20370 **    May you do good and not evil.
20371 **    May you find forgiveness for yourself and forgive others.
20372 **    May you share freely, never taking more than you give.
20373 **
20374 *************************************************************************
20375 ** This file contains code to implement a pseudo-random number
20376 ** generator (PRNG) for SQLite.
20377 **
20378 ** Random numbers are used by some of the database backends in order
20379 ** to generate random integer keys for tables or random filenames.
20380 */
20381 
20382 
20383 /* All threads share a single random number generator.
20384 ** This structure is the current state of the generator.
20385 */
20386 static SQLITE_WSD struct sqlite3PrngType {
20387   unsigned char isInit;          /* True if initialized */
20388   unsigned char i, j;            /* State variables */
20389   unsigned char s[256];          /* State variables */
20390 } sqlite3Prng;
20391 
20392 /*
20393 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20394 ** must be held while executing this routine.
20395 **
20396 ** Why not just use a library random generator like lrand48() for this?
20397 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
20398 ** good source of random numbers.  The lrand48() library function may
20399 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
20400 ** subtle problems on some systems that could cause problems.  It is hard
20401 ** to know.  To minimize the risk of problems due to bad lrand48()
20402 ** implementations, SQLite uses this random number generator based
20403 ** on RC4, which we know works very well.
20404 **
20405 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
20406 ** randomness any more.  But we will leave this code in all the same.
20407 */
20408 static u8 randomByte(void){
20409   unsigned char t;
20410 
20411 
20412   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20413   ** state vector.  If writable static data is unsupported on the target,
20414   ** we have to locate the state vector at run-time.  In the more common
20415   ** case where writable static data is supported, wsdPrng can refer directly
20416   ** to the "sqlite3Prng" state vector declared above.
20417   */
20418 #ifdef SQLITE_OMIT_WSD
20419   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20420 # define wsdPrng p[0]
20421 #else
20422 # define wsdPrng sqlite3Prng
20423 #endif
20424 
20425 
20426   /* Initialize the state of the random number generator once,
20427   ** the first time this routine is called.  The seed value does
20428   ** not need to contain a lot of randomness since we are not
20429   ** trying to do secure encryption or anything like that...
20430   **
20431   ** Nothing in this file or anywhere else in SQLite does any kind of
20432   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20433   ** number generator) not as an encryption device.
20434   */
20435   if( !wsdPrng.isInit ){
20436     int i;
20437     char k[256];
20438     wsdPrng.j = 0;
20439     wsdPrng.i = 0;
20440     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20441     for(i=0; i<256; i++){
20442       wsdPrng.s[i] = (u8)i;
20443     }
20444     for(i=0; i<256; i++){
20445       wsdPrng.j += wsdPrng.s[i] + k[i];
20446       t = wsdPrng.s[wsdPrng.j];
20447       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20448       wsdPrng.s[i] = t;
20449     }
20450     wsdPrng.isInit = 1;
20451   }
20452 
20453   /* Generate and return single random byte
20454   */
20455   wsdPrng.i++;
20456   t = wsdPrng.s[wsdPrng.i];
20457   wsdPrng.j += t;
20458   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20459   wsdPrng.s[wsdPrng.j] = t;
20460   t += wsdPrng.s[wsdPrng.i];
20461   return wsdPrng.s[t];
20462 }
20463 
20464 /*
20465 ** Return N random bytes.
20466 */
20467 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20468   unsigned char *zBuf = pBuf;
20469 #if SQLITE_THREADSAFE
20470   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20471 #endif
20472   sqlite3_mutex_enter(mutex);
20473   while( N-- ){
20474     *(zBuf++) = randomByte();
20475   }
20476   sqlite3_mutex_leave(mutex);
20477 }
20478 
20479 #ifndef SQLITE_OMIT_BUILTIN_TEST
20480 /*
20481 ** For testing purposes, we sometimes want to preserve the state of
20482 ** PRNG and restore the PRNG to its saved state at a later time, or
20483 ** to reset the PRNG to its initial state.  These routines accomplish
20484 ** those tasks.
20485 **
20486 ** The sqlite3_test_control() interface calls these routines to
20487 ** control the PRNG.
20488 */
20489 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20490 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20491   memcpy(
20492     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20493     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20494     sizeof(sqlite3Prng)
20495   );
20496 }
20497 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20498   memcpy(
20499     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20500     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20501     sizeof(sqlite3Prng)
20502   );
20503 }
20504 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20505   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20506 }
20507 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20508 
20509 /************** End of random.c **********************************************/
20510 /************** Begin file utf.c *********************************************/
20511 /*
20512 ** 2004 April 13
20513 **
20514 ** The author disclaims copyright to this source code.  In place of
20515 ** a legal notice, here is a blessing:
20516 **
20517 **    May you do good and not evil.
20518 **    May you find forgiveness for yourself and forgive others.
20519 **    May you share freely, never taking more than you give.
20520 **
20521 *************************************************************************
20522 ** This file contains routines used to translate between UTF-8,
20523 ** UTF-16, UTF-16BE, and UTF-16LE.
20524 **
20525 ** Notes on UTF-8:
20526 **
20527 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20528 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20529 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20530 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20531 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20532 **
20533 **
20534 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20535 **
20536 **      Word-0               Word-1          Value
20537 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20538 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20539 **
20540 **
20541 ** BOM or Byte Order Mark:
20542 **     0xff 0xfe   little-endian utf-16 follows
20543 **     0xfe 0xff   big-endian utf-16 follows
20544 **
20545 */
20546 /* #include <assert.h> */
20547 
20548 #ifndef SQLITE_AMALGAMATION
20549 /*
20550 ** The following constant value is used by the SQLITE_BIGENDIAN and
20551 ** SQLITE_LITTLEENDIAN macros.
20552 */
20553 SQLITE_PRIVATE const int sqlite3one = 1;
20554 #endif /* SQLITE_AMALGAMATION */
20555 
20556 /*
20557 ** This lookup table is used to help decode the first byte of
20558 ** a multi-byte UTF8 character.
20559 */
20560 static const unsigned char sqlite3Utf8Trans1[] = {
20561   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20562   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20563   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20564   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20565   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20566   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20567   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20568   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20569 };
20570 
20571 
20572 #define WRITE_UTF8(zOut, c) {                          \
20573   if( c<0x00080 ){                                     \
20574     *zOut++ = (u8)(c&0xFF);                            \
20575   }                                                    \
20576   else if( c<0x00800 ){                                \
20577     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20578     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20579   }                                                    \
20580   else if( c<0x10000 ){                                \
20581     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20582     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20583     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20584   }else{                                               \
20585     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20586     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20587     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20588     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20589   }                                                    \
20590 }
20591 
20592 #define WRITE_UTF16LE(zOut, c) {                                    \
20593   if( c<=0xFFFF ){                                                  \
20594     *zOut++ = (u8)(c&0x00FF);                                       \
20595     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20596   }else{                                                            \
20597     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20598     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20599     *zOut++ = (u8)(c&0x00FF);                                       \
20600     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20601   }                                                                 \
20602 }
20603 
20604 #define WRITE_UTF16BE(zOut, c) {                                    \
20605   if( c<=0xFFFF ){                                                  \
20606     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20607     *zOut++ = (u8)(c&0x00FF);                                       \
20608   }else{                                                            \
20609     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20610     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20611     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20612     *zOut++ = (u8)(c&0x00FF);                                       \
20613   }                                                                 \
20614 }
20615 
20616 #define READ_UTF16LE(zIn, TERM, c){                                   \
20617   c = (*zIn++);                                                       \
20618   c += ((*zIn++)<<8);                                                 \
20619   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20620     int c2 = (*zIn++);                                                \
20621     c2 += ((*zIn++)<<8);                                              \
20622     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20623   }                                                                   \
20624 }
20625 
20626 #define READ_UTF16BE(zIn, TERM, c){                                   \
20627   c = ((*zIn++)<<8);                                                  \
20628   c += (*zIn++);                                                      \
20629   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20630     int c2 = ((*zIn++)<<8);                                           \
20631     c2 += (*zIn++);                                                   \
20632     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20633   }                                                                   \
20634 }
20635 
20636 /*
20637 ** Translate a single UTF-8 character.  Return the unicode value.
20638 **
20639 ** During translation, assume that the byte that zTerm points
20640 ** is a 0x00.
20641 **
20642 ** Write a pointer to the next unread byte back into *pzNext.
20643 **
20644 ** Notes On Invalid UTF-8:
20645 **
20646 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20647 **     be encoded as a multi-byte character.  Any multi-byte character that
20648 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20649 **
20650 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20651 **     If a multi-byte character attempts to encode a value between
20652 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20653 **
20654 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20655 **     byte of a character are interpreted as single-byte characters
20656 **     and rendered as themselves even though they are technically
20657 **     invalid characters.
20658 **
20659 **  *  This routine accepts an infinite number of different UTF8 encodings
20660 **     for unicode values 0x80 and greater.  It do not change over-length
20661 **     encodings to 0xfffd as some systems recommend.
20662 */
20663 #define READ_UTF8(zIn, zTerm, c)                           \
20664   c = *(zIn++);                                            \
20665   if( c>=0xc0 ){                                           \
20666     c = sqlite3Utf8Trans1[c-0xc0];                         \
20667     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20668       c = (c<<6) + (0x3f & *(zIn++));                      \
20669     }                                                      \
20670     if( c<0x80                                             \
20671         || (c&0xFFFFF800)==0xD800                          \
20672         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20673   }
20674 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20675   const unsigned char **pz    /* Pointer to string from which to read char */
20676 ){
20677   unsigned int c;
20678 
20679   /* Same as READ_UTF8() above but without the zTerm parameter.
20680   ** For this routine, we assume the UTF8 string is always zero-terminated.
20681   */
20682   c = *((*pz)++);
20683   if( c>=0xc0 ){
20684     c = sqlite3Utf8Trans1[c-0xc0];
20685     while( (*(*pz) & 0xc0)==0x80 ){
20686       c = (c<<6) + (0x3f & *((*pz)++));
20687     }
20688     if( c<0x80
20689         || (c&0xFFFFF800)==0xD800
20690         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20691   }
20692   return c;
20693 }
20694 
20695 
20696 
20697 
20698 /*
20699 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20700 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20701 */
20702 /* #define TRANSLATE_TRACE 1 */
20703 
20704 #ifndef SQLITE_OMIT_UTF16
20705 /*
20706 ** This routine transforms the internal text encoding used by pMem to
20707 ** desiredEnc. It is an error if the string is already of the desired
20708 ** encoding, or if *pMem does not contain a string value.
20709 */
20710 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20711   int len;                    /* Maximum length of output string in bytes */
20712   unsigned char *zOut;                  /* Output buffer */
20713   unsigned char *zIn;                   /* Input iterator */
20714   unsigned char *zTerm;                 /* End of input */
20715   unsigned char *z;                     /* Output iterator */
20716   unsigned int c;
20717 
20718   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20719   assert( pMem->flags&MEM_Str );
20720   assert( pMem->enc!=desiredEnc );
20721   assert( pMem->enc!=0 );
20722   assert( pMem->n>=0 );
20723 
20724 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20725   {
20726     char zBuf[100];
20727     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20728     fprintf(stderr, "INPUT:  %s\n", zBuf);
20729   }
20730 #endif
20731 
20732   /* If the translation is between UTF-16 little and big endian, then
20733   ** all that is required is to swap the byte order. This case is handled
20734   ** differently from the others.
20735   */
20736   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20737     u8 temp;
20738     int rc;
20739     rc = sqlite3VdbeMemMakeWriteable(pMem);
20740     if( rc!=SQLITE_OK ){
20741       assert( rc==SQLITE_NOMEM );
20742       return SQLITE_NOMEM;
20743     }
20744     zIn = (u8*)pMem->z;
20745     zTerm = &zIn[pMem->n&~1];
20746     while( zIn<zTerm ){
20747       temp = *zIn;
20748       *zIn = *(zIn+1);
20749       zIn++;
20750       *zIn++ = temp;
20751     }
20752     pMem->enc = desiredEnc;
20753     goto translate_out;
20754   }
20755 
20756   /* Set len to the maximum number of bytes required in the output buffer. */
20757   if( desiredEnc==SQLITE_UTF8 ){
20758     /* When converting from UTF-16, the maximum growth results from
20759     ** translating a 2-byte character to a 4-byte UTF-8 character.
20760     ** A single byte is required for the output string
20761     ** nul-terminator.
20762     */
20763     pMem->n &= ~1;
20764     len = pMem->n * 2 + 1;
20765   }else{
20766     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20767     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20768     ** character. Two bytes are required in the output buffer for the
20769     ** nul-terminator.
20770     */
20771     len = pMem->n * 2 + 2;
20772   }
20773 
20774   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20775   ** byte past the end.
20776   **
20777   ** Variable zOut is set to point at the output buffer, space obtained
20778   ** from sqlite3_malloc().
20779   */
20780   zIn = (u8*)pMem->z;
20781   zTerm = &zIn[pMem->n];
20782   zOut = sqlite3DbMallocRaw(pMem->db, len);
20783   if( !zOut ){
20784     return SQLITE_NOMEM;
20785   }
20786   z = zOut;
20787 
20788   if( pMem->enc==SQLITE_UTF8 ){
20789     if( desiredEnc==SQLITE_UTF16LE ){
20790       /* UTF-8 -> UTF-16 Little-endian */
20791       while( zIn<zTerm ){
20792         READ_UTF8(zIn, zTerm, c);
20793         WRITE_UTF16LE(z, c);
20794       }
20795     }else{
20796       assert( desiredEnc==SQLITE_UTF16BE );
20797       /* UTF-8 -> UTF-16 Big-endian */
20798       while( zIn<zTerm ){
20799         READ_UTF8(zIn, zTerm, c);
20800         WRITE_UTF16BE(z, c);
20801       }
20802     }
20803     pMem->n = (int)(z - zOut);
20804     *z++ = 0;
20805   }else{
20806     assert( desiredEnc==SQLITE_UTF8 );
20807     if( pMem->enc==SQLITE_UTF16LE ){
20808       /* UTF-16 Little-endian -> UTF-8 */
20809       while( zIn<zTerm ){
20810         READ_UTF16LE(zIn, zIn<zTerm, c);
20811         WRITE_UTF8(z, c);
20812       }
20813     }else{
20814       /* UTF-16 Big-endian -> UTF-8 */
20815       while( zIn<zTerm ){
20816         READ_UTF16BE(zIn, zIn<zTerm, c);
20817         WRITE_UTF8(z, c);
20818       }
20819     }
20820     pMem->n = (int)(z - zOut);
20821   }
20822   *z = 0;
20823   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20824 
20825   sqlite3VdbeMemRelease(pMem);
20826   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20827   pMem->enc = desiredEnc;
20828   pMem->flags |= (MEM_Term|MEM_Dyn);
20829   pMem->z = (char*)zOut;
20830   pMem->zMalloc = pMem->z;
20831 
20832 translate_out:
20833 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20834   {
20835     char zBuf[100];
20836     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20837     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20838   }
20839 #endif
20840   return SQLITE_OK;
20841 }
20842 
20843 /*
20844 ** This routine checks for a byte-order mark at the beginning of the
20845 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20846 ** the encoding of the Mem adjusted. This routine does not do any
20847 ** byte-swapping, it just sets Mem.enc appropriately.
20848 **
20849 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20850 ** changed by this function.
20851 */
20852 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20853   int rc = SQLITE_OK;
20854   u8 bom = 0;
20855 
20856   assert( pMem->n>=0 );
20857   if( pMem->n>1 ){
20858     u8 b1 = *(u8 *)pMem->z;
20859     u8 b2 = *(((u8 *)pMem->z) + 1);
20860     if( b1==0xFE && b2==0xFF ){
20861       bom = SQLITE_UTF16BE;
20862     }
20863     if( b1==0xFF && b2==0xFE ){
20864       bom = SQLITE_UTF16LE;
20865     }
20866   }
20867 
20868   if( bom ){
20869     rc = sqlite3VdbeMemMakeWriteable(pMem);
20870     if( rc==SQLITE_OK ){
20871       pMem->n -= 2;
20872       memmove(pMem->z, &pMem->z[2], pMem->n);
20873       pMem->z[pMem->n] = '\0';
20874       pMem->z[pMem->n+1] = '\0';
20875       pMem->flags |= MEM_Term;
20876       pMem->enc = bom;
20877     }
20878   }
20879   return rc;
20880 }
20881 #endif /* SQLITE_OMIT_UTF16 */
20882 
20883 /*
20884 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20885 ** return the number of unicode characters in pZ up to (but not including)
20886 ** the first 0x00 byte. If nByte is not less than zero, return the
20887 ** number of unicode characters in the first nByte of pZ (or up to
20888 ** the first 0x00, whichever comes first).
20889 */
20890 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20891   int r = 0;
20892   const u8 *z = (const u8*)zIn;
20893   const u8 *zTerm;
20894   if( nByte>=0 ){
20895     zTerm = &z[nByte];
20896   }else{
20897     zTerm = (const u8*)(-1);
20898   }
20899   assert( z<=zTerm );
20900   while( *z!=0 && z<zTerm ){
20901     SQLITE_SKIP_UTF8(z);
20902     r++;
20903   }
20904   return r;
20905 }
20906 
20907 /* This test function is not currently used by the automated test-suite.
20908 ** Hence it is only available in debug builds.
20909 */
20910 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20911 /*
20912 ** Translate UTF-8 to UTF-8.
20913 **
20914 ** This has the effect of making sure that the string is well-formed
20915 ** UTF-8.  Miscoded characters are removed.
20916 **
20917 ** The translation is done in-place and aborted if the output
20918 ** overruns the input.
20919 */
20920 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20921   unsigned char *zOut = zIn;
20922   unsigned char *zStart = zIn;
20923   u32 c;
20924 
20925   while( zIn[0] && zOut<=zIn ){
20926     c = sqlite3Utf8Read((const u8**)&zIn);
20927     if( c!=0xfffd ){
20928       WRITE_UTF8(zOut, c);
20929     }
20930   }
20931   *zOut = 0;
20932   return (int)(zOut - zStart);
20933 }
20934 #endif
20935 
20936 #ifndef SQLITE_OMIT_UTF16
20937 /*
20938 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20939 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20940 ** be freed by the calling function.
20941 **
20942 ** NULL is returned if there is an allocation error.
20943 */
20944 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20945   Mem m;
20946   memset(&m, 0, sizeof(m));
20947   m.db = db;
20948   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20949   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20950   if( db->mallocFailed ){
20951     sqlite3VdbeMemRelease(&m);
20952     m.z = 0;
20953   }
20954   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20955   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20956   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20957   assert( m.z || db->mallocFailed );
20958   return m.z;
20959 }
20960 
20961 /*
20962 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20963 ** enc. A pointer to the new string is returned, and the value of *pnOut
20964 ** is set to the length of the returned string in bytes. The call should
20965 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20966 ** no longer required.
20967 **
20968 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20969 ** flag set.
20970 */
20971 #ifdef SQLITE_ENABLE_STAT3
20972 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20973   Mem m;
20974   memset(&m, 0, sizeof(m));
20975   m.db = db;
20976   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20977   if( sqlite3VdbeMemTranslate(&m, enc) ){
20978     assert( db->mallocFailed );
20979     return 0;
20980   }
20981   assert( m.z==m.zMalloc );
20982   *pnOut = m.n;
20983   return m.z;
20984 }
20985 #endif
20986 
20987 /*
20988 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20989 ** Return the number of bytes in the first nChar unicode characters
20990 ** in pZ.  nChar must be non-negative.
20991 */
20992 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20993   int c;
20994   unsigned char const *z = zIn;
20995   int n = 0;
20996 
20997   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20998     while( n<nChar ){
20999       READ_UTF16BE(z, 1, c);
21000       n++;
21001     }
21002   }else{
21003     while( n<nChar ){
21004       READ_UTF16LE(z, 1, c);
21005       n++;
21006     }
21007   }
21008   return (int)(z-(unsigned char const *)zIn);
21009 }
21010 
21011 #if defined(SQLITE_TEST)
21012 /*
21013 ** This routine is called from the TCL test function "translate_selftest".
21014 ** It checks that the primitives for serializing and deserializing
21015 ** characters in each encoding are inverses of each other.
21016 */
21017 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21018   unsigned int i, t;
21019   unsigned char zBuf[20];
21020   unsigned char *z;
21021   int n;
21022   unsigned int c;
21023 
21024   for(i=0; i<0x00110000; i++){
21025     z = zBuf;
21026     WRITE_UTF8(z, i);
21027     n = (int)(z-zBuf);
21028     assert( n>0 && n<=4 );
21029     z[0] = 0;
21030     z = zBuf;
21031     c = sqlite3Utf8Read((const u8**)&z);
21032     t = i;
21033     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21034     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21035     assert( c==t );
21036     assert( (z-zBuf)==n );
21037   }
21038   for(i=0; i<0x00110000; i++){
21039     if( i>=0xD800 && i<0xE000 ) continue;
21040     z = zBuf;
21041     WRITE_UTF16LE(z, i);
21042     n = (int)(z-zBuf);
21043     assert( n>0 && n<=4 );
21044     z[0] = 0;
21045     z = zBuf;
21046     READ_UTF16LE(z, 1, c);
21047     assert( c==i );
21048     assert( (z-zBuf)==n );
21049   }
21050   for(i=0; i<0x00110000; i++){
21051     if( i>=0xD800 && i<0xE000 ) continue;
21052     z = zBuf;
21053     WRITE_UTF16BE(z, i);
21054     n = (int)(z-zBuf);
21055     assert( n>0 && n<=4 );
21056     z[0] = 0;
21057     z = zBuf;
21058     READ_UTF16BE(z, 1, c);
21059     assert( c==i );
21060     assert( (z-zBuf)==n );
21061   }
21062 }
21063 #endif /* SQLITE_TEST */
21064 #endif /* SQLITE_OMIT_UTF16 */
21065 
21066 /************** End of utf.c *************************************************/
21067 /************** Begin file util.c ********************************************/
21068 /*
21069 ** 2001 September 15
21070 **
21071 ** The author disclaims copyright to this source code.  In place of
21072 ** a legal notice, here is a blessing:
21073 **
21074 **    May you do good and not evil.
21075 **    May you find forgiveness for yourself and forgive others.
21076 **    May you share freely, never taking more than you give.
21077 **
21078 *************************************************************************
21079 ** Utility functions used throughout sqlite.
21080 **
21081 ** This file contains functions for allocating memory, comparing
21082 ** strings, and stuff like that.
21083 **
21084 */
21085 /* #include <stdarg.h> */
21086 #ifdef SQLITE_HAVE_ISNAN
21087 # include <math.h>
21088 #endif
21089 
21090 /*
21091 ** Routine needed to support the testcase() macro.
21092 */
21093 #ifdef SQLITE_COVERAGE_TEST
21094 SQLITE_PRIVATE void sqlite3Coverage(int x){
21095   static unsigned dummy = 0;
21096   dummy += (unsigned)x;
21097 }
21098 #endif
21099 
21100 #ifndef SQLITE_OMIT_FLOATING_POINT
21101 /*
21102 ** Return true if the floating point value is Not a Number (NaN).
21103 **
21104 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21105 ** Otherwise, we have our own implementation that works on most systems.
21106 */
21107 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21108   int rc;   /* The value return */
21109 #if !defined(SQLITE_HAVE_ISNAN)
21110   /*
21111   ** Systems that support the isnan() library function should probably
21112   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21113   ** found that many systems do not have a working isnan() function so
21114   ** this implementation is provided as an alternative.
21115   **
21116   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21117   ** On the other hand, the use of -ffast-math comes with the following
21118   ** warning:
21119   **
21120   **      This option [-ffast-math] should never be turned on by any
21121   **      -O option since it can result in incorrect output for programs
21122   **      which depend on an exact implementation of IEEE or ISO
21123   **      rules/specifications for math functions.
21124   **
21125   ** Under MSVC, this NaN test may fail if compiled with a floating-
21126   ** point precision mode other than /fp:precise.  From the MSDN
21127   ** documentation:
21128   **
21129   **      The compiler [with /fp:precise] will properly handle comparisons
21130   **      involving NaN. For example, x != x evaluates to true if x is NaN
21131   **      ...
21132   */
21133 #ifdef __FAST_MATH__
21134 # error SQLite will not work correctly with the -ffast-math option of GCC.
21135 #endif
21136   volatile double y = x;
21137   volatile double z = y;
21138   rc = (y!=z);
21139 #else  /* if defined(SQLITE_HAVE_ISNAN) */
21140   rc = isnan(x);
21141 #endif /* SQLITE_HAVE_ISNAN */
21142   testcase( rc );
21143   return rc;
21144 }
21145 #endif /* SQLITE_OMIT_FLOATING_POINT */
21146 
21147 /*
21148 ** Compute a string length that is limited to what can be stored in
21149 ** lower 30 bits of a 32-bit signed integer.
21150 **
21151 ** The value returned will never be negative.  Nor will it ever be greater
21152 ** than the actual length of the string.  For very long strings (greater
21153 ** than 1GiB) the value returned might be less than the true string length.
21154 */
21155 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21156   const char *z2 = z;
21157   if( z==0 ) return 0;
21158   while( *z2 ){ z2++; }
21159   return 0x3fffffff & (int)(z2 - z);
21160 }
21161 
21162 /*
21163 ** Set the most recent error code and error string for the sqlite
21164 ** handle "db". The error code is set to "err_code".
21165 **
21166 ** If it is not NULL, string zFormat specifies the format of the
21167 ** error string in the style of the printf functions: The following
21168 ** format characters are allowed:
21169 **
21170 **      %s      Insert a string
21171 **      %z      A string that should be freed after use
21172 **      %d      Insert an integer
21173 **      %T      Insert a token
21174 **      %S      Insert the first element of a SrcList
21175 **
21176 ** zFormat and any string tokens that follow it are assumed to be
21177 ** encoded in UTF-8.
21178 **
21179 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21180 ** should be called with err_code set to SQLITE_OK and zFormat set
21181 ** to NULL.
21182 */
21183 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21184   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21185     db->errCode = err_code;
21186     if( zFormat ){
21187       char *z;
21188       va_list ap;
21189       va_start(ap, zFormat);
21190       z = sqlite3VMPrintf(db, zFormat, ap);
21191       va_end(ap);
21192       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21193     }else{
21194       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21195     }
21196   }
21197 }
21198 
21199 /*
21200 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21201 ** The following formatting characters are allowed:
21202 **
21203 **      %s      Insert a string
21204 **      %z      A string that should be freed after use
21205 **      %d      Insert an integer
21206 **      %T      Insert a token
21207 **      %S      Insert the first element of a SrcList
21208 **
21209 ** This function should be used to report any error that occurs whilst
21210 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21211 ** last thing the sqlite3_prepare() function does is copy the error
21212 ** stored by this function into the database handle using sqlite3Error().
21213 ** Function sqlite3Error() should be used during statement execution
21214 ** (sqlite3_step() etc.).
21215 */
21216 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21217   char *zMsg;
21218   va_list ap;
21219   sqlite3 *db = pParse->db;
21220   va_start(ap, zFormat);
21221   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21222   va_end(ap);
21223   if( db->suppressErr ){
21224     sqlite3DbFree(db, zMsg);
21225   }else{
21226     pParse->nErr++;
21227     sqlite3DbFree(db, pParse->zErrMsg);
21228     pParse->zErrMsg = zMsg;
21229     pParse->rc = SQLITE_ERROR;
21230   }
21231 }
21232 
21233 /*
21234 ** Convert an SQL-style quoted string into a normal string by removing
21235 ** the quote characters.  The conversion is done in-place.  If the
21236 ** input does not begin with a quote character, then this routine
21237 ** is a no-op.
21238 **
21239 ** The input string must be zero-terminated.  A new zero-terminator
21240 ** is added to the dequoted string.
21241 **
21242 ** The return value is -1 if no dequoting occurs or the length of the
21243 ** dequoted string, exclusive of the zero terminator, if dequoting does
21244 ** occur.
21245 **
21246 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21247 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21248 ** "a-b-c".
21249 */
21250 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21251   char quote;
21252   int i, j;
21253   if( z==0 ) return -1;
21254   quote = z[0];
21255   switch( quote ){
21256     case '\'':  break;
21257     case '"':   break;
21258     case '`':   break;                /* For MySQL compatibility */
21259     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21260     default:    return -1;
21261   }
21262   for(i=1, j=0; ALWAYS(z[i]); i++){
21263     if( z[i]==quote ){
21264       if( z[i+1]==quote ){
21265         z[j++] = quote;
21266         i++;
21267       }else{
21268         break;
21269       }
21270     }else{
21271       z[j++] = z[i];
21272     }
21273   }
21274   z[j] = 0;
21275   return j;
21276 }
21277 
21278 /* Convenient short-hand */
21279 #define UpperToLower sqlite3UpperToLower
21280 
21281 /*
21282 ** Some systems have stricmp().  Others have strcasecmp().  Because
21283 ** there is no consistency, we will define our own.
21284 **
21285 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21286 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21287 ** the contents of two buffers containing UTF-8 strings in a
21288 ** case-independent fashion, using the same definition of "case
21289 ** independence" that SQLite uses internally when comparing identifiers.
21290 */
21291 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21292   register unsigned char *a, *b;
21293   a = (unsigned char *)zLeft;
21294   b = (unsigned char *)zRight;
21295   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21296   return UpperToLower[*a] - UpperToLower[*b];
21297 }
21298 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21299   register unsigned char *a, *b;
21300   a = (unsigned char *)zLeft;
21301   b = (unsigned char *)zRight;
21302   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21303   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21304 }
21305 
21306 /*
21307 ** The string z[] is an text representation of a real number.
21308 ** Convert this string to a double and write it into *pResult.
21309 **
21310 ** The string z[] is length bytes in length (bytes, not characters) and
21311 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21312 **
21313 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21314 ** if the string is empty or contains extraneous text.  Valid numbers
21315 ** are in one of these formats:
21316 **
21317 **    [+-]digits[E[+-]digits]
21318 **    [+-]digits.[digits][E[+-]digits]
21319 **    [+-].digits[E[+-]digits]
21320 **
21321 ** Leading and trailing whitespace is ignored for the purpose of determining
21322 ** validity.
21323 **
21324 ** If some prefix of the input string is a valid number, this routine
21325 ** returns FALSE but it still converts the prefix and writes the result
21326 ** into *pResult.
21327 */
21328 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21329 #ifndef SQLITE_OMIT_FLOATING_POINT
21330   int incr;
21331   const char *zEnd = z + length;
21332   /* sign * significand * (10 ^ (esign * exponent)) */
21333   int sign = 1;    /* sign of significand */
21334   i64 s = 0;       /* significand */
21335   int d = 0;       /* adjust exponent for shifting decimal point */
21336   int esign = 1;   /* sign of exponent */
21337   int e = 0;       /* exponent */
21338   int eValid = 1;  /* True exponent is either not used or is well-formed */
21339   double result;
21340   int nDigits = 0;
21341   int nonNum = 0;
21342 
21343   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21344   *pResult = 0.0;   /* Default return value, in case of an error */
21345 
21346   if( enc==SQLITE_UTF8 ){
21347     incr = 1;
21348   }else{
21349     int i;
21350     incr = 2;
21351     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21352     for(i=3-enc; i<length && z[i]==0; i+=2){}
21353     nonNum = i<length;
21354     zEnd = z+i+enc-3;
21355     z += (enc&1);
21356   }
21357 
21358   /* skip leading spaces */
21359   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21360   if( z>=zEnd ) return 0;
21361 
21362   /* get sign of significand */
21363   if( *z=='-' ){
21364     sign = -1;
21365     z+=incr;
21366   }else if( *z=='+' ){
21367     z+=incr;
21368   }
21369 
21370   /* skip leading zeroes */
21371   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21372 
21373   /* copy max significant digits to significand */
21374   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21375     s = s*10 + (*z - '0');
21376     z+=incr, nDigits++;
21377   }
21378 
21379   /* skip non-significant significand digits
21380   ** (increase exponent by d to shift decimal left) */
21381   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21382   if( z>=zEnd ) goto do_atof_calc;
21383 
21384   /* if decimal point is present */
21385   if( *z=='.' ){
21386     z+=incr;
21387     /* copy digits from after decimal to significand
21388     ** (decrease exponent by d to shift decimal right) */
21389     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21390       s = s*10 + (*z - '0');
21391       z+=incr, nDigits++, d--;
21392     }
21393     /* skip non-significant digits */
21394     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21395   }
21396   if( z>=zEnd ) goto do_atof_calc;
21397 
21398   /* if exponent is present */
21399   if( *z=='e' || *z=='E' ){
21400     z+=incr;
21401     eValid = 0;
21402     if( z>=zEnd ) goto do_atof_calc;
21403     /* get sign of exponent */
21404     if( *z=='-' ){
21405       esign = -1;
21406       z+=incr;
21407     }else if( *z=='+' ){
21408       z+=incr;
21409     }
21410     /* copy digits to exponent */
21411     while( z<zEnd && sqlite3Isdigit(*z) ){
21412       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21413       z+=incr;
21414       eValid = 1;
21415     }
21416   }
21417 
21418   /* skip trailing spaces */
21419   if( nDigits && eValid ){
21420     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21421   }
21422 
21423 do_atof_calc:
21424   /* adjust exponent by d, and update sign */
21425   e = (e*esign) + d;
21426   if( e<0 ) {
21427     esign = -1;
21428     e *= -1;
21429   } else {
21430     esign = 1;
21431   }
21432 
21433   /* if 0 significand */
21434   if( !s ) {
21435     /* In the IEEE 754 standard, zero is signed.
21436     ** Add the sign if we've seen at least one digit */
21437     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21438   } else {
21439     /* attempt to reduce exponent */
21440     if( esign>0 ){
21441       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21442     }else{
21443       while( !(s%10) && e>0 ) e--,s/=10;
21444     }
21445 
21446     /* adjust the sign of significand */
21447     s = sign<0 ? -s : s;
21448 
21449     /* if exponent, scale significand as appropriate
21450     ** and store in result. */
21451     if( e ){
21452       LONGDOUBLE_TYPE scale = 1.0;
21453       /* attempt to handle extremely small/large numbers better */
21454       if( e>307 && e<342 ){
21455         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21456         if( esign<0 ){
21457           result = s / scale;
21458           result /= 1.0e+308;
21459         }else{
21460           result = s * scale;
21461           result *= 1.0e+308;
21462         }
21463       }else if( e>=342 ){
21464         if( esign<0 ){
21465           result = 0.0*s;
21466         }else{
21467           result = 1e308*1e308*s;  /* Infinity */
21468         }
21469       }else{
21470         /* 1.0e+22 is the largest power of 10 than can be
21471         ** represented exactly. */
21472         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21473         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21474         if( esign<0 ){
21475           result = s / scale;
21476         }else{
21477           result = s * scale;
21478         }
21479       }
21480     } else {
21481       result = (double)s;
21482     }
21483   }
21484 
21485   /* store the result */
21486   *pResult = result;
21487 
21488   /* return true if number and no extra non-whitespace chracters after */
21489   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
21490 #else
21491   return !sqlite3Atoi64(z, pResult, length, enc);
21492 #endif /* SQLITE_OMIT_FLOATING_POINT */
21493 }
21494 
21495 /*
21496 ** Compare the 19-character string zNum against the text representation
21497 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21498 ** if zNum is less than, equal to, or greater than the string.
21499 ** Note that zNum must contain exactly 19 characters.
21500 **
21501 ** Unlike memcmp() this routine is guaranteed to return the difference
21502 ** in the values of the last digit if the only difference is in the
21503 ** last digit.  So, for example,
21504 **
21505 **      compare2pow63("9223372036854775800", 1)
21506 **
21507 ** will return -8.
21508 */
21509 static int compare2pow63(const char *zNum, int incr){
21510   int c = 0;
21511   int i;
21512                     /* 012345678901234567 */
21513   const char *pow63 = "922337203685477580";
21514   for(i=0; c==0 && i<18; i++){
21515     c = (zNum[i*incr]-pow63[i])*10;
21516   }
21517   if( c==0 ){
21518     c = zNum[18*incr] - '8';
21519     testcase( c==(-1) );
21520     testcase( c==0 );
21521     testcase( c==(+1) );
21522   }
21523   return c;
21524 }
21525 
21526 
21527 /*
21528 ** Convert zNum to a 64-bit signed integer.
21529 **
21530 ** If the zNum value is representable as a 64-bit twos-complement
21531 ** integer, then write that value into *pNum and return 0.
21532 **
21533 ** If zNum is exactly 9223372036854665808, return 2.  This special
21534 ** case is broken out because while 9223372036854665808 cannot be a
21535 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21536 **
21537 ** If zNum is too big for a 64-bit integer and is not
21538 ** 9223372036854665808  or if zNum contains any non-numeric text,
21539 ** then return 1.
21540 **
21541 ** length is the number of bytes in the string (bytes, not characters).
21542 ** The string is not necessarily zero-terminated.  The encoding is
21543 ** given by enc.
21544 */
21545 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21546   int incr;
21547   u64 u = 0;
21548   int neg = 0; /* assume positive */
21549   int i;
21550   int c = 0;
21551   int nonNum = 0;
21552   const char *zStart;
21553   const char *zEnd = zNum + length;
21554   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21555   if( enc==SQLITE_UTF8 ){
21556     incr = 1;
21557   }else{
21558     incr = 2;
21559     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21560     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
21561     nonNum = i<length;
21562     zEnd = zNum+i+enc-3;
21563     zNum += (enc&1);
21564   }
21565   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21566   if( zNum<zEnd ){
21567     if( *zNum=='-' ){
21568       neg = 1;
21569       zNum+=incr;
21570     }else if( *zNum=='+' ){
21571       zNum+=incr;
21572     }
21573   }
21574   zStart = zNum;
21575   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21576   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21577     u = u*10 + c - '0';
21578   }
21579   if( u>LARGEST_INT64 ){
21580     *pNum = SMALLEST_INT64;
21581   }else if( neg ){
21582     *pNum = -(i64)u;
21583   }else{
21584     *pNum = (i64)u;
21585   }
21586   testcase( i==18 );
21587   testcase( i==19 );
21588   testcase( i==20 );
21589   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
21590     /* zNum is empty or contains non-numeric text or is longer
21591     ** than 19 digits (thus guaranteeing that it is too large) */
21592     return 1;
21593   }else if( i<19*incr ){
21594     /* Less than 19 digits, so we know that it fits in 64 bits */
21595     assert( u<=LARGEST_INT64 );
21596     return 0;
21597   }else{
21598     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21599     c = compare2pow63(zNum, incr);
21600     if( c<0 ){
21601       /* zNum is less than 9223372036854775808 so it fits */
21602       assert( u<=LARGEST_INT64 );
21603       return 0;
21604     }else if( c>0 ){
21605       /* zNum is greater than 9223372036854775808 so it overflows */
21606       return 1;
21607     }else{
21608       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21609       ** special case 2 overflow if positive */
21610       assert( u-1==LARGEST_INT64 );
21611       assert( (*pNum)==SMALLEST_INT64 );
21612       return neg ? 0 : 2;
21613     }
21614   }
21615 }
21616 
21617 /*
21618 ** If zNum represents an integer that will fit in 32-bits, then set
21619 ** *pValue to that integer and return true.  Otherwise return false.
21620 **
21621 ** Any non-numeric characters that following zNum are ignored.
21622 ** This is different from sqlite3Atoi64() which requires the
21623 ** input number to be zero-terminated.
21624 */
21625 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21626   sqlite_int64 v = 0;
21627   int i, c;
21628   int neg = 0;
21629   if( zNum[0]=='-' ){
21630     neg = 1;
21631     zNum++;
21632   }else if( zNum[0]=='+' ){
21633     zNum++;
21634   }
21635   while( zNum[0]=='0' ) zNum++;
21636   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21637     v = v*10 + c;
21638   }
21639 
21640   /* The longest decimal representation of a 32 bit integer is 10 digits:
21641   **
21642   **             1234567890
21643   **     2^31 -> 2147483648
21644   */
21645   testcase( i==10 );
21646   if( i>10 ){
21647     return 0;
21648   }
21649   testcase( v-neg==2147483647 );
21650   if( v-neg>2147483647 ){
21651     return 0;
21652   }
21653   if( neg ){
21654     v = -v;
21655   }
21656   *pValue = (int)v;
21657   return 1;
21658 }
21659 
21660 /*
21661 ** Return a 32-bit integer value extracted from a string.  If the
21662 ** string is not an integer, just return 0.
21663 */
21664 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21665   int x = 0;
21666   if( z ) sqlite3GetInt32(z, &x);
21667   return x;
21668 }
21669 
21670 /*
21671 ** The variable-length integer encoding is as follows:
21672 **
21673 ** KEY:
21674 **         A = 0xxxxxxx    7 bits of data and one flag bit
21675 **         B = 1xxxxxxx    7 bits of data and one flag bit
21676 **         C = xxxxxxxx    8 bits of data
21677 **
21678 **  7 bits - A
21679 ** 14 bits - BA
21680 ** 21 bits - BBA
21681 ** 28 bits - BBBA
21682 ** 35 bits - BBBBA
21683 ** 42 bits - BBBBBA
21684 ** 49 bits - BBBBBBA
21685 ** 56 bits - BBBBBBBA
21686 ** 64 bits - BBBBBBBBC
21687 */
21688 
21689 /*
21690 ** Write a 64-bit variable-length integer to memory starting at p[0].
21691 ** The length of data write will be between 1 and 9 bytes.  The number
21692 ** of bytes written is returned.
21693 **
21694 ** A variable-length integer consists of the lower 7 bits of each byte
21695 ** for all bytes that have the 8th bit set and one byte with the 8th
21696 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21697 ** 8 bits and is the last byte.
21698 */
21699 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21700   int i, j, n;
21701   u8 buf[10];
21702   if( v & (((u64)0xff000000)<<32) ){
21703     p[8] = (u8)v;
21704     v >>= 8;
21705     for(i=7; i>=0; i--){
21706       p[i] = (u8)((v & 0x7f) | 0x80);
21707       v >>= 7;
21708     }
21709     return 9;
21710   }
21711   n = 0;
21712   do{
21713     buf[n++] = (u8)((v & 0x7f) | 0x80);
21714     v >>= 7;
21715   }while( v!=0 );
21716   buf[0] &= 0x7f;
21717   assert( n<=9 );
21718   for(i=0, j=n-1; j>=0; j--, i++){
21719     p[i] = buf[j];
21720   }
21721   return n;
21722 }
21723 
21724 /*
21725 ** This routine is a faster version of sqlite3PutVarint() that only
21726 ** works for 32-bit positive integers and which is optimized for
21727 ** the common case of small integers.  A MACRO version, putVarint32,
21728 ** is provided which inlines the single-byte case.  All code should use
21729 ** the MACRO version as this function assumes the single-byte case has
21730 ** already been handled.
21731 */
21732 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21733 #ifndef putVarint32
21734   if( (v & ~0x7f)==0 ){
21735     p[0] = v;
21736     return 1;
21737   }
21738 #endif
21739   if( (v & ~0x3fff)==0 ){
21740     p[0] = (u8)((v>>7) | 0x80);
21741     p[1] = (u8)(v & 0x7f);
21742     return 2;
21743   }
21744   return sqlite3PutVarint(p, v);
21745 }
21746 
21747 /*
21748 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21749 ** are defined here rather than simply putting the constant expressions
21750 ** inline in order to work around bugs in the RVT compiler.
21751 **
21752 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21753 **
21754 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21755 */
21756 #define SLOT_2_0     0x001fc07f
21757 #define SLOT_4_2_0   0xf01fc07f
21758 
21759 
21760 /*
21761 ** Read a 64-bit variable-length integer from memory starting at p[0].
21762 ** Return the number of bytes read.  The value is stored in *v.
21763 */
21764 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21765   u32 a,b,s;
21766 
21767   a = *p;
21768   /* a: p0 (unmasked) */
21769   if (!(a&0x80))
21770   {
21771     *v = a;
21772     return 1;
21773   }
21774 
21775   p++;
21776   b = *p;
21777   /* b: p1 (unmasked) */
21778   if (!(b&0x80))
21779   {
21780     a &= 0x7f;
21781     a = a<<7;
21782     a |= b;
21783     *v = a;
21784     return 2;
21785   }
21786 
21787   /* Verify that constants are precomputed correctly */
21788   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21789   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21790 
21791   p++;
21792   a = a<<14;
21793   a |= *p;
21794   /* a: p0<<14 | p2 (unmasked) */
21795   if (!(a&0x80))
21796   {
21797     a &= SLOT_2_0;
21798     b &= 0x7f;
21799     b = b<<7;
21800     a |= b;
21801     *v = a;
21802     return 3;
21803   }
21804 
21805   /* CSE1 from below */
21806   a &= SLOT_2_0;
21807   p++;
21808   b = b<<14;
21809   b |= *p;
21810   /* b: p1<<14 | p3 (unmasked) */
21811   if (!(b&0x80))
21812   {
21813     b &= SLOT_2_0;
21814     /* moved CSE1 up */
21815     /* a &= (0x7f<<14)|(0x7f); */
21816     a = a<<7;
21817     a |= b;
21818     *v = a;
21819     return 4;
21820   }
21821 
21822   /* a: p0<<14 | p2 (masked) */
21823   /* b: p1<<14 | p3 (unmasked) */
21824   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21825   /* moved CSE1 up */
21826   /* a &= (0x7f<<14)|(0x7f); */
21827   b &= SLOT_2_0;
21828   s = a;
21829   /* s: p0<<14 | p2 (masked) */
21830 
21831   p++;
21832   a = a<<14;
21833   a |= *p;
21834   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21835   if (!(a&0x80))
21836   {
21837     /* we can skip these cause they were (effectively) done above in calc'ing s */
21838     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21839     /* b &= (0x7f<<14)|(0x7f); */
21840     b = b<<7;
21841     a |= b;
21842     s = s>>18;
21843     *v = ((u64)s)<<32 | a;
21844     return 5;
21845   }
21846 
21847   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21848   s = s<<7;
21849   s |= b;
21850   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21851 
21852   p++;
21853   b = b<<14;
21854   b |= *p;
21855   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21856   if (!(b&0x80))
21857   {
21858     /* we can skip this cause it was (effectively) done above in calc'ing s */
21859     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21860     a &= SLOT_2_0;
21861     a = a<<7;
21862     a |= b;
21863     s = s>>18;
21864     *v = ((u64)s)<<32 | a;
21865     return 6;
21866   }
21867 
21868   p++;
21869   a = a<<14;
21870   a |= *p;
21871   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21872   if (!(a&0x80))
21873   {
21874     a &= SLOT_4_2_0;
21875     b &= SLOT_2_0;
21876     b = b<<7;
21877     a |= b;
21878     s = s>>11;
21879     *v = ((u64)s)<<32 | a;
21880     return 7;
21881   }
21882 
21883   /* CSE2 from below */
21884   a &= SLOT_2_0;
21885   p++;
21886   b = b<<14;
21887   b |= *p;
21888   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21889   if (!(b&0x80))
21890   {
21891     b &= SLOT_4_2_0;
21892     /* moved CSE2 up */
21893     /* a &= (0x7f<<14)|(0x7f); */
21894     a = a<<7;
21895     a |= b;
21896     s = s>>4;
21897     *v = ((u64)s)<<32 | a;
21898     return 8;
21899   }
21900 
21901   p++;
21902   a = a<<15;
21903   a |= *p;
21904   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21905 
21906   /* moved CSE2 up */
21907   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21908   b &= SLOT_2_0;
21909   b = b<<8;
21910   a |= b;
21911 
21912   s = s<<4;
21913   b = p[-4];
21914   b &= 0x7f;
21915   b = b>>3;
21916   s |= b;
21917 
21918   *v = ((u64)s)<<32 | a;
21919 
21920   return 9;
21921 }
21922 
21923 /*
21924 ** Read a 32-bit variable-length integer from memory starting at p[0].
21925 ** Return the number of bytes read.  The value is stored in *v.
21926 **
21927 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21928 ** integer, then set *v to 0xffffffff.
21929 **
21930 ** A MACRO version, getVarint32, is provided which inlines the
21931 ** single-byte case.  All code should use the MACRO version as
21932 ** this function assumes the single-byte case has already been handled.
21933 */
21934 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21935   u32 a,b;
21936 
21937   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21938   ** by the getVarin32() macro */
21939   a = *p;
21940   /* a: p0 (unmasked) */
21941 #ifndef getVarint32
21942   if (!(a&0x80))
21943   {
21944     /* Values between 0 and 127 */
21945     *v = a;
21946     return 1;
21947   }
21948 #endif
21949 
21950   /* The 2-byte case */
21951   p++;
21952   b = *p;
21953   /* b: p1 (unmasked) */
21954   if (!(b&0x80))
21955   {
21956     /* Values between 128 and 16383 */
21957     a &= 0x7f;
21958     a = a<<7;
21959     *v = a | b;
21960     return 2;
21961   }
21962 
21963   /* The 3-byte case */
21964   p++;
21965   a = a<<14;
21966   a |= *p;
21967   /* a: p0<<14 | p2 (unmasked) */
21968   if (!(a&0x80))
21969   {
21970     /* Values between 16384 and 2097151 */
21971     a &= (0x7f<<14)|(0x7f);
21972     b &= 0x7f;
21973     b = b<<7;
21974     *v = a | b;
21975     return 3;
21976   }
21977 
21978   /* A 32-bit varint is used to store size information in btrees.
21979   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21980   ** A 3-byte varint is sufficient, for example, to record the size
21981   ** of a 1048569-byte BLOB or string.
21982   **
21983   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21984   ** rare larger cases can be handled by the slower 64-bit varint
21985   ** routine.
21986   */
21987 #if 1
21988   {
21989     u64 v64;
21990     u8 n;
21991 
21992     p -= 2;
21993     n = sqlite3GetVarint(p, &v64);
21994     assert( n>3 && n<=9 );
21995     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21996       *v = 0xffffffff;
21997     }else{
21998       *v = (u32)v64;
21999     }
22000     return n;
22001   }
22002 
22003 #else
22004   /* For following code (kept for historical record only) shows an
22005   ** unrolling for the 3- and 4-byte varint cases.  This code is
22006   ** slightly faster, but it is also larger and much harder to test.
22007   */
22008   p++;
22009   b = b<<14;
22010   b |= *p;
22011   /* b: p1<<14 | p3 (unmasked) */
22012   if (!(b&0x80))
22013   {
22014     /* Values between 2097152 and 268435455 */
22015     b &= (0x7f<<14)|(0x7f);
22016     a &= (0x7f<<14)|(0x7f);
22017     a = a<<7;
22018     *v = a | b;
22019     return 4;
22020   }
22021 
22022   p++;
22023   a = a<<14;
22024   a |= *p;
22025   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22026   if (!(a&0x80))
22027   {
22028     /* Values  between 268435456 and 34359738367 */
22029     a &= SLOT_4_2_0;
22030     b &= SLOT_4_2_0;
22031     b = b<<7;
22032     *v = a | b;
22033     return 5;
22034   }
22035 
22036   /* We can only reach this point when reading a corrupt database
22037   ** file.  In that case we are not in any hurry.  Use the (relatively
22038   ** slow) general-purpose sqlite3GetVarint() routine to extract the
22039   ** value. */
22040   {
22041     u64 v64;
22042     u8 n;
22043 
22044     p -= 4;
22045     n = sqlite3GetVarint(p, &v64);
22046     assert( n>5 && n<=9 );
22047     *v = (u32)v64;
22048     return n;
22049   }
22050 #endif
22051 }
22052 
22053 /*
22054 ** Return the number of bytes that will be needed to store the given
22055 ** 64-bit integer.
22056 */
22057 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22058   int i = 0;
22059   do{
22060     i++;
22061     v >>= 7;
22062   }while( v!=0 && ALWAYS(i<9) );
22063   return i;
22064 }
22065 
22066 
22067 /*
22068 ** Read or write a four-byte big-endian integer value.
22069 */
22070 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22071   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22072 }
22073 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22074   p[0] = (u8)(v>>24);
22075   p[1] = (u8)(v>>16);
22076   p[2] = (u8)(v>>8);
22077   p[3] = (u8)v;
22078 }
22079 
22080 
22081 
22082 /*
22083 ** Translate a single byte of Hex into an integer.
22084 ** This routine only works if h really is a valid hexadecimal
22085 ** character:  0..9a..fA..F
22086 */
22087 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22088   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22089 #ifdef SQLITE_ASCII
22090   h += 9*(1&(h>>6));
22091 #endif
22092 #ifdef SQLITE_EBCDIC
22093   h += 9*(1&~(h>>4));
22094 #endif
22095   return (u8)(h & 0xf);
22096 }
22097 
22098 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22099 /*
22100 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22101 ** value.  Return a pointer to its binary value.  Space to hold the
22102 ** binary value has been obtained from malloc and must be freed by
22103 ** the calling routine.
22104 */
22105 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22106   char *zBlob;
22107   int i;
22108 
22109   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22110   n--;
22111   if( zBlob ){
22112     for(i=0; i<n; i+=2){
22113       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22114     }
22115     zBlob[i/2] = 0;
22116   }
22117   return zBlob;
22118 }
22119 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22120 
22121 /*
22122 ** Log an error that is an API call on a connection pointer that should
22123 ** not have been used.  The "type" of connection pointer is given as the
22124 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22125 */
22126 static void logBadConnection(const char *zType){
22127   sqlite3_log(SQLITE_MISUSE,
22128      "API call with %s database connection pointer",
22129      zType
22130   );
22131 }
22132 
22133 /*
22134 ** Check to make sure we have a valid db pointer.  This test is not
22135 ** foolproof but it does provide some measure of protection against
22136 ** misuse of the interface such as passing in db pointers that are
22137 ** NULL or which have been previously closed.  If this routine returns
22138 ** 1 it means that the db pointer is valid and 0 if it should not be
22139 ** dereferenced for any reason.  The calling function should invoke
22140 ** SQLITE_MISUSE immediately.
22141 **
22142 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22143 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22144 ** open properly and is not fit for general use but which can be
22145 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22146 */
22147 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22148   u32 magic;
22149   if( db==0 ){
22150     logBadConnection("NULL");
22151     return 0;
22152   }
22153   magic = db->magic;
22154   if( magic!=SQLITE_MAGIC_OPEN ){
22155     if( sqlite3SafetyCheckSickOrOk(db) ){
22156       testcase( sqlite3GlobalConfig.xLog!=0 );
22157       logBadConnection("unopened");
22158     }
22159     return 0;
22160   }else{
22161     return 1;
22162   }
22163 }
22164 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22165   u32 magic;
22166   magic = db->magic;
22167   if( magic!=SQLITE_MAGIC_SICK &&
22168       magic!=SQLITE_MAGIC_OPEN &&
22169       magic!=SQLITE_MAGIC_BUSY ){
22170     testcase( sqlite3GlobalConfig.xLog!=0 );
22171     logBadConnection("invalid");
22172     return 0;
22173   }else{
22174     return 1;
22175   }
22176 }
22177 
22178 /*
22179 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22180 ** the other 64-bit signed integer at *pA and store the result in *pA.
22181 ** Return 0 on success.  Or if the operation would have resulted in an
22182 ** overflow, leave *pA unchanged and return 1.
22183 */
22184 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22185   i64 iA = *pA;
22186   testcase( iA==0 ); testcase( iA==1 );
22187   testcase( iB==-1 ); testcase( iB==0 );
22188   if( iB>=0 ){
22189     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22190     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22191     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22192     *pA += iB;
22193   }else{
22194     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22195     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22196     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22197     *pA += iB;
22198   }
22199   return 0;
22200 }
22201 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22202   testcase( iB==SMALLEST_INT64+1 );
22203   if( iB==SMALLEST_INT64 ){
22204     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22205     if( (*pA)>=0 ) return 1;
22206     *pA -= iB;
22207     return 0;
22208   }else{
22209     return sqlite3AddInt64(pA, -iB);
22210   }
22211 }
22212 #define TWOPOWER32 (((i64)1)<<32)
22213 #define TWOPOWER31 (((i64)1)<<31)
22214 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22215   i64 iA = *pA;
22216   i64 iA1, iA0, iB1, iB0, r;
22217 
22218   iA1 = iA/TWOPOWER32;
22219   iA0 = iA % TWOPOWER32;
22220   iB1 = iB/TWOPOWER32;
22221   iB0 = iB % TWOPOWER32;
22222   if( iA1*iB1 != 0 ) return 1;
22223   assert( iA1*iB0==0 || iA0*iB1==0 );
22224   r = iA1*iB0 + iA0*iB1;
22225   testcase( r==(-TWOPOWER31)-1 );
22226   testcase( r==(-TWOPOWER31) );
22227   testcase( r==TWOPOWER31 );
22228   testcase( r==TWOPOWER31-1 );
22229   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22230   r *= TWOPOWER32;
22231   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22232   *pA = r;
22233   return 0;
22234 }
22235 
22236 /*
22237 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
22238 ** if the integer has a value of -2147483648, return +2147483647
22239 */
22240 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22241   if( x>=0 ) return x;
22242   if( x==(int)0x80000000 ) return 0x7fffffff;
22243   return -x;
22244 }
22245 
22246 #ifdef SQLITE_ENABLE_8_3_NAMES
22247 /*
22248 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22249 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22250 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22251 ** three characters, then shorten the suffix on z[] to be the last three
22252 ** characters of the original suffix.
22253 **
22254 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22255 ** do the suffix shortening regardless of URI parameter.
22256 **
22257 ** Examples:
22258 **
22259 **     test.db-journal    =>   test.nal
22260 **     test.db-wal        =>   test.wal
22261 **     test.db-shm        =>   test.shm
22262 **     test.db-mj7f3319fa =>   test.9fa
22263 */
22264 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22265 #if SQLITE_ENABLE_8_3_NAMES<2
22266   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22267 #endif
22268   {
22269     int i, sz;
22270     sz = sqlite3Strlen30(z);
22271     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22272     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22273   }
22274 }
22275 #endif
22276 
22277 /************** End of util.c ************************************************/
22278 /************** Begin file hash.c ********************************************/
22279 /*
22280 ** 2001 September 22
22281 **
22282 ** The author disclaims copyright to this source code.  In place of
22283 ** a legal notice, here is a blessing:
22284 **
22285 **    May you do good and not evil.
22286 **    May you find forgiveness for yourself and forgive others.
22287 **    May you share freely, never taking more than you give.
22288 **
22289 *************************************************************************
22290 ** This is the implementation of generic hash-tables
22291 ** used in SQLite.
22292 */
22293 /* #include <assert.h> */
22294 
22295 /* Turn bulk memory into a hash table object by initializing the
22296 ** fields of the Hash structure.
22297 **
22298 ** "pNew" is a pointer to the hash table that is to be initialized.
22299 */
22300 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22301   assert( pNew!=0 );
22302   pNew->first = 0;
22303   pNew->count = 0;
22304   pNew->htsize = 0;
22305   pNew->ht = 0;
22306 }
22307 
22308 /* Remove all entries from a hash table.  Reclaim all memory.
22309 ** Call this routine to delete a hash table or to reset a hash table
22310 ** to the empty state.
22311 */
22312 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22313   HashElem *elem;         /* For looping over all elements of the table */
22314 
22315   assert( pH!=0 );
22316   elem = pH->first;
22317   pH->first = 0;
22318   sqlite3_free(pH->ht);
22319   pH->ht = 0;
22320   pH->htsize = 0;
22321   while( elem ){
22322     HashElem *next_elem = elem->next;
22323     sqlite3_free(elem);
22324     elem = next_elem;
22325   }
22326   pH->count = 0;
22327 }
22328 
22329 /*
22330 ** The hashing function.
22331 */
22332 static unsigned int strHash(const char *z, int nKey){
22333   int h = 0;
22334   assert( nKey>=0 );
22335   while( nKey > 0  ){
22336     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22337     nKey--;
22338   }
22339   return h;
22340 }
22341 
22342 
22343 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22344 ** insert pNew into the pEntry hash bucket.
22345 */
22346 static void insertElement(
22347   Hash *pH,              /* The complete hash table */
22348   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22349   HashElem *pNew         /* The element to be inserted */
22350 ){
22351   HashElem *pHead;       /* First element already in pEntry */
22352   if( pEntry ){
22353     pHead = pEntry->count ? pEntry->chain : 0;
22354     pEntry->count++;
22355     pEntry->chain = pNew;
22356   }else{
22357     pHead = 0;
22358   }
22359   if( pHead ){
22360     pNew->next = pHead;
22361     pNew->prev = pHead->prev;
22362     if( pHead->prev ){ pHead->prev->next = pNew; }
22363     else             { pH->first = pNew; }
22364     pHead->prev = pNew;
22365   }else{
22366     pNew->next = pH->first;
22367     if( pH->first ){ pH->first->prev = pNew; }
22368     pNew->prev = 0;
22369     pH->first = pNew;
22370   }
22371 }
22372 
22373 
22374 /* Resize the hash table so that it cantains "new_size" buckets.
22375 **
22376 ** The hash table might fail to resize if sqlite3_malloc() fails or
22377 ** if the new size is the same as the prior size.
22378 ** Return TRUE if the resize occurs and false if not.
22379 */
22380 static int rehash(Hash *pH, unsigned int new_size){
22381   struct _ht *new_ht;            /* The new hash table */
22382   HashElem *elem, *next_elem;    /* For looping over existing elements */
22383 
22384 #if SQLITE_MALLOC_SOFT_LIMIT>0
22385   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22386     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22387   }
22388   if( new_size==pH->htsize ) return 0;
22389 #endif
22390 
22391   /* The inability to allocates space for a larger hash table is
22392   ** a performance hit but it is not a fatal error.  So mark the
22393   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
22394   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22395   ** only zeroes the requested number of bytes whereas this module will
22396   ** use the actual amount of space allocated for the hash table (which
22397   ** may be larger than the requested amount).
22398   */
22399   sqlite3BeginBenignMalloc();
22400   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22401   sqlite3EndBenignMalloc();
22402 
22403   if( new_ht==0 ) return 0;
22404   sqlite3_free(pH->ht);
22405   pH->ht = new_ht;
22406   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22407   memset(new_ht, 0, new_size*sizeof(struct _ht));
22408   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22409     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22410     next_elem = elem->next;
22411     insertElement(pH, &new_ht[h], elem);
22412   }
22413   return 1;
22414 }
22415 
22416 /* This function (for internal use only) locates an element in an
22417 ** hash table that matches the given key.  The hash for this key has
22418 ** already been computed and is passed as the 4th parameter.
22419 */
22420 static HashElem *findElementGivenHash(
22421   const Hash *pH,     /* The pH to be searched */
22422   const char *pKey,   /* The key we are searching for */
22423   int nKey,           /* Bytes in key (not counting zero terminator) */
22424   unsigned int h      /* The hash for this key. */
22425 ){
22426   HashElem *elem;                /* Used to loop thru the element list */
22427   int count;                     /* Number of elements left to test */
22428 
22429   if( pH->ht ){
22430     struct _ht *pEntry = &pH->ht[h];
22431     elem = pEntry->chain;
22432     count = pEntry->count;
22433   }else{
22434     elem = pH->first;
22435     count = pH->count;
22436   }
22437   while( count-- && ALWAYS(elem) ){
22438     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
22439       return elem;
22440     }
22441     elem = elem->next;
22442   }
22443   return 0;
22444 }
22445 
22446 /* Remove a single entry from the hash table given a pointer to that
22447 ** element and a hash on the element's key.
22448 */
22449 static void removeElementGivenHash(
22450   Hash *pH,         /* The pH containing "elem" */
22451   HashElem* elem,   /* The element to be removed from the pH */
22452   unsigned int h    /* Hash value for the element */
22453 ){
22454   struct _ht *pEntry;
22455   if( elem->prev ){
22456     elem->prev->next = elem->next;
22457   }else{
22458     pH->first = elem->next;
22459   }
22460   if( elem->next ){
22461     elem->next->prev = elem->prev;
22462   }
22463   if( pH->ht ){
22464     pEntry = &pH->ht[h];
22465     if( pEntry->chain==elem ){
22466       pEntry->chain = elem->next;
22467     }
22468     pEntry->count--;
22469     assert( pEntry->count>=0 );
22470   }
22471   sqlite3_free( elem );
22472   pH->count--;
22473   if( pH->count==0 ){
22474     assert( pH->first==0 );
22475     assert( pH->count==0 );
22476     sqlite3HashClear(pH);
22477   }
22478 }
22479 
22480 /* Attempt to locate an element of the hash table pH with a key
22481 ** that matches pKey,nKey.  Return the data for this element if it is
22482 ** found, or NULL if there is no match.
22483 */
22484 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22485   HashElem *elem;    /* The element that matches key */
22486   unsigned int h;    /* A hash on key */
22487 
22488   assert( pH!=0 );
22489   assert( pKey!=0 );
22490   assert( nKey>=0 );
22491   if( pH->ht ){
22492     h = strHash(pKey, nKey) % pH->htsize;
22493   }else{
22494     h = 0;
22495   }
22496   elem = findElementGivenHash(pH, pKey, nKey, h);
22497   return elem ? elem->data : 0;
22498 }
22499 
22500 /* Insert an element into the hash table pH.  The key is pKey,nKey
22501 ** and the data is "data".
22502 **
22503 ** If no element exists with a matching key, then a new
22504 ** element is created and NULL is returned.
22505 **
22506 ** If another element already exists with the same key, then the
22507 ** new data replaces the old data and the old data is returned.
22508 ** The key is not copied in this instance.  If a malloc fails, then
22509 ** the new data is returned and the hash table is unchanged.
22510 **
22511 ** If the "data" parameter to this function is NULL, then the
22512 ** element corresponding to "key" is removed from the hash table.
22513 */
22514 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22515   unsigned int h;       /* the hash of the key modulo hash table size */
22516   HashElem *elem;       /* Used to loop thru the element list */
22517   HashElem *new_elem;   /* New element added to the pH */
22518 
22519   assert( pH!=0 );
22520   assert( pKey!=0 );
22521   assert( nKey>=0 );
22522   if( pH->htsize ){
22523     h = strHash(pKey, nKey) % pH->htsize;
22524   }else{
22525     h = 0;
22526   }
22527   elem = findElementGivenHash(pH,pKey,nKey,h);
22528   if( elem ){
22529     void *old_data = elem->data;
22530     if( data==0 ){
22531       removeElementGivenHash(pH,elem,h);
22532     }else{
22533       elem->data = data;
22534       elem->pKey = pKey;
22535       assert(nKey==elem->nKey);
22536     }
22537     return old_data;
22538   }
22539   if( data==0 ) return 0;
22540   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22541   if( new_elem==0 ) return data;
22542   new_elem->pKey = pKey;
22543   new_elem->nKey = nKey;
22544   new_elem->data = data;
22545   pH->count++;
22546   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22547     if( rehash(pH, pH->count*2) ){
22548       assert( pH->htsize>0 );
22549       h = strHash(pKey, nKey) % pH->htsize;
22550     }
22551   }
22552   if( pH->ht ){
22553     insertElement(pH, &pH->ht[h], new_elem);
22554   }else{
22555     insertElement(pH, 0, new_elem);
22556   }
22557   return 0;
22558 }
22559 
22560 /************** End of hash.c ************************************************/
22561 /************** Begin file opcodes.c *****************************************/
22562 /* Automatically generated.  Do not edit */
22563 /* See the mkopcodec.awk script for details. */
22564 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22565 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22566  static const char *const azName[] = { "?",
22567      /*   1 */ "Goto",
22568      /*   2 */ "Gosub",
22569      /*   3 */ "Return",
22570      /*   4 */ "Yield",
22571      /*   5 */ "HaltIfNull",
22572      /*   6 */ "Halt",
22573      /*   7 */ "Integer",
22574      /*   8 */ "Int64",
22575      /*   9 */ "String",
22576      /*  10 */ "Null",
22577      /*  11 */ "Blob",
22578      /*  12 */ "Variable",
22579      /*  13 */ "Move",
22580      /*  14 */ "Copy",
22581      /*  15 */ "SCopy",
22582      /*  16 */ "ResultRow",
22583      /*  17 */ "CollSeq",
22584      /*  18 */ "Function",
22585      /*  19 */ "Not",
22586      /*  20 */ "AddImm",
22587      /*  21 */ "MustBeInt",
22588      /*  22 */ "RealAffinity",
22589      /*  23 */ "Permutation",
22590      /*  24 */ "Compare",
22591      /*  25 */ "Jump",
22592      /*  26 */ "Once",
22593      /*  27 */ "If",
22594      /*  28 */ "IfNot",
22595      /*  29 */ "Column",
22596      /*  30 */ "Affinity",
22597      /*  31 */ "MakeRecord",
22598      /*  32 */ "Count",
22599      /*  33 */ "Savepoint",
22600      /*  34 */ "AutoCommit",
22601      /*  35 */ "Transaction",
22602      /*  36 */ "ReadCookie",
22603      /*  37 */ "SetCookie",
22604      /*  38 */ "VerifyCookie",
22605      /*  39 */ "OpenRead",
22606      /*  40 */ "OpenWrite",
22607      /*  41 */ "OpenAutoindex",
22608      /*  42 */ "OpenEphemeral",
22609      /*  43 */ "SorterOpen",
22610      /*  44 */ "OpenPseudo",
22611      /*  45 */ "Close",
22612      /*  46 */ "SeekLt",
22613      /*  47 */ "SeekLe",
22614      /*  48 */ "SeekGe",
22615      /*  49 */ "SeekGt",
22616      /*  50 */ "Seek",
22617      /*  51 */ "NotFound",
22618      /*  52 */ "Found",
22619      /*  53 */ "IsUnique",
22620      /*  54 */ "NotExists",
22621      /*  55 */ "Sequence",
22622      /*  56 */ "NewRowid",
22623      /*  57 */ "Insert",
22624      /*  58 */ "InsertInt",
22625      /*  59 */ "Delete",
22626      /*  60 */ "ResetCount",
22627      /*  61 */ "SorterCompare",
22628      /*  62 */ "SorterData",
22629      /*  63 */ "RowKey",
22630      /*  64 */ "RowData",
22631      /*  65 */ "Rowid",
22632      /*  66 */ "NullRow",
22633      /*  67 */ "Last",
22634      /*  68 */ "Or",
22635      /*  69 */ "And",
22636      /*  70 */ "SorterSort",
22637      /*  71 */ "Sort",
22638      /*  72 */ "Rewind",
22639      /*  73 */ "IsNull",
22640      /*  74 */ "NotNull",
22641      /*  75 */ "Ne",
22642      /*  76 */ "Eq",
22643      /*  77 */ "Gt",
22644      /*  78 */ "Le",
22645      /*  79 */ "Lt",
22646      /*  80 */ "Ge",
22647      /*  81 */ "SorterNext",
22648      /*  82 */ "BitAnd",
22649      /*  83 */ "BitOr",
22650      /*  84 */ "ShiftLeft",
22651      /*  85 */ "ShiftRight",
22652      /*  86 */ "Add",
22653      /*  87 */ "Subtract",
22654      /*  88 */ "Multiply",
22655      /*  89 */ "Divide",
22656      /*  90 */ "Remainder",
22657      /*  91 */ "Concat",
22658      /*  92 */ "Prev",
22659      /*  93 */ "BitNot",
22660      /*  94 */ "String8",
22661      /*  95 */ "Next",
22662      /*  96 */ "SorterInsert",
22663      /*  97 */ "IdxInsert",
22664      /*  98 */ "IdxDelete",
22665      /*  99 */ "IdxRowid",
22666      /* 100 */ "IdxLT",
22667      /* 101 */ "IdxGE",
22668      /* 102 */ "Destroy",
22669      /* 103 */ "Clear",
22670      /* 104 */ "CreateIndex",
22671      /* 105 */ "CreateTable",
22672      /* 106 */ "ParseSchema",
22673      /* 107 */ "LoadAnalysis",
22674      /* 108 */ "DropTable",
22675      /* 109 */ "DropIndex",
22676      /* 110 */ "DropTrigger",
22677      /* 111 */ "IntegrityCk",
22678      /* 112 */ "RowSetAdd",
22679      /* 113 */ "RowSetRead",
22680      /* 114 */ "RowSetTest",
22681      /* 115 */ "Program",
22682      /* 116 */ "Param",
22683      /* 117 */ "FkCounter",
22684      /* 118 */ "FkIfZero",
22685      /* 119 */ "MemMax",
22686      /* 120 */ "IfPos",
22687      /* 121 */ "IfNeg",
22688      /* 122 */ "IfZero",
22689      /* 123 */ "AggStep",
22690      /* 124 */ "AggFinal",
22691      /* 125 */ "Checkpoint",
22692      /* 126 */ "JournalMode",
22693      /* 127 */ "Vacuum",
22694      /* 128 */ "IncrVacuum",
22695      /* 129 */ "Expire",
22696      /* 130 */ "Real",
22697      /* 131 */ "TableLock",
22698      /* 132 */ "VBegin",
22699      /* 133 */ "VCreate",
22700      /* 134 */ "VDestroy",
22701      /* 135 */ "VOpen",
22702      /* 136 */ "VFilter",
22703      /* 137 */ "VColumn",
22704      /* 138 */ "VNext",
22705      /* 139 */ "VRename",
22706      /* 140 */ "VUpdate",
22707      /* 141 */ "ToText",
22708      /* 142 */ "ToBlob",
22709      /* 143 */ "ToNumeric",
22710      /* 144 */ "ToInt",
22711      /* 145 */ "ToReal",
22712      /* 146 */ "Pagecount",
22713      /* 147 */ "MaxPgcnt",
22714      /* 148 */ "Trace",
22715      /* 149 */ "Noop",
22716      /* 150 */ "Explain",
22717   };
22718   return azName[i];
22719 }
22720 #endif
22721 
22722 /************** End of opcodes.c *********************************************/
22723 /************** Begin file os_unix.c *****************************************/
22724 /*
22725 ** 2004 May 22
22726 **
22727 ** The author disclaims copyright to this source code.  In place of
22728 ** a legal notice, here is a blessing:
22729 **
22730 **    May you do good and not evil.
22731 **    May you find forgiveness for yourself and forgive others.
22732 **    May you share freely, never taking more than you give.
22733 **
22734 ******************************************************************************
22735 **
22736 ** This file contains the VFS implementation for unix-like operating systems
22737 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22738 **
22739 ** There are actually several different VFS implementations in this file.
22740 ** The differences are in the way that file locking is done.  The default
22741 ** implementation uses Posix Advisory Locks.  Alternative implementations
22742 ** use flock(), dot-files, various proprietary locking schemas, or simply
22743 ** skip locking all together.
22744 **
22745 ** This source file is organized into divisions where the logic for various
22746 ** subfunctions is contained within the appropriate division.  PLEASE
22747 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22748 ** in the correct division and should be clearly labeled.
22749 **
22750 ** The layout of divisions is as follows:
22751 **
22752 **   *  General-purpose declarations and utility functions.
22753 **   *  Unique file ID logic used by VxWorks.
22754 **   *  Various locking primitive implementations (all except proxy locking):
22755 **      + for Posix Advisory Locks
22756 **      + for no-op locks
22757 **      + for dot-file locks
22758 **      + for flock() locking
22759 **      + for named semaphore locks (VxWorks only)
22760 **      + for AFP filesystem locks (MacOSX only)
22761 **   *  sqlite3_file methods not associated with locking.
22762 **   *  Definitions of sqlite3_io_methods objects for all locking
22763 **      methods plus "finder" functions for each locking method.
22764 **   *  sqlite3_vfs method implementations.
22765 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22766 **   *  Definitions of sqlite3_vfs objects for all locking methods
22767 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22768 */
22769 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22770 
22771 /* Use posix_fallocate() if it is available
22772 */
22773 #if !defined(HAVE_POSIX_FALLOCATE) \
22774       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22775 # define HAVE_POSIX_FALLOCATE 1
22776 #endif
22777 
22778 /*
22779 ** There are various methods for file locking used for concurrency
22780 ** control:
22781 **
22782 **   1. POSIX locking (the default),
22783 **   2. No locking,
22784 **   3. Dot-file locking,
22785 **   4. flock() locking,
22786 **   5. AFP locking (OSX only),
22787 **   6. Named POSIX semaphores (VXWorks only),
22788 **   7. proxy locking. (OSX only)
22789 **
22790 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22791 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22792 ** selection of the appropriate locking style based on the filesystem
22793 ** where the database is located.
22794 */
22795 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22796 #  if defined(__APPLE__)
22797 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22798 #  else
22799 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22800 #  endif
22801 #endif
22802 
22803 /*
22804 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
22805 ** vxworks, or 0 otherwise.
22806 */
22807 #ifndef OS_VXWORKS
22808 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22809 #    define OS_VXWORKS 1
22810 #  else
22811 #    define OS_VXWORKS 0
22812 #  endif
22813 #endif
22814 
22815 /*
22816 ** These #defines should enable >2GB file support on Posix if the
22817 ** underlying operating system supports it.  If the OS lacks
22818 ** large file support, these should be no-ops.
22819 **
22820 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22821 ** on the compiler command line.  This is necessary if you are compiling
22822 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22823 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22824 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22825 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22826 ** portability you should omit LFS.
22827 **
22828 ** The previous paragraph was written in 2005.  (This paragraph is written
22829 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22830 ** you should probably leave LFS enabled.  But some embedded platforms might
22831 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22832 */
22833 #ifndef SQLITE_DISABLE_LFS
22834 # define _LARGE_FILE       1
22835 # ifndef _FILE_OFFSET_BITS
22836 #   define _FILE_OFFSET_BITS 64
22837 # endif
22838 # define _LARGEFILE_SOURCE 1
22839 #endif
22840 
22841 /*
22842 ** standard include files.
22843 */
22844 #include <sys/types.h>
22845 #include <sys/stat.h>
22846 #include <fcntl.h>
22847 #include <unistd.h>
22848 /* #include <time.h> */
22849 #include <sys/time.h>
22850 #include <errno.h>
22851 #ifndef SQLITE_OMIT_WAL
22852 #include <sys/mman.h>
22853 #endif
22854 
22855 
22856 #if SQLITE_ENABLE_LOCKING_STYLE
22857 # include <sys/ioctl.h>
22858 # if OS_VXWORKS
22859 #  include <semaphore.h>
22860 #  include <limits.h>
22861 # else
22862 #  include <sys/file.h>
22863 #  include <sys/param.h>
22864 # endif
22865 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22866 
22867 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22868 # include <sys/mount.h>
22869 #endif
22870 
22871 #ifdef HAVE_UTIME
22872 # include <utime.h>
22873 #endif
22874 
22875 /*
22876 ** Allowed values of unixFile.fsFlags
22877 */
22878 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22879 
22880 /*
22881 ** If we are to be thread-safe, include the pthreads header and define
22882 ** the SQLITE_UNIX_THREADS macro.
22883 */
22884 #if SQLITE_THREADSAFE
22885 /* # include <pthread.h> */
22886 # define SQLITE_UNIX_THREADS 1
22887 #endif
22888 
22889 /*
22890 ** Default permissions when creating a new file
22891 */
22892 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22893 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22894 #endif
22895 
22896 /*
22897 ** Default permissions when creating auto proxy dir
22898 */
22899 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22900 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22901 #endif
22902 
22903 /*
22904 ** Maximum supported path-length.
22905 */
22906 #define MAX_PATHNAME 512
22907 
22908 /*
22909 ** Only set the lastErrno if the error code is a real error and not
22910 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22911 */
22912 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22913 
22914 /* Forward references */
22915 typedef struct unixShm unixShm;               /* Connection shared memory */
22916 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22917 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22918 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22919 
22920 /*
22921 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22922 ** cannot be closed immediately. In these cases, instances of the following
22923 ** structure are used to store the file descriptor while waiting for an
22924 ** opportunity to either close or reuse it.
22925 */
22926 struct UnixUnusedFd {
22927   int fd;                   /* File descriptor to close */
22928   int flags;                /* Flags this file descriptor was opened with */
22929   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22930 };
22931 
22932 /*
22933 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22934 ** VFS implementations.
22935 */
22936 typedef struct unixFile unixFile;
22937 struct unixFile {
22938   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22939   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
22940   unixInodeInfo *pInode;              /* Info about locks on this inode */
22941   int h;                              /* The file descriptor */
22942   unsigned char eFileLock;            /* The type of lock held on this fd */
22943   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
22944   int lastErrno;                      /* The unix errno from last I/O error */
22945   void *lockingContext;               /* Locking style specific state */
22946   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22947   const char *zPath;                  /* Name of the file */
22948   unixShm *pShm;                      /* Shared memory segment information */
22949   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22950 #ifdef __QNXNTO__
22951   int sectorSize;                     /* Device sector size */
22952   int deviceCharacteristics;          /* Precomputed device characteristics */
22953 #endif
22954 #if SQLITE_ENABLE_LOCKING_STYLE
22955   int openFlags;                      /* The flags specified at open() */
22956 #endif
22957 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22958   unsigned fsFlags;                   /* cached details from statfs() */
22959 #endif
22960 #if OS_VXWORKS
22961   struct vxworksFileId *pId;          /* Unique file ID */
22962 #endif
22963 #ifdef SQLITE_DEBUG
22964   /* The next group of variables are used to track whether or not the
22965   ** transaction counter in bytes 24-27 of database files are updated
22966   ** whenever any part of the database changes.  An assertion fault will
22967   ** occur if a file is updated without also updating the transaction
22968   ** counter.  This test is made to avoid new problems similar to the
22969   ** one described by ticket #3584.
22970   */
22971   unsigned char transCntrChng;   /* True if the transaction counter changed */
22972   unsigned char dbUpdate;        /* True if any part of database file changed */
22973   unsigned char inNormalWrite;   /* True if in a normal write operation */
22974 #endif
22975 #ifdef SQLITE_TEST
22976   /* In test mode, increase the size of this structure a bit so that
22977   ** it is larger than the struct CrashFile defined in test6.c.
22978   */
22979   char aPadding[32];
22980 #endif
22981 };
22982 
22983 /*
22984 ** Allowed values for the unixFile.ctrlFlags bitmask:
22985 */
22986 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
22987 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
22988 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
22989 #ifndef SQLITE_DISABLE_DIRSYNC
22990 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
22991 #else
22992 # define UNIXFILE_DIRSYNC    0x00
22993 #endif
22994 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
22995 #define UNIXFILE_DELETE      0x20     /* Delete on close */
22996 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
22997 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
22998 
22999 /*
23000 ** Include code that is common to all os_*.c files
23001 */
23002 /************** Include os_common.h in the middle of os_unix.c ***************/
23003 /************** Begin file os_common.h ***************************************/
23004 /*
23005 ** 2004 May 22
23006 **
23007 ** The author disclaims copyright to this source code.  In place of
23008 ** a legal notice, here is a blessing:
23009 **
23010 **    May you do good and not evil.
23011 **    May you find forgiveness for yourself and forgive others.
23012 **    May you share freely, never taking more than you give.
23013 **
23014 ******************************************************************************
23015 **
23016 ** This file contains macros and a little bit of code that is common to
23017 ** all of the platform-specific files (os_*.c) and is #included into those
23018 ** files.
23019 **
23020 ** This file should be #included by the os_*.c files only.  It is not a
23021 ** general purpose header file.
23022 */
23023 #ifndef _OS_COMMON_H_
23024 #define _OS_COMMON_H_
23025 
23026 /*
23027 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23028 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23029 ** switch.  The following code should catch this problem at compile-time.
23030 */
23031 #ifdef MEMORY_DEBUG
23032 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23033 #endif
23034 
23035 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23036 # ifndef SQLITE_DEBUG_OS_TRACE
23037 #   define SQLITE_DEBUG_OS_TRACE 0
23038 # endif
23039   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23040 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23041 #else
23042 # define OSTRACE(X)
23043 #endif
23044 
23045 /*
23046 ** Macros for performance tracing.  Normally turned off.  Only works
23047 ** on i486 hardware.
23048 */
23049 #ifdef SQLITE_PERFORMANCE_TRACE
23050 
23051 /*
23052 ** hwtime.h contains inline assembler code for implementing
23053 ** high-performance timing routines.
23054 */
23055 /************** Include hwtime.h in the middle of os_common.h ****************/
23056 /************** Begin file hwtime.h ******************************************/
23057 /*
23058 ** 2008 May 27
23059 **
23060 ** The author disclaims copyright to this source code.  In place of
23061 ** a legal notice, here is a blessing:
23062 **
23063 **    May you do good and not evil.
23064 **    May you find forgiveness for yourself and forgive others.
23065 **    May you share freely, never taking more than you give.
23066 **
23067 ******************************************************************************
23068 **
23069 ** This file contains inline asm code for retrieving "high-performance"
23070 ** counters for x86 class CPUs.
23071 */
23072 #ifndef _HWTIME_H_
23073 #define _HWTIME_H_
23074 
23075 /*
23076 ** The following routine only works on pentium-class (or newer) processors.
23077 ** It uses the RDTSC opcode to read the cycle count value out of the
23078 ** processor and returns that value.  This can be used for high-res
23079 ** profiling.
23080 */
23081 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23082       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23083 
23084   #if defined(__GNUC__)
23085 
23086   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23087      unsigned int lo, hi;
23088      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23089      return (sqlite_uint64)hi << 32 | lo;
23090   }
23091 
23092   #elif defined(_MSC_VER)
23093 
23094   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23095      __asm {
23096         rdtsc
23097         ret       ; return value at EDX:EAX
23098      }
23099   }
23100 
23101   #endif
23102 
23103 #elif (defined(__GNUC__) && defined(__x86_64__))
23104 
23105   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23106       unsigned long val;
23107       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23108       return val;
23109   }
23110 
23111 #elif (defined(__GNUC__) && defined(__ppc__))
23112 
23113   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23114       unsigned long long retval;
23115       unsigned long junk;
23116       __asm__ __volatile__ ("\n\
23117           1:      mftbu   %1\n\
23118                   mftb    %L0\n\
23119                   mftbu   %0\n\
23120                   cmpw    %0,%1\n\
23121                   bne     1b"
23122                   : "=r" (retval), "=r" (junk));
23123       return retval;
23124   }
23125 
23126 #else
23127 
23128   #error Need implementation of sqlite3Hwtime() for your platform.
23129 
23130   /*
23131   ** To compile without implementing sqlite3Hwtime() for your platform,
23132   ** you can remove the above #error and use the following
23133   ** stub function.  You will lose timing support for many
23134   ** of the debugging and testing utilities, but it should at
23135   ** least compile and run.
23136   */
23137 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23138 
23139 #endif
23140 
23141 #endif /* !defined(_HWTIME_H_) */
23142 
23143 /************** End of hwtime.h **********************************************/
23144 /************** Continuing where we left off in os_common.h ******************/
23145 
23146 static sqlite_uint64 g_start;
23147 static sqlite_uint64 g_elapsed;
23148 #define TIMER_START       g_start=sqlite3Hwtime()
23149 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23150 #define TIMER_ELAPSED     g_elapsed
23151 #else
23152 #define TIMER_START
23153 #define TIMER_END
23154 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23155 #endif
23156 
23157 /*
23158 ** If we compile with the SQLITE_TEST macro set, then the following block
23159 ** of code will give us the ability to simulate a disk I/O error.  This
23160 ** is used for testing the I/O recovery logic.
23161 */
23162 #ifdef SQLITE_TEST
23163 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23164 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23165 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23166 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23167 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23168 SQLITE_API int sqlite3_diskfull_pending = 0;
23169 SQLITE_API int sqlite3_diskfull = 0;
23170 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23171 #define SimulateIOError(CODE)  \
23172   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23173        || sqlite3_io_error_pending-- == 1 )  \
23174               { local_ioerr(); CODE; }
23175 static void local_ioerr(){
23176   IOTRACE(("IOERR\n"));
23177   sqlite3_io_error_hit++;
23178   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23179 }
23180 #define SimulateDiskfullError(CODE) \
23181    if( sqlite3_diskfull_pending ){ \
23182      if( sqlite3_diskfull_pending == 1 ){ \
23183        local_ioerr(); \
23184        sqlite3_diskfull = 1; \
23185        sqlite3_io_error_hit = 1; \
23186        CODE; \
23187      }else{ \
23188        sqlite3_diskfull_pending--; \
23189      } \
23190    }
23191 #else
23192 #define SimulateIOErrorBenign(X)
23193 #define SimulateIOError(A)
23194 #define SimulateDiskfullError(A)
23195 #endif
23196 
23197 /*
23198 ** When testing, keep a count of the number of open files.
23199 */
23200 #ifdef SQLITE_TEST
23201 SQLITE_API int sqlite3_open_file_count = 0;
23202 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23203 #else
23204 #define OpenCounter(X)
23205 #endif
23206 
23207 #endif /* !defined(_OS_COMMON_H_) */
23208 
23209 /************** End of os_common.h *******************************************/
23210 /************** Continuing where we left off in os_unix.c ********************/
23211 
23212 /*
23213 ** Define various macros that are missing from some systems.
23214 */
23215 #ifndef O_LARGEFILE
23216 # define O_LARGEFILE 0
23217 #endif
23218 #ifdef SQLITE_DISABLE_LFS
23219 # undef O_LARGEFILE
23220 # define O_LARGEFILE 0
23221 #endif
23222 #ifndef O_NOFOLLOW
23223 # define O_NOFOLLOW 0
23224 #endif
23225 #ifndef O_BINARY
23226 # define O_BINARY 0
23227 #endif
23228 
23229 /*
23230 ** The threadid macro resolves to the thread-id or to 0.  Used for
23231 ** testing and debugging only.
23232 */
23233 #if SQLITE_THREADSAFE
23234 #define threadid pthread_self()
23235 #else
23236 #define threadid 0
23237 #endif
23238 
23239 /*
23240 ** Different Unix systems declare open() in different ways.  Same use
23241 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23242 ** The difference is important when using a pointer to the function.
23243 **
23244 ** The safest way to deal with the problem is to always use this wrapper
23245 ** which always has the same well-defined interface.
23246 */
23247 static int posixOpen(const char *zFile, int flags, int mode){
23248   return open(zFile, flags, mode);
23249 }
23250 
23251 /*
23252 ** On some systems, calls to fchown() will trigger a message in a security
23253 ** log if they come from non-root processes.  So avoid calling fchown() if
23254 ** we are not running as root.
23255 */
23256 static int posixFchown(int fd, uid_t uid, gid_t gid){
23257   return geteuid() ? 0 : fchown(fd,uid,gid);
23258 }
23259 
23260 /* Forward reference */
23261 static int openDirectory(const char*, int*);
23262 
23263 /*
23264 ** Many system calls are accessed through pointer-to-functions so that
23265 ** they may be overridden at runtime to facilitate fault injection during
23266 ** testing and sandboxing.  The following array holds the names and pointers
23267 ** to all overrideable system calls.
23268 */
23269 static struct unix_syscall {
23270   const char *zName;            /* Name of the system call */
23271   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23272   sqlite3_syscall_ptr pDefault; /* Default value */
23273 } aSyscall[] = {
23274   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23275 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23276 
23277   { "close",        (sqlite3_syscall_ptr)close,      0  },
23278 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23279 
23280   { "access",       (sqlite3_syscall_ptr)access,     0  },
23281 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23282 
23283   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23284 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23285 
23286   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23287 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23288 
23289 /*
23290 ** The DJGPP compiler environment looks mostly like Unix, but it
23291 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23292 ** that always succeeds.  This means that locking does not occur under
23293 ** DJGPP.  But it is DOS - what did you expect?
23294 */
23295 #ifdef __DJGPP__
23296   { "fstat",        0,                 0  },
23297 #define osFstat(a,b,c)    0
23298 #else
23299   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23300 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23301 #endif
23302 
23303   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23304 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23305 
23306   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23307 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23308 
23309   { "read",         (sqlite3_syscall_ptr)read,       0  },
23310 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23311 
23312 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23313   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23314 #else
23315   { "pread",        (sqlite3_syscall_ptr)0,          0  },
23316 #endif
23317 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23318 
23319 #if defined(USE_PREAD64)
23320   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23321 #else
23322   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23323 #endif
23324 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23325 
23326   { "write",        (sqlite3_syscall_ptr)write,      0  },
23327 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23328 
23329 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23330   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23331 #else
23332   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23333 #endif
23334 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23335                     aSyscall[12].pCurrent)
23336 
23337 #if defined(USE_PREAD64)
23338   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23339 #else
23340   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23341 #endif
23342 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23343                     aSyscall[13].pCurrent)
23344 
23345   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23346 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23347 
23348 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23349   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23350 #else
23351   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23352 #endif
23353 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23354 
23355   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23356 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23357 
23358   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23359 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23360 
23361   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23362 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23363 
23364   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23365 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23366 
23367   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23368 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23369 
23370 }; /* End of the overrideable system calls */
23371 
23372 /*
23373 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23374 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23375 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23376 ** system call named zName.
23377 */
23378 static int unixSetSystemCall(
23379   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23380   const char *zName,            /* Name of system call to override */
23381   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23382 ){
23383   unsigned int i;
23384   int rc = SQLITE_NOTFOUND;
23385 
23386   UNUSED_PARAMETER(pNotUsed);
23387   if( zName==0 ){
23388     /* If no zName is given, restore all system calls to their default
23389     ** settings and return NULL
23390     */
23391     rc = SQLITE_OK;
23392     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23393       if( aSyscall[i].pDefault ){
23394         aSyscall[i].pCurrent = aSyscall[i].pDefault;
23395       }
23396     }
23397   }else{
23398     /* If zName is specified, operate on only the one system call
23399     ** specified.
23400     */
23401     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23402       if( strcmp(zName, aSyscall[i].zName)==0 ){
23403         if( aSyscall[i].pDefault==0 ){
23404           aSyscall[i].pDefault = aSyscall[i].pCurrent;
23405         }
23406         rc = SQLITE_OK;
23407         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23408         aSyscall[i].pCurrent = pNewFunc;
23409         break;
23410       }
23411     }
23412   }
23413   return rc;
23414 }
23415 
23416 /*
23417 ** Return the value of a system call.  Return NULL if zName is not a
23418 ** recognized system call name.  NULL is also returned if the system call
23419 ** is currently undefined.
23420 */
23421 static sqlite3_syscall_ptr unixGetSystemCall(
23422   sqlite3_vfs *pNotUsed,
23423   const char *zName
23424 ){
23425   unsigned int i;
23426 
23427   UNUSED_PARAMETER(pNotUsed);
23428   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23429     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23430   }
23431   return 0;
23432 }
23433 
23434 /*
23435 ** Return the name of the first system call after zName.  If zName==NULL
23436 ** then return the name of the first system call.  Return NULL if zName
23437 ** is the last system call or if zName is not the name of a valid
23438 ** system call.
23439 */
23440 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23441   int i = -1;
23442 
23443   UNUSED_PARAMETER(p);
23444   if( zName ){
23445     for(i=0; i<ArraySize(aSyscall)-1; i++){
23446       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23447     }
23448   }
23449   for(i++; i<ArraySize(aSyscall); i++){
23450     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23451   }
23452   return 0;
23453 }
23454 
23455 /*
23456 ** Invoke open().  Do so multiple times, until it either succeeds or
23457 ** fails for some reason other than EINTR.
23458 **
23459 ** If the file creation mode "m" is 0 then set it to the default for
23460 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23461 ** 0644) as modified by the system umask.  If m is not 0, then
23462 ** make the file creation mode be exactly m ignoring the umask.
23463 **
23464 ** The m parameter will be non-zero only when creating -wal, -journal,
23465 ** and -shm files.  We want those files to have *exactly* the same
23466 ** permissions as their original database, unadulterated by the umask.
23467 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23468 ** transaction crashes and leaves behind hot journals, then any
23469 ** process that is able to write to the database will also be able to
23470 ** recover the hot journals.
23471 */
23472 static int robust_open(const char *z, int f, mode_t m){
23473   int fd;
23474   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
23475   do{
23476 #if defined(O_CLOEXEC)
23477     fd = osOpen(z,f|O_CLOEXEC,m2);
23478 #else
23479     fd = osOpen(z,f,m2);
23480 #endif
23481   }while( fd<0 && errno==EINTR );
23482   if( fd>=0 ){
23483     if( m!=0 ){
23484       struct stat statbuf;
23485       if( osFstat(fd, &statbuf)==0
23486        && statbuf.st_size==0
23487        && (statbuf.st_mode&0777)!=m
23488       ){
23489         osFchmod(fd, m);
23490       }
23491     }
23492 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23493     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23494 #endif
23495   }
23496   return fd;
23497 }
23498 
23499 /*
23500 ** Helper functions to obtain and relinquish the global mutex. The
23501 ** global mutex is used to protect the unixInodeInfo and
23502 ** vxworksFileId objects used by this file, all of which may be
23503 ** shared by multiple threads.
23504 **
23505 ** Function unixMutexHeld() is used to assert() that the global mutex
23506 ** is held when required. This function is only used as part of assert()
23507 ** statements. e.g.
23508 **
23509 **   unixEnterMutex()
23510 **     assert( unixMutexHeld() );
23511 **   unixEnterLeave()
23512 */
23513 static void unixEnterMutex(void){
23514   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23515 }
23516 static void unixLeaveMutex(void){
23517   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23518 }
23519 #ifdef SQLITE_DEBUG
23520 static int unixMutexHeld(void) {
23521   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23522 }
23523 #endif
23524 
23525 
23526 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23527 /*
23528 ** Helper function for printing out trace information from debugging
23529 ** binaries. This returns the string represetation of the supplied
23530 ** integer lock-type.
23531 */
23532 static const char *azFileLock(int eFileLock){
23533   switch( eFileLock ){
23534     case NO_LOCK: return "NONE";
23535     case SHARED_LOCK: return "SHARED";
23536     case RESERVED_LOCK: return "RESERVED";
23537     case PENDING_LOCK: return "PENDING";
23538     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23539   }
23540   return "ERROR";
23541 }
23542 #endif
23543 
23544 #ifdef SQLITE_LOCK_TRACE
23545 /*
23546 ** Print out information about all locking operations.
23547 **
23548 ** This routine is used for troubleshooting locks on multithreaded
23549 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23550 ** command-line option on the compiler.  This code is normally
23551 ** turned off.
23552 */
23553 static int lockTrace(int fd, int op, struct flock *p){
23554   char *zOpName, *zType;
23555   int s;
23556   int savedErrno;
23557   if( op==F_GETLK ){
23558     zOpName = "GETLK";
23559   }else if( op==F_SETLK ){
23560     zOpName = "SETLK";
23561   }else{
23562     s = osFcntl(fd, op, p);
23563     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23564     return s;
23565   }
23566   if( p->l_type==F_RDLCK ){
23567     zType = "RDLCK";
23568   }else if( p->l_type==F_WRLCK ){
23569     zType = "WRLCK";
23570   }else if( p->l_type==F_UNLCK ){
23571     zType = "UNLCK";
23572   }else{
23573     assert( 0 );
23574   }
23575   assert( p->l_whence==SEEK_SET );
23576   s = osFcntl(fd, op, p);
23577   savedErrno = errno;
23578   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23579      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23580      (int)p->l_pid, s);
23581   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23582     struct flock l2;
23583     l2 = *p;
23584     osFcntl(fd, F_GETLK, &l2);
23585     if( l2.l_type==F_RDLCK ){
23586       zType = "RDLCK";
23587     }else if( l2.l_type==F_WRLCK ){
23588       zType = "WRLCK";
23589     }else if( l2.l_type==F_UNLCK ){
23590       zType = "UNLCK";
23591     }else{
23592       assert( 0 );
23593     }
23594     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23595        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23596   }
23597   errno = savedErrno;
23598   return s;
23599 }
23600 #undef osFcntl
23601 #define osFcntl lockTrace
23602 #endif /* SQLITE_LOCK_TRACE */
23603 
23604 /*
23605 ** Retry ftruncate() calls that fail due to EINTR
23606 */
23607 static int robust_ftruncate(int h, sqlite3_int64 sz){
23608   int rc;
23609   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23610   return rc;
23611 }
23612 
23613 /*
23614 ** This routine translates a standard POSIX errno code into something
23615 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23616 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23617 ** and a variety of "please close the file descriptor NOW" errors into
23618 ** SQLITE_IOERR
23619 **
23620 ** Errors during initialization of locks, or file system support for locks,
23621 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23622 */
23623 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23624   switch (posixError) {
23625 #if 0
23626   /* At one point this code was not commented out. In theory, this branch
23627   ** should never be hit, as this function should only be called after
23628   ** a locking-related function (i.e. fcntl()) has returned non-zero with
23629   ** the value of errno as the first argument. Since a system call has failed,
23630   ** errno should be non-zero.
23631   **
23632   ** Despite this, if errno really is zero, we still don't want to return
23633   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23634   ** propagated back to the caller. Commenting this branch out means errno==0
23635   ** will be handled by the "default:" case below.
23636   */
23637   case 0:
23638     return SQLITE_OK;
23639 #endif
23640 
23641   case EAGAIN:
23642   case ETIMEDOUT:
23643   case EBUSY:
23644   case EINTR:
23645   case ENOLCK:
23646     /* random NFS retry error, unless during file system support
23647      * introspection, in which it actually means what it says */
23648     return SQLITE_BUSY;
23649 
23650   case EACCES:
23651     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23652     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
23653         (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
23654         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23655         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23656       return SQLITE_BUSY;
23657     }
23658     /* else fall through */
23659   case EPERM:
23660     return SQLITE_PERM;
23661 
23662   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23663   ** this module never makes such a call. And the code in SQLite itself
23664   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23665   ** this case is also commented out. If the system does set errno to EDEADLK,
23666   ** the default SQLITE_IOERR_XXX code will be returned. */
23667 #if 0
23668   case EDEADLK:
23669     return SQLITE_IOERR_BLOCKED;
23670 #endif
23671 
23672 #if EOPNOTSUPP!=ENOTSUP
23673   case EOPNOTSUPP:
23674     /* something went terribly awry, unless during file system support
23675      * introspection, in which it actually means what it says */
23676 #endif
23677 #ifdef ENOTSUP
23678   case ENOTSUP:
23679     /* invalid fd, unless during file system support introspection, in which
23680      * it actually means what it says */
23681 #endif
23682   case EIO:
23683   case EBADF:
23684   case EINVAL:
23685   case ENOTCONN:
23686   case ENODEV:
23687   case ENXIO:
23688   case ENOENT:
23689 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
23690   case ESTALE:
23691 #endif
23692   case ENOSYS:
23693     /* these should force the client to close the file and reconnect */
23694 
23695   default:
23696     return sqliteIOErr;
23697   }
23698 }
23699 
23700 
23701 
23702 /******************************************************************************
23703 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23704 **
23705 ** On most versions of unix, we can get a unique ID for a file by concatenating
23706 ** the device number and the inode number.  But this does not work on VxWorks.
23707 ** On VxWorks, a unique file id must be based on the canonical filename.
23708 **
23709 ** A pointer to an instance of the following structure can be used as a
23710 ** unique file ID in VxWorks.  Each instance of this structure contains
23711 ** a copy of the canonical filename.  There is also a reference count.
23712 ** The structure is reclaimed when the number of pointers to it drops to
23713 ** zero.
23714 **
23715 ** There are never very many files open at one time and lookups are not
23716 ** a performance-critical path, so it is sufficient to put these
23717 ** structures on a linked list.
23718 */
23719 struct vxworksFileId {
23720   struct vxworksFileId *pNext;  /* Next in a list of them all */
23721   int nRef;                     /* Number of references to this one */
23722   int nName;                    /* Length of the zCanonicalName[] string */
23723   char *zCanonicalName;         /* Canonical filename */
23724 };
23725 
23726 #if OS_VXWORKS
23727 /*
23728 ** All unique filenames are held on a linked list headed by this
23729 ** variable:
23730 */
23731 static struct vxworksFileId *vxworksFileList = 0;
23732 
23733 /*
23734 ** Simplify a filename into its canonical form
23735 ** by making the following changes:
23736 **
23737 **  * removing any trailing and duplicate /
23738 **  * convert /./ into just /
23739 **  * convert /A/../ where A is any simple name into just /
23740 **
23741 ** Changes are made in-place.  Return the new name length.
23742 **
23743 ** The original filename is in z[0..n-1].  Return the number of
23744 ** characters in the simplified name.
23745 */
23746 static int vxworksSimplifyName(char *z, int n){
23747   int i, j;
23748   while( n>1 && z[n-1]=='/' ){ n--; }
23749   for(i=j=0; i<n; i++){
23750     if( z[i]=='/' ){
23751       if( z[i+1]=='/' ) continue;
23752       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23753         i += 1;
23754         continue;
23755       }
23756       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23757         while( j>0 && z[j-1]!='/' ){ j--; }
23758         if( j>0 ){ j--; }
23759         i += 2;
23760         continue;
23761       }
23762     }
23763     z[j++] = z[i];
23764   }
23765   z[j] = 0;
23766   return j;
23767 }
23768 
23769 /*
23770 ** Find a unique file ID for the given absolute pathname.  Return
23771 ** a pointer to the vxworksFileId object.  This pointer is the unique
23772 ** file ID.
23773 **
23774 ** The nRef field of the vxworksFileId object is incremented before
23775 ** the object is returned.  A new vxworksFileId object is created
23776 ** and added to the global list if necessary.
23777 **
23778 ** If a memory allocation error occurs, return NULL.
23779 */
23780 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23781   struct vxworksFileId *pNew;         /* search key and new file ID */
23782   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23783   int n;                              /* Length of zAbsoluteName string */
23784 
23785   assert( zAbsoluteName[0]=='/' );
23786   n = (int)strlen(zAbsoluteName);
23787   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23788   if( pNew==0 ) return 0;
23789   pNew->zCanonicalName = (char*)&pNew[1];
23790   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23791   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23792 
23793   /* Search for an existing entry that matching the canonical name.
23794   ** If found, increment the reference count and return a pointer to
23795   ** the existing file ID.
23796   */
23797   unixEnterMutex();
23798   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23799     if( pCandidate->nName==n
23800      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23801     ){
23802        sqlite3_free(pNew);
23803        pCandidate->nRef++;
23804        unixLeaveMutex();
23805        return pCandidate;
23806     }
23807   }
23808 
23809   /* No match was found.  We will make a new file ID */
23810   pNew->nRef = 1;
23811   pNew->nName = n;
23812   pNew->pNext = vxworksFileList;
23813   vxworksFileList = pNew;
23814   unixLeaveMutex();
23815   return pNew;
23816 }
23817 
23818 /*
23819 ** Decrement the reference count on a vxworksFileId object.  Free
23820 ** the object when the reference count reaches zero.
23821 */
23822 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23823   unixEnterMutex();
23824   assert( pId->nRef>0 );
23825   pId->nRef--;
23826   if( pId->nRef==0 ){
23827     struct vxworksFileId **pp;
23828     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23829     assert( *pp==pId );
23830     *pp = pId->pNext;
23831     sqlite3_free(pId);
23832   }
23833   unixLeaveMutex();
23834 }
23835 #endif /* OS_VXWORKS */
23836 /*************** End of Unique File ID Utility Used By VxWorks ****************
23837 ******************************************************************************/
23838 
23839 
23840 /******************************************************************************
23841 *************************** Posix Advisory Locking ****************************
23842 **
23843 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23844 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23845 ** sets or clears a lock, that operation overrides any prior locks set
23846 ** by the same process.  It does not explicitly say so, but this implies
23847 ** that it overrides locks set by the same process using a different
23848 ** file descriptor.  Consider this test case:
23849 **
23850 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23851 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23852 **
23853 ** Suppose ./file1 and ./file2 are really the same file (because
23854 ** one is a hard or symbolic link to the other) then if you set
23855 ** an exclusive lock on fd1, then try to get an exclusive lock
23856 ** on fd2, it works.  I would have expected the second lock to
23857 ** fail since there was already a lock on the file due to fd1.
23858 ** But not so.  Since both locks came from the same process, the
23859 ** second overrides the first, even though they were on different
23860 ** file descriptors opened on different file names.
23861 **
23862 ** This means that we cannot use POSIX locks to synchronize file access
23863 ** among competing threads of the same process.  POSIX locks will work fine
23864 ** to synchronize access for threads in separate processes, but not
23865 ** threads within the same process.
23866 **
23867 ** To work around the problem, SQLite has to manage file locks internally
23868 ** on its own.  Whenever a new database is opened, we have to find the
23869 ** specific inode of the database file (the inode is determined by the
23870 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23871 ** and check for locks already existing on that inode.  When locks are
23872 ** created or removed, we have to look at our own internal record of the
23873 ** locks to see if another thread has previously set a lock on that same
23874 ** inode.
23875 **
23876 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23877 ** For VxWorks, we have to use the alternative unique ID system based on
23878 ** canonical filename and implemented in the previous division.)
23879 **
23880 ** The sqlite3_file structure for POSIX is no longer just an integer file
23881 ** descriptor.  It is now a structure that holds the integer file
23882 ** descriptor and a pointer to a structure that describes the internal
23883 ** locks on the corresponding inode.  There is one locking structure
23884 ** per inode, so if the same inode is opened twice, both unixFile structures
23885 ** point to the same locking structure.  The locking structure keeps
23886 ** a reference count (so we will know when to delete it) and a "cnt"
23887 ** field that tells us its internal lock status.  cnt==0 means the
23888 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23889 ** cnt>0 means there are cnt shared locks on the file.
23890 **
23891 ** Any attempt to lock or unlock a file first checks the locking
23892 ** structure.  The fcntl() system call is only invoked to set a
23893 ** POSIX lock if the internal lock structure transitions between
23894 ** a locked and an unlocked state.
23895 **
23896 ** But wait:  there are yet more problems with POSIX advisory locks.
23897 **
23898 ** If you close a file descriptor that points to a file that has locks,
23899 ** all locks on that file that are owned by the current process are
23900 ** released.  To work around this problem, each unixInodeInfo object
23901 ** maintains a count of the number of pending locks on tha inode.
23902 ** When an attempt is made to close an unixFile, if there are
23903 ** other unixFile open on the same inode that are holding locks, the call
23904 ** to close() the file descriptor is deferred until all of the locks clear.
23905 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23906 ** be closed and that list is walked (and cleared) when the last lock
23907 ** clears.
23908 **
23909 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23910 **
23911 ** Many older versions of linux use the LinuxThreads library which is
23912 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23913 ** A cannot be modified or overridden by a different thread B.
23914 ** Only thread A can modify the lock.  Locking behavior is correct
23915 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23916 ** on linux - with NPTL a lock created by thread A can override locks
23917 ** in thread B.  But there is no way to know at compile-time which
23918 ** threading library is being used.  So there is no way to know at
23919 ** compile-time whether or not thread A can override locks on thread B.
23920 ** One has to do a run-time check to discover the behavior of the
23921 ** current process.
23922 **
23923 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23924 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23925 ** LinuxThreads provided that (1) there is no more than one connection
23926 ** per database file in the same process and (2) database connections
23927 ** do not move across threads.
23928 */
23929 
23930 /*
23931 ** An instance of the following structure serves as the key used
23932 ** to locate a particular unixInodeInfo object.
23933 */
23934 struct unixFileId {
23935   dev_t dev;                  /* Device number */
23936 #if OS_VXWORKS
23937   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23938 #else
23939   ino_t ino;                  /* Inode number */
23940 #endif
23941 };
23942 
23943 /*
23944 ** An instance of the following structure is allocated for each open
23945 ** inode.  Or, on LinuxThreads, there is one of these structures for
23946 ** each inode opened by each thread.
23947 **
23948 ** A single inode can have multiple file descriptors, so each unixFile
23949 ** structure contains a pointer to an instance of this object and this
23950 ** object keeps a count of the number of unixFile pointing to it.
23951 */
23952 struct unixInodeInfo {
23953   struct unixFileId fileId;       /* The lookup key */
23954   int nShared;                    /* Number of SHARED locks held */
23955   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23956   unsigned char bProcessLock;     /* An exclusive process lock is held */
23957   int nRef;                       /* Number of pointers to this structure */
23958   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23959   int nLock;                      /* Number of outstanding file locks */
23960   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23961   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23962   unixInodeInfo *pPrev;           /*    .... doubly linked */
23963 #if SQLITE_ENABLE_LOCKING_STYLE
23964   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23965 #endif
23966 #if OS_VXWORKS
23967   sem_t *pSem;                    /* Named POSIX semaphore */
23968   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23969 #endif
23970 };
23971 
23972 /*
23973 ** A lists of all unixInodeInfo objects.
23974 */
23975 static unixInodeInfo *inodeList = 0;
23976 
23977 /*
23978 **
23979 ** This function - unixLogError_x(), is only ever called via the macro
23980 ** unixLogError().
23981 **
23982 ** It is invoked after an error occurs in an OS function and errno has been
23983 ** set. It logs a message using sqlite3_log() containing the current value of
23984 ** errno and, if possible, the human-readable equivalent from strerror() or
23985 ** strerror_r().
23986 **
23987 ** The first argument passed to the macro should be the error code that
23988 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
23989 ** The two subsequent arguments should be the name of the OS function that
23990 ** failed (e.g. "unlink", "open") and the associated file-system path,
23991 ** if any.
23992 */
23993 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
23994 static int unixLogErrorAtLine(
23995   int errcode,                    /* SQLite error code */
23996   const char *zFunc,              /* Name of OS function that failed */
23997   const char *zPath,              /* File path associated with error */
23998   int iLine                       /* Source line number where error occurred */
23999 ){
24000   char *zErr;                     /* Message from strerror() or equivalent */
24001   int iErrno = errno;             /* Saved syscall error number */
24002 
24003   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24004   ** the strerror() function to obtain the human-readable error message
24005   ** equivalent to errno. Otherwise, use strerror_r().
24006   */
24007 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24008   char aErr[80];
24009   memset(aErr, 0, sizeof(aErr));
24010   zErr = aErr;
24011 
24012   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24013   ** assume that the system provides the GNU version of strerror_r() that
24014   ** returns a pointer to a buffer containing the error message. That pointer
24015   ** may point to aErr[], or it may point to some static storage somewhere.
24016   ** Otherwise, assume that the system provides the POSIX version of
24017   ** strerror_r(), which always writes an error message into aErr[].
24018   **
24019   ** If the code incorrectly assumes that it is the POSIX version that is
24020   ** available, the error message will often be an empty string. Not a
24021   ** huge problem. Incorrectly concluding that the GNU version is available
24022   ** could lead to a segfault though.
24023   */
24024 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24025   zErr =
24026 # endif
24027   strerror_r(iErrno, aErr, sizeof(aErr)-1);
24028 
24029 #elif SQLITE_THREADSAFE
24030   /* This is a threadsafe build, but strerror_r() is not available. */
24031   zErr = "";
24032 #else
24033   /* Non-threadsafe build, use strerror(). */
24034   zErr = strerror(iErrno);
24035 #endif
24036 
24037   assert( errcode!=SQLITE_OK );
24038   if( zPath==0 ) zPath = "";
24039   sqlite3_log(errcode,
24040       "os_unix.c:%d: (%d) %s(%s) - %s",
24041       iLine, iErrno, zFunc, zPath, zErr
24042   );
24043 
24044   return errcode;
24045 }
24046 
24047 /*
24048 ** Close a file descriptor.
24049 **
24050 ** We assume that close() almost always works, since it is only in a
24051 ** very sick application or on a very sick platform that it might fail.
24052 ** If it does fail, simply leak the file descriptor, but do log the
24053 ** error.
24054 **
24055 ** Note that it is not safe to retry close() after EINTR since the
24056 ** file descriptor might have already been reused by another thread.
24057 ** So we don't even try to recover from an EINTR.  Just log the error
24058 ** and move on.
24059 */
24060 static void robust_close(unixFile *pFile, int h, int lineno){
24061   if( osClose(h) ){
24062     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24063                        pFile ? pFile->zPath : 0, lineno);
24064   }
24065 }
24066 
24067 /*
24068 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24069 */
24070 static void closePendingFds(unixFile *pFile){
24071   unixInodeInfo *pInode = pFile->pInode;
24072   UnixUnusedFd *p;
24073   UnixUnusedFd *pNext;
24074   for(p=pInode->pUnused; p; p=pNext){
24075     pNext = p->pNext;
24076     robust_close(pFile, p->fd, __LINE__);
24077     sqlite3_free(p);
24078   }
24079   pInode->pUnused = 0;
24080 }
24081 
24082 /*
24083 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24084 **
24085 ** The mutex entered using the unixEnterMutex() function must be held
24086 ** when this function is called.
24087 */
24088 static void releaseInodeInfo(unixFile *pFile){
24089   unixInodeInfo *pInode = pFile->pInode;
24090   assert( unixMutexHeld() );
24091   if( ALWAYS(pInode) ){
24092     pInode->nRef--;
24093     if( pInode->nRef==0 ){
24094       assert( pInode->pShmNode==0 );
24095       closePendingFds(pFile);
24096       if( pInode->pPrev ){
24097         assert( pInode->pPrev->pNext==pInode );
24098         pInode->pPrev->pNext = pInode->pNext;
24099       }else{
24100         assert( inodeList==pInode );
24101         inodeList = pInode->pNext;
24102       }
24103       if( pInode->pNext ){
24104         assert( pInode->pNext->pPrev==pInode );
24105         pInode->pNext->pPrev = pInode->pPrev;
24106       }
24107       sqlite3_free(pInode);
24108     }
24109   }
24110 }
24111 
24112 /*
24113 ** Given a file descriptor, locate the unixInodeInfo object that
24114 ** describes that file descriptor.  Create a new one if necessary.  The
24115 ** return value might be uninitialized if an error occurs.
24116 **
24117 ** The mutex entered using the unixEnterMutex() function must be held
24118 ** when this function is called.
24119 **
24120 ** Return an appropriate error code.
24121 */
24122 static int findInodeInfo(
24123   unixFile *pFile,               /* Unix file with file desc used in the key */
24124   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
24125 ){
24126   int rc;                        /* System call return code */
24127   int fd;                        /* The file descriptor for pFile */
24128   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
24129   struct stat statbuf;           /* Low-level file information */
24130   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
24131 
24132   assert( unixMutexHeld() );
24133 
24134   /* Get low-level information about the file that we can used to
24135   ** create a unique name for the file.
24136   */
24137   fd = pFile->h;
24138   rc = osFstat(fd, &statbuf);
24139   if( rc!=0 ){
24140     pFile->lastErrno = errno;
24141 #ifdef EOVERFLOW
24142     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24143 #endif
24144     return SQLITE_IOERR;
24145   }
24146 
24147 #ifdef __APPLE__
24148   /* On OS X on an msdos filesystem, the inode number is reported
24149   ** incorrectly for zero-size files.  See ticket #3260.  To work
24150   ** around this problem (we consider it a bug in OS X, not SQLite)
24151   ** we always increase the file size to 1 by writing a single byte
24152   ** prior to accessing the inode number.  The one byte written is
24153   ** an ASCII 'S' character which also happens to be the first byte
24154   ** in the header of every SQLite database.  In this way, if there
24155   ** is a race condition such that another thread has already populated
24156   ** the first page of the database, no damage is done.
24157   */
24158   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24159     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24160     if( rc!=1 ){
24161       pFile->lastErrno = errno;
24162       return SQLITE_IOERR;
24163     }
24164     rc = osFstat(fd, &statbuf);
24165     if( rc!=0 ){
24166       pFile->lastErrno = errno;
24167       return SQLITE_IOERR;
24168     }
24169   }
24170 #endif
24171 
24172   memset(&fileId, 0, sizeof(fileId));
24173   fileId.dev = statbuf.st_dev;
24174 #if OS_VXWORKS
24175   fileId.pId = pFile->pId;
24176 #else
24177   fileId.ino = statbuf.st_ino;
24178 #endif
24179   pInode = inodeList;
24180   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24181     pInode = pInode->pNext;
24182   }
24183   if( pInode==0 ){
24184     pInode = sqlite3_malloc( sizeof(*pInode) );
24185     if( pInode==0 ){
24186       return SQLITE_NOMEM;
24187     }
24188     memset(pInode, 0, sizeof(*pInode));
24189     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24190     pInode->nRef = 1;
24191     pInode->pNext = inodeList;
24192     pInode->pPrev = 0;
24193     if( inodeList ) inodeList->pPrev = pInode;
24194     inodeList = pInode;
24195   }else{
24196     pInode->nRef++;
24197   }
24198   *ppInode = pInode;
24199   return SQLITE_OK;
24200 }
24201 
24202 
24203 /*
24204 ** This routine checks if there is a RESERVED lock held on the specified
24205 ** file by this or any other process. If such a lock is held, set *pResOut
24206 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24207 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24208 */
24209 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24210   int rc = SQLITE_OK;
24211   int reserved = 0;
24212   unixFile *pFile = (unixFile*)id;
24213 
24214   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24215 
24216   assert( pFile );
24217   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24218 
24219   /* Check if a thread in this process holds such a lock */
24220   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24221     reserved = 1;
24222   }
24223 
24224   /* Otherwise see if some other process holds it.
24225   */
24226 #ifndef __DJGPP__
24227   if( !reserved && !pFile->pInode->bProcessLock ){
24228     struct flock lock;
24229     lock.l_whence = SEEK_SET;
24230     lock.l_start = RESERVED_BYTE;
24231     lock.l_len = 1;
24232     lock.l_type = F_WRLCK;
24233     if( osFcntl(pFile->h, F_GETLK, &lock) ){
24234       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24235       pFile->lastErrno = errno;
24236     } else if( lock.l_type!=F_UNLCK ){
24237       reserved = 1;
24238     }
24239   }
24240 #endif
24241 
24242   unixLeaveMutex();
24243   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24244 
24245   *pResOut = reserved;
24246   return rc;
24247 }
24248 
24249 /*
24250 ** Attempt to set a system-lock on the file pFile.  The lock is
24251 ** described by pLock.
24252 **
24253 ** If the pFile was opened read/write from unix-excl, then the only lock
24254 ** ever obtained is an exclusive lock, and it is obtained exactly once
24255 ** the first time any lock is attempted.  All subsequent system locking
24256 ** operations become no-ops.  Locking operations still happen internally,
24257 ** in order to coordinate access between separate database connections
24258 ** within this process, but all of that is handled in memory and the
24259 ** operating system does not participate.
24260 **
24261 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24262 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24263 ** and is read-only.
24264 **
24265 ** Zero is returned if the call completes successfully, or -1 if a call
24266 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24267 */
24268 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24269   int rc;
24270   unixInodeInfo *pInode = pFile->pInode;
24271   assert( unixMutexHeld() );
24272   assert( pInode!=0 );
24273   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24274    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24275   ){
24276     if( pInode->bProcessLock==0 ){
24277       struct flock lock;
24278       assert( pInode->nLock==0 );
24279       lock.l_whence = SEEK_SET;
24280       lock.l_start = SHARED_FIRST;
24281       lock.l_len = SHARED_SIZE;
24282       lock.l_type = F_WRLCK;
24283       rc = osFcntl(pFile->h, F_SETLK, &lock);
24284       if( rc<0 ) return rc;
24285       pInode->bProcessLock = 1;
24286       pInode->nLock++;
24287     }else{
24288       rc = 0;
24289     }
24290   }else{
24291     rc = osFcntl(pFile->h, F_SETLK, pLock);
24292   }
24293   return rc;
24294 }
24295 
24296 /*
24297 ** Lock the file with the lock specified by parameter eFileLock - one
24298 ** of the following:
24299 **
24300 **     (1) SHARED_LOCK
24301 **     (2) RESERVED_LOCK
24302 **     (3) PENDING_LOCK
24303 **     (4) EXCLUSIVE_LOCK
24304 **
24305 ** Sometimes when requesting one lock state, additional lock states
24306 ** are inserted in between.  The locking might fail on one of the later
24307 ** transitions leaving the lock state different from what it started but
24308 ** still short of its goal.  The following chart shows the allowed
24309 ** transitions and the inserted intermediate states:
24310 **
24311 **    UNLOCKED -> SHARED
24312 **    SHARED -> RESERVED
24313 **    SHARED -> (PENDING) -> EXCLUSIVE
24314 **    RESERVED -> (PENDING) -> EXCLUSIVE
24315 **    PENDING -> EXCLUSIVE
24316 **
24317 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24318 ** routine to lower a locking level.
24319 */
24320 static int unixLock(sqlite3_file *id, int eFileLock){
24321   /* The following describes the implementation of the various locks and
24322   ** lock transitions in terms of the POSIX advisory shared and exclusive
24323   ** lock primitives (called read-locks and write-locks below, to avoid
24324   ** confusion with SQLite lock names). The algorithms are complicated
24325   ** slightly in order to be compatible with windows systems simultaneously
24326   ** accessing the same database file, in case that is ever required.
24327   **
24328   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24329   ** byte', each single bytes at well known offsets, and the 'shared byte
24330   ** range', a range of 510 bytes at a well known offset.
24331   **
24332   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24333   ** byte'.  If this is successful, a random byte from the 'shared byte
24334   ** range' is read-locked and the lock on the 'pending byte' released.
24335   **
24336   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24337   ** A RESERVED lock is implemented by grabbing a write-lock on the
24338   ** 'reserved byte'.
24339   **
24340   ** A process may only obtain a PENDING lock after it has obtained a
24341   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24342   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24343   ** obtained, but existing SHARED locks are allowed to persist. A process
24344   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24345   ** This property is used by the algorithm for rolling back a journal file
24346   ** after a crash.
24347   **
24348   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24349   ** implemented by obtaining a write-lock on the entire 'shared byte
24350   ** range'. Since all other locks require a read-lock on one of the bytes
24351   ** within this range, this ensures that no other locks are held on the
24352   ** database.
24353   **
24354   ** The reason a single byte cannot be used instead of the 'shared byte
24355   ** range' is that some versions of windows do not support read-locks. By
24356   ** locking a random byte from a range, concurrent SHARED locks may exist
24357   ** even if the locking primitive used is always a write-lock.
24358   */
24359   int rc = SQLITE_OK;
24360   unixFile *pFile = (unixFile*)id;
24361   unixInodeInfo *pInode;
24362   struct flock lock;
24363   int tErrno = 0;
24364 
24365   assert( pFile );
24366   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24367       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24368       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24369 
24370   /* If there is already a lock of this type or more restrictive on the
24371   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24372   ** unixEnterMutex() hasn't been called yet.
24373   */
24374   if( pFile->eFileLock>=eFileLock ){
24375     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24376             azFileLock(eFileLock)));
24377     return SQLITE_OK;
24378   }
24379 
24380   /* Make sure the locking sequence is correct.
24381   **  (1) We never move from unlocked to anything higher than shared lock.
24382   **  (2) SQLite never explicitly requests a pendig lock.
24383   **  (3) A shared lock is always held when a reserve lock is requested.
24384   */
24385   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24386   assert( eFileLock!=PENDING_LOCK );
24387   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24388 
24389   /* This mutex is needed because pFile->pInode is shared across threads
24390   */
24391   unixEnterMutex();
24392   pInode = pFile->pInode;
24393 
24394   /* If some thread using this PID has a lock via a different unixFile*
24395   ** handle that precludes the requested lock, return BUSY.
24396   */
24397   if( (pFile->eFileLock!=pInode->eFileLock &&
24398           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24399   ){
24400     rc = SQLITE_BUSY;
24401     goto end_lock;
24402   }
24403 
24404   /* If a SHARED lock is requested, and some thread using this PID already
24405   ** has a SHARED or RESERVED lock, then increment reference counts and
24406   ** return SQLITE_OK.
24407   */
24408   if( eFileLock==SHARED_LOCK &&
24409       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24410     assert( eFileLock==SHARED_LOCK );
24411     assert( pFile->eFileLock==0 );
24412     assert( pInode->nShared>0 );
24413     pFile->eFileLock = SHARED_LOCK;
24414     pInode->nShared++;
24415     pInode->nLock++;
24416     goto end_lock;
24417   }
24418 
24419 
24420   /* A PENDING lock is needed before acquiring a SHARED lock and before
24421   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24422   ** be released.
24423   */
24424   lock.l_len = 1L;
24425   lock.l_whence = SEEK_SET;
24426   if( eFileLock==SHARED_LOCK
24427       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24428   ){
24429     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24430     lock.l_start = PENDING_BYTE;
24431     if( unixFileLock(pFile, &lock) ){
24432       tErrno = errno;
24433       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24434       if( rc!=SQLITE_BUSY ){
24435         pFile->lastErrno = tErrno;
24436       }
24437       goto end_lock;
24438     }
24439   }
24440 
24441 
24442   /* If control gets to this point, then actually go ahead and make
24443   ** operating system calls for the specified lock.
24444   */
24445   if( eFileLock==SHARED_LOCK ){
24446     assert( pInode->nShared==0 );
24447     assert( pInode->eFileLock==0 );
24448     assert( rc==SQLITE_OK );
24449 
24450     /* Now get the read-lock */
24451     lock.l_start = SHARED_FIRST;
24452     lock.l_len = SHARED_SIZE;
24453     if( unixFileLock(pFile, &lock) ){
24454       tErrno = errno;
24455       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24456     }
24457 
24458     /* Drop the temporary PENDING lock */
24459     lock.l_start = PENDING_BYTE;
24460     lock.l_len = 1L;
24461     lock.l_type = F_UNLCK;
24462     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24463       /* This could happen with a network mount */
24464       tErrno = errno;
24465       rc = SQLITE_IOERR_UNLOCK;
24466     }
24467 
24468     if( rc ){
24469       if( rc!=SQLITE_BUSY ){
24470         pFile->lastErrno = tErrno;
24471       }
24472       goto end_lock;
24473     }else{
24474       pFile->eFileLock = SHARED_LOCK;
24475       pInode->nLock++;
24476       pInode->nShared = 1;
24477     }
24478   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24479     /* We are trying for an exclusive lock but another thread in this
24480     ** same process is still holding a shared lock. */
24481     rc = SQLITE_BUSY;
24482   }else{
24483     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24484     ** assumed that there is a SHARED or greater lock on the file
24485     ** already.
24486     */
24487     assert( 0!=pFile->eFileLock );
24488     lock.l_type = F_WRLCK;
24489 
24490     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24491     if( eFileLock==RESERVED_LOCK ){
24492       lock.l_start = RESERVED_BYTE;
24493       lock.l_len = 1L;
24494     }else{
24495       lock.l_start = SHARED_FIRST;
24496       lock.l_len = SHARED_SIZE;
24497     }
24498 
24499     if( unixFileLock(pFile, &lock) ){
24500       tErrno = errno;
24501       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24502       if( rc!=SQLITE_BUSY ){
24503         pFile->lastErrno = tErrno;
24504       }
24505     }
24506   }
24507 
24508 
24509 #ifdef SQLITE_DEBUG
24510   /* Set up the transaction-counter change checking flags when
24511   ** transitioning from a SHARED to a RESERVED lock.  The change
24512   ** from SHARED to RESERVED marks the beginning of a normal
24513   ** write operation (not a hot journal rollback).
24514   */
24515   if( rc==SQLITE_OK
24516    && pFile->eFileLock<=SHARED_LOCK
24517    && eFileLock==RESERVED_LOCK
24518   ){
24519     pFile->transCntrChng = 0;
24520     pFile->dbUpdate = 0;
24521     pFile->inNormalWrite = 1;
24522   }
24523 #endif
24524 
24525 
24526   if( rc==SQLITE_OK ){
24527     pFile->eFileLock = eFileLock;
24528     pInode->eFileLock = eFileLock;
24529   }else if( eFileLock==EXCLUSIVE_LOCK ){
24530     pFile->eFileLock = PENDING_LOCK;
24531     pInode->eFileLock = PENDING_LOCK;
24532   }
24533 
24534 end_lock:
24535   unixLeaveMutex();
24536   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
24537       rc==SQLITE_OK ? "ok" : "failed"));
24538   return rc;
24539 }
24540 
24541 /*
24542 ** Add the file descriptor used by file handle pFile to the corresponding
24543 ** pUnused list.
24544 */
24545 static void setPendingFd(unixFile *pFile){
24546   unixInodeInfo *pInode = pFile->pInode;
24547   UnixUnusedFd *p = pFile->pUnused;
24548   p->pNext = pInode->pUnused;
24549   pInode->pUnused = p;
24550   pFile->h = -1;
24551   pFile->pUnused = 0;
24552 }
24553 
24554 /*
24555 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24556 ** must be either NO_LOCK or SHARED_LOCK.
24557 **
24558 ** If the locking level of the file descriptor is already at or below
24559 ** the requested locking level, this routine is a no-op.
24560 **
24561 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24562 ** the byte range is divided into 2 parts and the first part is unlocked then
24563 ** set to a read lock, then the other part is simply unlocked.  This works
24564 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
24565 ** remove the write lock on a region when a read lock is set.
24566 */
24567 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24568   unixFile *pFile = (unixFile*)id;
24569   unixInodeInfo *pInode;
24570   struct flock lock;
24571   int rc = SQLITE_OK;
24572 
24573   assert( pFile );
24574   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24575       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24576       getpid()));
24577 
24578   assert( eFileLock<=SHARED_LOCK );
24579   if( pFile->eFileLock<=eFileLock ){
24580     return SQLITE_OK;
24581   }
24582   unixEnterMutex();
24583   pInode = pFile->pInode;
24584   assert( pInode->nShared!=0 );
24585   if( pFile->eFileLock>SHARED_LOCK ){
24586     assert( pInode->eFileLock==pFile->eFileLock );
24587 
24588 #ifdef SQLITE_DEBUG
24589     /* When reducing a lock such that other processes can start
24590     ** reading the database file again, make sure that the
24591     ** transaction counter was updated if any part of the database
24592     ** file changed.  If the transaction counter is not updated,
24593     ** other connections to the same file might not realize that
24594     ** the file has changed and hence might not know to flush their
24595     ** cache.  The use of a stale cache can lead to database corruption.
24596     */
24597     pFile->inNormalWrite = 0;
24598 #endif
24599 
24600     /* downgrading to a shared lock on NFS involves clearing the write lock
24601     ** before establishing the readlock - to avoid a race condition we downgrade
24602     ** the lock in 2 blocks, so that part of the range will be covered by a
24603     ** write lock until the rest is covered by a read lock:
24604     **  1:   [WWWWW]
24605     **  2:   [....W]
24606     **  3:   [RRRRW]
24607     **  4:   [RRRR.]
24608     */
24609     if( eFileLock==SHARED_LOCK ){
24610 
24611 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24612       (void)handleNFSUnlock;
24613       assert( handleNFSUnlock==0 );
24614 #endif
24615 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24616       if( handleNFSUnlock ){
24617         int tErrno;               /* Error code from system call errors */
24618         off_t divSize = SHARED_SIZE - 1;
24619 
24620         lock.l_type = F_UNLCK;
24621         lock.l_whence = SEEK_SET;
24622         lock.l_start = SHARED_FIRST;
24623         lock.l_len = divSize;
24624         if( unixFileLock(pFile, &lock)==(-1) ){
24625           tErrno = errno;
24626           rc = SQLITE_IOERR_UNLOCK;
24627           if( IS_LOCK_ERROR(rc) ){
24628             pFile->lastErrno = tErrno;
24629           }
24630           goto end_unlock;
24631         }
24632         lock.l_type = F_RDLCK;
24633         lock.l_whence = SEEK_SET;
24634         lock.l_start = SHARED_FIRST;
24635         lock.l_len = divSize;
24636         if( unixFileLock(pFile, &lock)==(-1) ){
24637           tErrno = errno;
24638           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24639           if( IS_LOCK_ERROR(rc) ){
24640             pFile->lastErrno = tErrno;
24641           }
24642           goto end_unlock;
24643         }
24644         lock.l_type = F_UNLCK;
24645         lock.l_whence = SEEK_SET;
24646         lock.l_start = SHARED_FIRST+divSize;
24647         lock.l_len = SHARED_SIZE-divSize;
24648         if( unixFileLock(pFile, &lock)==(-1) ){
24649           tErrno = errno;
24650           rc = SQLITE_IOERR_UNLOCK;
24651           if( IS_LOCK_ERROR(rc) ){
24652             pFile->lastErrno = tErrno;
24653           }
24654           goto end_unlock;
24655         }
24656       }else
24657 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24658       {
24659         lock.l_type = F_RDLCK;
24660         lock.l_whence = SEEK_SET;
24661         lock.l_start = SHARED_FIRST;
24662         lock.l_len = SHARED_SIZE;
24663         if( unixFileLock(pFile, &lock) ){
24664           /* In theory, the call to unixFileLock() cannot fail because another
24665           ** process is holding an incompatible lock. If it does, this
24666           ** indicates that the other process is not following the locking
24667           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24668           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
24669           ** an assert to fail). */
24670           rc = SQLITE_IOERR_RDLOCK;
24671           pFile->lastErrno = errno;
24672           goto end_unlock;
24673         }
24674       }
24675     }
24676     lock.l_type = F_UNLCK;
24677     lock.l_whence = SEEK_SET;
24678     lock.l_start = PENDING_BYTE;
24679     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24680     if( unixFileLock(pFile, &lock)==0 ){
24681       pInode->eFileLock = SHARED_LOCK;
24682     }else{
24683       rc = SQLITE_IOERR_UNLOCK;
24684       pFile->lastErrno = errno;
24685       goto end_unlock;
24686     }
24687   }
24688   if( eFileLock==NO_LOCK ){
24689     /* Decrement the shared lock counter.  Release the lock using an
24690     ** OS call only when all threads in this same process have released
24691     ** the lock.
24692     */
24693     pInode->nShared--;
24694     if( pInode->nShared==0 ){
24695       lock.l_type = F_UNLCK;
24696       lock.l_whence = SEEK_SET;
24697       lock.l_start = lock.l_len = 0L;
24698       if( unixFileLock(pFile, &lock)==0 ){
24699         pInode->eFileLock = NO_LOCK;
24700       }else{
24701         rc = SQLITE_IOERR_UNLOCK;
24702         pFile->lastErrno = errno;
24703         pInode->eFileLock = NO_LOCK;
24704         pFile->eFileLock = NO_LOCK;
24705       }
24706     }
24707 
24708     /* Decrement the count of locks against this same file.  When the
24709     ** count reaches zero, close any other file descriptors whose close
24710     ** was deferred because of outstanding locks.
24711     */
24712     pInode->nLock--;
24713     assert( pInode->nLock>=0 );
24714     if( pInode->nLock==0 ){
24715       closePendingFds(pFile);
24716     }
24717   }
24718 
24719 end_unlock:
24720   unixLeaveMutex();
24721   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24722   return rc;
24723 }
24724 
24725 /*
24726 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24727 ** must be either NO_LOCK or SHARED_LOCK.
24728 **
24729 ** If the locking level of the file descriptor is already at or below
24730 ** the requested locking level, this routine is a no-op.
24731 */
24732 static int unixUnlock(sqlite3_file *id, int eFileLock){
24733   return posixUnlock(id, eFileLock, 0);
24734 }
24735 
24736 /*
24737 ** This function performs the parts of the "close file" operation
24738 ** common to all locking schemes. It closes the directory and file
24739 ** handles, if they are valid, and sets all fields of the unixFile
24740 ** structure to 0.
24741 **
24742 ** It is *not* necessary to hold the mutex when this routine is called,
24743 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24744 ** vxworksReleaseFileId() routine.
24745 */
24746 static int closeUnixFile(sqlite3_file *id){
24747   unixFile *pFile = (unixFile*)id;
24748   if( pFile->h>=0 ){
24749     robust_close(pFile, pFile->h, __LINE__);
24750     pFile->h = -1;
24751   }
24752 #if OS_VXWORKS
24753   if( pFile->pId ){
24754     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
24755       osUnlink(pFile->pId->zCanonicalName);
24756     }
24757     vxworksReleaseFileId(pFile->pId);
24758     pFile->pId = 0;
24759   }
24760 #endif
24761   OSTRACE(("CLOSE   %-3d\n", pFile->h));
24762   OpenCounter(-1);
24763   sqlite3_free(pFile->pUnused);
24764   memset(pFile, 0, sizeof(unixFile));
24765   return SQLITE_OK;
24766 }
24767 
24768 /*
24769 ** Close a file.
24770 */
24771 static int unixClose(sqlite3_file *id){
24772   int rc = SQLITE_OK;
24773   unixFile *pFile = (unixFile *)id;
24774   unixUnlock(id, NO_LOCK);
24775   unixEnterMutex();
24776 
24777   /* unixFile.pInode is always valid here. Otherwise, a different close
24778   ** routine (e.g. nolockClose()) would be called instead.
24779   */
24780   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
24781   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
24782     /* If there are outstanding locks, do not actually close the file just
24783     ** yet because that would clear those locks.  Instead, add the file
24784     ** descriptor to pInode->pUnused list.  It will be automatically closed
24785     ** when the last lock is cleared.
24786     */
24787     setPendingFd(pFile);
24788   }
24789   releaseInodeInfo(pFile);
24790   rc = closeUnixFile(id);
24791   unixLeaveMutex();
24792   return rc;
24793 }
24794 
24795 /************** End of the posix advisory lock implementation *****************
24796 ******************************************************************************/
24797 
24798 /******************************************************************************
24799 ****************************** No-op Locking **********************************
24800 **
24801 ** Of the various locking implementations available, this is by far the
24802 ** simplest:  locking is ignored.  No attempt is made to lock the database
24803 ** file for reading or writing.
24804 **
24805 ** This locking mode is appropriate for use on read-only databases
24806 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24807 ** also be used if the application employs some external mechanism to
24808 ** prevent simultaneous access of the same database by two or more
24809 ** database connections.  But there is a serious risk of database
24810 ** corruption if this locking mode is used in situations where multiple
24811 ** database connections are accessing the same database file at the same
24812 ** time and one or more of those connections are writing.
24813 */
24814 
24815 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24816   UNUSED_PARAMETER(NotUsed);
24817   *pResOut = 0;
24818   return SQLITE_OK;
24819 }
24820 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24821   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24822   return SQLITE_OK;
24823 }
24824 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24825   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24826   return SQLITE_OK;
24827 }
24828 
24829 /*
24830 ** Close the file.
24831 */
24832 static int nolockClose(sqlite3_file *id) {
24833   return closeUnixFile(id);
24834 }
24835 
24836 /******************* End of the no-op lock implementation *********************
24837 ******************************************************************************/
24838 
24839 /******************************************************************************
24840 ************************* Begin dot-file Locking ******************************
24841 **
24842 ** The dotfile locking implementation uses the existence of separate lock
24843 ** files (really a directory) to control access to the database.  This works
24844 ** on just about every filesystem imaginable.  But there are serious downsides:
24845 **
24846 **    (1)  There is zero concurrency.  A single reader blocks all other
24847 **         connections from reading or writing the database.
24848 **
24849 **    (2)  An application crash or power loss can leave stale lock files
24850 **         sitting around that need to be cleared manually.
24851 **
24852 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24853 ** other locking strategy is available.
24854 **
24855 ** Dotfile locking works by creating a subdirectory in the same directory as
24856 ** the database and with the same name but with a ".lock" extension added.
24857 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
24858 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24859 */
24860 
24861 /*
24862 ** The file suffix added to the data base filename in order to create the
24863 ** lock directory.
24864 */
24865 #define DOTLOCK_SUFFIX ".lock"
24866 
24867 /*
24868 ** This routine checks if there is a RESERVED lock held on the specified
24869 ** file by this or any other process. If such a lock is held, set *pResOut
24870 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24871 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24872 **
24873 ** In dotfile locking, either a lock exists or it does not.  So in this
24874 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24875 ** is held on the file and false if the file is unlocked.
24876 */
24877 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24878   int rc = SQLITE_OK;
24879   int reserved = 0;
24880   unixFile *pFile = (unixFile*)id;
24881 
24882   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24883 
24884   assert( pFile );
24885 
24886   /* Check if a thread in this process holds such a lock */
24887   if( pFile->eFileLock>SHARED_LOCK ){
24888     /* Either this connection or some other connection in the same process
24889     ** holds a lock on the file.  No need to check further. */
24890     reserved = 1;
24891   }else{
24892     /* The lock is held if and only if the lockfile exists */
24893     const char *zLockFile = (const char*)pFile->lockingContext;
24894     reserved = osAccess(zLockFile, 0)==0;
24895   }
24896   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24897   *pResOut = reserved;
24898   return rc;
24899 }
24900 
24901 /*
24902 ** Lock the file with the lock specified by parameter eFileLock - one
24903 ** of the following:
24904 **
24905 **     (1) SHARED_LOCK
24906 **     (2) RESERVED_LOCK
24907 **     (3) PENDING_LOCK
24908 **     (4) EXCLUSIVE_LOCK
24909 **
24910 ** Sometimes when requesting one lock state, additional lock states
24911 ** are inserted in between.  The locking might fail on one of the later
24912 ** transitions leaving the lock state different from what it started but
24913 ** still short of its goal.  The following chart shows the allowed
24914 ** transitions and the inserted intermediate states:
24915 **
24916 **    UNLOCKED -> SHARED
24917 **    SHARED -> RESERVED
24918 **    SHARED -> (PENDING) -> EXCLUSIVE
24919 **    RESERVED -> (PENDING) -> EXCLUSIVE
24920 **    PENDING -> EXCLUSIVE
24921 **
24922 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24923 ** routine to lower a locking level.
24924 **
24925 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24926 ** But we track the other locking levels internally.
24927 */
24928 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24929   unixFile *pFile = (unixFile*)id;
24930   char *zLockFile = (char *)pFile->lockingContext;
24931   int rc = SQLITE_OK;
24932 
24933 
24934   /* If we have any lock, then the lock file already exists.  All we have
24935   ** to do is adjust our internal record of the lock level.
24936   */
24937   if( pFile->eFileLock > NO_LOCK ){
24938     pFile->eFileLock = eFileLock;
24939     /* Always update the timestamp on the old file */
24940 #ifdef HAVE_UTIME
24941     utime(zLockFile, NULL);
24942 #else
24943     utimes(zLockFile, NULL);
24944 #endif
24945     return SQLITE_OK;
24946   }
24947 
24948   /* grab an exclusive lock */
24949   rc = osMkdir(zLockFile, 0777);
24950   if( rc<0 ){
24951     /* failed to open/create the lock directory */
24952     int tErrno = errno;
24953     if( EEXIST == tErrno ){
24954       rc = SQLITE_BUSY;
24955     } else {
24956       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24957       if( IS_LOCK_ERROR(rc) ){
24958         pFile->lastErrno = tErrno;
24959       }
24960     }
24961     return rc;
24962   }
24963 
24964   /* got it, set the type and return ok */
24965   pFile->eFileLock = eFileLock;
24966   return rc;
24967 }
24968 
24969 /*
24970 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24971 ** must be either NO_LOCK or SHARED_LOCK.
24972 **
24973 ** If the locking level of the file descriptor is already at or below
24974 ** the requested locking level, this routine is a no-op.
24975 **
24976 ** When the locking level reaches NO_LOCK, delete the lock file.
24977 */
24978 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24979   unixFile *pFile = (unixFile*)id;
24980   char *zLockFile = (char *)pFile->lockingContext;
24981   int rc;
24982 
24983   assert( pFile );
24984   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24985            pFile->eFileLock, getpid()));
24986   assert( eFileLock<=SHARED_LOCK );
24987 
24988   /* no-op if possible */
24989   if( pFile->eFileLock==eFileLock ){
24990     return SQLITE_OK;
24991   }
24992 
24993   /* To downgrade to shared, simply update our internal notion of the
24994   ** lock state.  No need to mess with the file on disk.
24995   */
24996   if( eFileLock==SHARED_LOCK ){
24997     pFile->eFileLock = SHARED_LOCK;
24998     return SQLITE_OK;
24999   }
25000 
25001   /* To fully unlock the database, delete the lock file */
25002   assert( eFileLock==NO_LOCK );
25003   rc = osRmdir(zLockFile);
25004   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25005   if( rc<0 ){
25006     int tErrno = errno;
25007     rc = 0;
25008     if( ENOENT != tErrno ){
25009       rc = SQLITE_IOERR_UNLOCK;
25010     }
25011     if( IS_LOCK_ERROR(rc) ){
25012       pFile->lastErrno = tErrno;
25013     }
25014     return rc;
25015   }
25016   pFile->eFileLock = NO_LOCK;
25017   return SQLITE_OK;
25018 }
25019 
25020 /*
25021 ** Close a file.  Make sure the lock has been released before closing.
25022 */
25023 static int dotlockClose(sqlite3_file *id) {
25024   int rc = SQLITE_OK;
25025   if( id ){
25026     unixFile *pFile = (unixFile*)id;
25027     dotlockUnlock(id, NO_LOCK);
25028     sqlite3_free(pFile->lockingContext);
25029     rc = closeUnixFile(id);
25030   }
25031   return rc;
25032 }
25033 /****************** End of the dot-file lock implementation *******************
25034 ******************************************************************************/
25035 
25036 /******************************************************************************
25037 ************************** Begin flock Locking ********************************
25038 **
25039 ** Use the flock() system call to do file locking.
25040 **
25041 ** flock() locking is like dot-file locking in that the various
25042 ** fine-grain locking levels supported by SQLite are collapsed into
25043 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
25044 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
25045 ** still works when you do this, but concurrency is reduced since
25046 ** only a single process can be reading the database at a time.
25047 **
25048 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25049 ** compiling for VXWORKS.
25050 */
25051 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25052 
25053 /*
25054 ** Retry flock() calls that fail with EINTR
25055 */
25056 #ifdef EINTR
25057 static int robust_flock(int fd, int op){
25058   int rc;
25059   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25060   return rc;
25061 }
25062 #else
25063 # define robust_flock(a,b) flock(a,b)
25064 #endif
25065 
25066 
25067 /*
25068 ** This routine checks if there is a RESERVED lock held on the specified
25069 ** file by this or any other process. If such a lock is held, set *pResOut
25070 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25071 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25072 */
25073 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25074   int rc = SQLITE_OK;
25075   int reserved = 0;
25076   unixFile *pFile = (unixFile*)id;
25077 
25078   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25079 
25080   assert( pFile );
25081 
25082   /* Check if a thread in this process holds such a lock */
25083   if( pFile->eFileLock>SHARED_LOCK ){
25084     reserved = 1;
25085   }
25086 
25087   /* Otherwise see if some other process holds it. */
25088   if( !reserved ){
25089     /* attempt to get the lock */
25090     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25091     if( !lrc ){
25092       /* got the lock, unlock it */
25093       lrc = robust_flock(pFile->h, LOCK_UN);
25094       if ( lrc ) {
25095         int tErrno = errno;
25096         /* unlock failed with an error */
25097         lrc = SQLITE_IOERR_UNLOCK;
25098         if( IS_LOCK_ERROR(lrc) ){
25099           pFile->lastErrno = tErrno;
25100           rc = lrc;
25101         }
25102       }
25103     } else {
25104       int tErrno = errno;
25105       reserved = 1;
25106       /* someone else might have it reserved */
25107       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25108       if( IS_LOCK_ERROR(lrc) ){
25109         pFile->lastErrno = tErrno;
25110         rc = lrc;
25111       }
25112     }
25113   }
25114   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25115 
25116 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25117   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25118     rc = SQLITE_OK;
25119     reserved=1;
25120   }
25121 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25122   *pResOut = reserved;
25123   return rc;
25124 }
25125 
25126 /*
25127 ** Lock the file with the lock specified by parameter eFileLock - one
25128 ** of the following:
25129 **
25130 **     (1) SHARED_LOCK
25131 **     (2) RESERVED_LOCK
25132 **     (3) PENDING_LOCK
25133 **     (4) EXCLUSIVE_LOCK
25134 **
25135 ** Sometimes when requesting one lock state, additional lock states
25136 ** are inserted in between.  The locking might fail on one of the later
25137 ** transitions leaving the lock state different from what it started but
25138 ** still short of its goal.  The following chart shows the allowed
25139 ** transitions and the inserted intermediate states:
25140 **
25141 **    UNLOCKED -> SHARED
25142 **    SHARED -> RESERVED
25143 **    SHARED -> (PENDING) -> EXCLUSIVE
25144 **    RESERVED -> (PENDING) -> EXCLUSIVE
25145 **    PENDING -> EXCLUSIVE
25146 **
25147 ** flock() only really support EXCLUSIVE locks.  We track intermediate
25148 ** lock states in the sqlite3_file structure, but all locks SHARED or
25149 ** above are really EXCLUSIVE locks and exclude all other processes from
25150 ** access the file.
25151 **
25152 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25153 ** routine to lower a locking level.
25154 */
25155 static int flockLock(sqlite3_file *id, int eFileLock) {
25156   int rc = SQLITE_OK;
25157   unixFile *pFile = (unixFile*)id;
25158 
25159   assert( pFile );
25160 
25161   /* if we already have a lock, it is exclusive.
25162   ** Just adjust level and punt on outta here. */
25163   if (pFile->eFileLock > NO_LOCK) {
25164     pFile->eFileLock = eFileLock;
25165     return SQLITE_OK;
25166   }
25167 
25168   /* grab an exclusive lock */
25169 
25170   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25171     int tErrno = errno;
25172     /* didn't get, must be busy */
25173     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25174     if( IS_LOCK_ERROR(rc) ){
25175       pFile->lastErrno = tErrno;
25176     }
25177   } else {
25178     /* got it, set the type and return ok */
25179     pFile->eFileLock = eFileLock;
25180   }
25181   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
25182            rc==SQLITE_OK ? "ok" : "failed"));
25183 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25184   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25185     rc = SQLITE_BUSY;
25186   }
25187 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25188   return rc;
25189 }
25190 
25191 
25192 /*
25193 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25194 ** must be either NO_LOCK or SHARED_LOCK.
25195 **
25196 ** If the locking level of the file descriptor is already at or below
25197 ** the requested locking level, this routine is a no-op.
25198 */
25199 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25200   unixFile *pFile = (unixFile*)id;
25201 
25202   assert( pFile );
25203   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25204            pFile->eFileLock, getpid()));
25205   assert( eFileLock<=SHARED_LOCK );
25206 
25207   /* no-op if possible */
25208   if( pFile->eFileLock==eFileLock ){
25209     return SQLITE_OK;
25210   }
25211 
25212   /* shared can just be set because we always have an exclusive */
25213   if (eFileLock==SHARED_LOCK) {
25214     pFile->eFileLock = eFileLock;
25215     return SQLITE_OK;
25216   }
25217 
25218   /* no, really, unlock. */
25219   if( robust_flock(pFile->h, LOCK_UN) ){
25220 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25221     return SQLITE_OK;
25222 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25223     return SQLITE_IOERR_UNLOCK;
25224   }else{
25225     pFile->eFileLock = NO_LOCK;
25226     return SQLITE_OK;
25227   }
25228 }
25229 
25230 /*
25231 ** Close a file.
25232 */
25233 static int flockClose(sqlite3_file *id) {
25234   int rc = SQLITE_OK;
25235   if( id ){
25236     flockUnlock(id, NO_LOCK);
25237     rc = closeUnixFile(id);
25238   }
25239   return rc;
25240 }
25241 
25242 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25243 
25244 /******************* End of the flock lock implementation *********************
25245 ******************************************************************************/
25246 
25247 /******************************************************************************
25248 ************************ Begin Named Semaphore Locking ************************
25249 **
25250 ** Named semaphore locking is only supported on VxWorks.
25251 **
25252 ** Semaphore locking is like dot-lock and flock in that it really only
25253 ** supports EXCLUSIVE locking.  Only a single process can read or write
25254 ** the database file at a time.  This reduces potential concurrency, but
25255 ** makes the lock implementation much easier.
25256 */
25257 #if OS_VXWORKS
25258 
25259 /*
25260 ** This routine checks if there is a RESERVED lock held on the specified
25261 ** file by this or any other process. If such a lock is held, set *pResOut
25262 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25263 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25264 */
25265 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25266   int rc = SQLITE_OK;
25267   int reserved = 0;
25268   unixFile *pFile = (unixFile*)id;
25269 
25270   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25271 
25272   assert( pFile );
25273 
25274   /* Check if a thread in this process holds such a lock */
25275   if( pFile->eFileLock>SHARED_LOCK ){
25276     reserved = 1;
25277   }
25278 
25279   /* Otherwise see if some other process holds it. */
25280   if( !reserved ){
25281     sem_t *pSem = pFile->pInode->pSem;
25282     struct stat statBuf;
25283 
25284     if( sem_trywait(pSem)==-1 ){
25285       int tErrno = errno;
25286       if( EAGAIN != tErrno ){
25287         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25288         pFile->lastErrno = tErrno;
25289       } else {
25290         /* someone else has the lock when we are in NO_LOCK */
25291         reserved = (pFile->eFileLock < SHARED_LOCK);
25292       }
25293     }else{
25294       /* we could have it if we want it */
25295       sem_post(pSem);
25296     }
25297   }
25298   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25299 
25300   *pResOut = reserved;
25301   return rc;
25302 }
25303 
25304 /*
25305 ** Lock the file with the lock specified by parameter eFileLock - one
25306 ** of the following:
25307 **
25308 **     (1) SHARED_LOCK
25309 **     (2) RESERVED_LOCK
25310 **     (3) PENDING_LOCK
25311 **     (4) EXCLUSIVE_LOCK
25312 **
25313 ** Sometimes when requesting one lock state, additional lock states
25314 ** are inserted in between.  The locking might fail on one of the later
25315 ** transitions leaving the lock state different from what it started but
25316 ** still short of its goal.  The following chart shows the allowed
25317 ** transitions and the inserted intermediate states:
25318 **
25319 **    UNLOCKED -> SHARED
25320 **    SHARED -> RESERVED
25321 **    SHARED -> (PENDING) -> EXCLUSIVE
25322 **    RESERVED -> (PENDING) -> EXCLUSIVE
25323 **    PENDING -> EXCLUSIVE
25324 **
25325 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25326 ** lock states in the sqlite3_file structure, but all locks SHARED or
25327 ** above are really EXCLUSIVE locks and exclude all other processes from
25328 ** access the file.
25329 **
25330 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25331 ** routine to lower a locking level.
25332 */
25333 static int semLock(sqlite3_file *id, int eFileLock) {
25334   unixFile *pFile = (unixFile*)id;
25335   int fd;
25336   sem_t *pSem = pFile->pInode->pSem;
25337   int rc = SQLITE_OK;
25338 
25339   /* if we already have a lock, it is exclusive.
25340   ** Just adjust level and punt on outta here. */
25341   if (pFile->eFileLock > NO_LOCK) {
25342     pFile->eFileLock = eFileLock;
25343     rc = SQLITE_OK;
25344     goto sem_end_lock;
25345   }
25346 
25347   /* lock semaphore now but bail out when already locked. */
25348   if( sem_trywait(pSem)==-1 ){
25349     rc = SQLITE_BUSY;
25350     goto sem_end_lock;
25351   }
25352 
25353   /* got it, set the type and return ok */
25354   pFile->eFileLock = eFileLock;
25355 
25356  sem_end_lock:
25357   return rc;
25358 }
25359 
25360 /*
25361 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25362 ** must be either NO_LOCK or SHARED_LOCK.
25363 **
25364 ** If the locking level of the file descriptor is already at or below
25365 ** the requested locking level, this routine is a no-op.
25366 */
25367 static int semUnlock(sqlite3_file *id, int eFileLock) {
25368   unixFile *pFile = (unixFile*)id;
25369   sem_t *pSem = pFile->pInode->pSem;
25370 
25371   assert( pFile );
25372   assert( pSem );
25373   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25374            pFile->eFileLock, getpid()));
25375   assert( eFileLock<=SHARED_LOCK );
25376 
25377   /* no-op if possible */
25378   if( pFile->eFileLock==eFileLock ){
25379     return SQLITE_OK;
25380   }
25381 
25382   /* shared can just be set because we always have an exclusive */
25383   if (eFileLock==SHARED_LOCK) {
25384     pFile->eFileLock = eFileLock;
25385     return SQLITE_OK;
25386   }
25387 
25388   /* no, really unlock. */
25389   if ( sem_post(pSem)==-1 ) {
25390     int rc, tErrno = errno;
25391     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25392     if( IS_LOCK_ERROR(rc) ){
25393       pFile->lastErrno = tErrno;
25394     }
25395     return rc;
25396   }
25397   pFile->eFileLock = NO_LOCK;
25398   return SQLITE_OK;
25399 }
25400 
25401 /*
25402  ** Close a file.
25403  */
25404 static int semClose(sqlite3_file *id) {
25405   if( id ){
25406     unixFile *pFile = (unixFile*)id;
25407     semUnlock(id, NO_LOCK);
25408     assert( pFile );
25409     unixEnterMutex();
25410     releaseInodeInfo(pFile);
25411     unixLeaveMutex();
25412     closeUnixFile(id);
25413   }
25414   return SQLITE_OK;
25415 }
25416 
25417 #endif /* OS_VXWORKS */
25418 /*
25419 ** Named semaphore locking is only available on VxWorks.
25420 **
25421 *************** End of the named semaphore lock implementation ****************
25422 ******************************************************************************/
25423 
25424 
25425 /******************************************************************************
25426 *************************** Begin AFP Locking *********************************
25427 **
25428 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25429 ** on Apple Macintosh computers - both OS9 and OSX.
25430 **
25431 ** Third-party implementations of AFP are available.  But this code here
25432 ** only works on OSX.
25433 */
25434 
25435 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25436 /*
25437 ** The afpLockingContext structure contains all afp lock specific state
25438 */
25439 typedef struct afpLockingContext afpLockingContext;
25440 struct afpLockingContext {
25441   int reserved;
25442   const char *dbPath;             /* Name of the open file */
25443 };
25444 
25445 struct ByteRangeLockPB2
25446 {
25447   unsigned long long offset;        /* offset to first byte to lock */
25448   unsigned long long length;        /* nbr of bytes to lock */
25449   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25450   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25451   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25452   int fd;                           /* file desc to assoc this lock with */
25453 };
25454 
25455 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25456 
25457 /*
25458 ** This is a utility for setting or clearing a bit-range lock on an
25459 ** AFP filesystem.
25460 **
25461 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25462 */
25463 static int afpSetLock(
25464   const char *path,              /* Name of the file to be locked or unlocked */
25465   unixFile *pFile,               /* Open file descriptor on path */
25466   unsigned long long offset,     /* First byte to be locked */
25467   unsigned long long length,     /* Number of bytes to lock */
25468   int setLockFlag                /* True to set lock.  False to clear lock */
25469 ){
25470   struct ByteRangeLockPB2 pb;
25471   int err;
25472 
25473   pb.unLockFlag = setLockFlag ? 0 : 1;
25474   pb.startEndFlag = 0;
25475   pb.offset = offset;
25476   pb.length = length;
25477   pb.fd = pFile->h;
25478 
25479   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
25480     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25481     offset, length));
25482   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25483   if ( err==-1 ) {
25484     int rc;
25485     int tErrno = errno;
25486     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25487              path, tErrno, strerror(tErrno)));
25488 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25489     rc = SQLITE_BUSY;
25490 #else
25491     rc = sqliteErrorFromPosixError(tErrno,
25492                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25493 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25494     if( IS_LOCK_ERROR(rc) ){
25495       pFile->lastErrno = tErrno;
25496     }
25497     return rc;
25498   } else {
25499     return SQLITE_OK;
25500   }
25501 }
25502 
25503 /*
25504 ** This routine checks if there is a RESERVED lock held on the specified
25505 ** file by this or any other process. If such a lock is held, set *pResOut
25506 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25507 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25508 */
25509 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25510   int rc = SQLITE_OK;
25511   int reserved = 0;
25512   unixFile *pFile = (unixFile*)id;
25513   afpLockingContext *context;
25514 
25515   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25516 
25517   assert( pFile );
25518   context = (afpLockingContext *) pFile->lockingContext;
25519   if( context->reserved ){
25520     *pResOut = 1;
25521     return SQLITE_OK;
25522   }
25523   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25524 
25525   /* Check if a thread in this process holds such a lock */
25526   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25527     reserved = 1;
25528   }
25529 
25530   /* Otherwise see if some other process holds it.
25531    */
25532   if( !reserved ){
25533     /* lock the RESERVED byte */
25534     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25535     if( SQLITE_OK==lrc ){
25536       /* if we succeeded in taking the reserved lock, unlock it to restore
25537       ** the original state */
25538       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25539     } else {
25540       /* if we failed to get the lock then someone else must have it */
25541       reserved = 1;
25542     }
25543     if( IS_LOCK_ERROR(lrc) ){
25544       rc=lrc;
25545     }
25546   }
25547 
25548   unixLeaveMutex();
25549   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25550 
25551   *pResOut = reserved;
25552   return rc;
25553 }
25554 
25555 /*
25556 ** Lock the file with the lock specified by parameter eFileLock - one
25557 ** of the following:
25558 **
25559 **     (1) SHARED_LOCK
25560 **     (2) RESERVED_LOCK
25561 **     (3) PENDING_LOCK
25562 **     (4) EXCLUSIVE_LOCK
25563 **
25564 ** Sometimes when requesting one lock state, additional lock states
25565 ** are inserted in between.  The locking might fail on one of the later
25566 ** transitions leaving the lock state different from what it started but
25567 ** still short of its goal.  The following chart shows the allowed
25568 ** transitions and the inserted intermediate states:
25569 **
25570 **    UNLOCKED -> SHARED
25571 **    SHARED -> RESERVED
25572 **    SHARED -> (PENDING) -> EXCLUSIVE
25573 **    RESERVED -> (PENDING) -> EXCLUSIVE
25574 **    PENDING -> EXCLUSIVE
25575 **
25576 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25577 ** routine to lower a locking level.
25578 */
25579 static int afpLock(sqlite3_file *id, int eFileLock){
25580   int rc = SQLITE_OK;
25581   unixFile *pFile = (unixFile*)id;
25582   unixInodeInfo *pInode = pFile->pInode;
25583   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25584 
25585   assert( pFile );
25586   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25587            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25588            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25589 
25590   /* If there is already a lock of this type or more restrictive on the
25591   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25592   ** unixEnterMutex() hasn't been called yet.
25593   */
25594   if( pFile->eFileLock>=eFileLock ){
25595     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25596            azFileLock(eFileLock)));
25597     return SQLITE_OK;
25598   }
25599 
25600   /* Make sure the locking sequence is correct
25601   **  (1) We never move from unlocked to anything higher than shared lock.
25602   **  (2) SQLite never explicitly requests a pendig lock.
25603   **  (3) A shared lock is always held when a reserve lock is requested.
25604   */
25605   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25606   assert( eFileLock!=PENDING_LOCK );
25607   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25608 
25609   /* This mutex is needed because pFile->pInode is shared across threads
25610   */
25611   unixEnterMutex();
25612   pInode = pFile->pInode;
25613 
25614   /* If some thread using this PID has a lock via a different unixFile*
25615   ** handle that precludes the requested lock, return BUSY.
25616   */
25617   if( (pFile->eFileLock!=pInode->eFileLock &&
25618        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25619      ){
25620     rc = SQLITE_BUSY;
25621     goto afp_end_lock;
25622   }
25623 
25624   /* If a SHARED lock is requested, and some thread using this PID already
25625   ** has a SHARED or RESERVED lock, then increment reference counts and
25626   ** return SQLITE_OK.
25627   */
25628   if( eFileLock==SHARED_LOCK &&
25629      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25630     assert( eFileLock==SHARED_LOCK );
25631     assert( pFile->eFileLock==0 );
25632     assert( pInode->nShared>0 );
25633     pFile->eFileLock = SHARED_LOCK;
25634     pInode->nShared++;
25635     pInode->nLock++;
25636     goto afp_end_lock;
25637   }
25638 
25639   /* A PENDING lock is needed before acquiring a SHARED lock and before
25640   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25641   ** be released.
25642   */
25643   if( eFileLock==SHARED_LOCK
25644       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25645   ){
25646     int failed;
25647     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25648     if (failed) {
25649       rc = failed;
25650       goto afp_end_lock;
25651     }
25652   }
25653 
25654   /* If control gets to this point, then actually go ahead and make
25655   ** operating system calls for the specified lock.
25656   */
25657   if( eFileLock==SHARED_LOCK ){
25658     int lrc1, lrc2, lrc1Errno = 0;
25659     long lk, mask;
25660 
25661     assert( pInode->nShared==0 );
25662     assert( pInode->eFileLock==0 );
25663 
25664     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25665     /* Now get the read-lock SHARED_LOCK */
25666     /* note that the quality of the randomness doesn't matter that much */
25667     lk = random();
25668     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25669     lrc1 = afpSetLock(context->dbPath, pFile,
25670           SHARED_FIRST+pInode->sharedByte, 1, 1);
25671     if( IS_LOCK_ERROR(lrc1) ){
25672       lrc1Errno = pFile->lastErrno;
25673     }
25674     /* Drop the temporary PENDING lock */
25675     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25676 
25677     if( IS_LOCK_ERROR(lrc1) ) {
25678       pFile->lastErrno = lrc1Errno;
25679       rc = lrc1;
25680       goto afp_end_lock;
25681     } else if( IS_LOCK_ERROR(lrc2) ){
25682       rc = lrc2;
25683       goto afp_end_lock;
25684     } else if( lrc1 != SQLITE_OK ) {
25685       rc = lrc1;
25686     } else {
25687       pFile->eFileLock = SHARED_LOCK;
25688       pInode->nLock++;
25689       pInode->nShared = 1;
25690     }
25691   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25692     /* We are trying for an exclusive lock but another thread in this
25693      ** same process is still holding a shared lock. */
25694     rc = SQLITE_BUSY;
25695   }else{
25696     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25697     ** assumed that there is a SHARED or greater lock on the file
25698     ** already.
25699     */
25700     int failed = 0;
25701     assert( 0!=pFile->eFileLock );
25702     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25703         /* Acquire a RESERVED lock */
25704         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25705       if( !failed ){
25706         context->reserved = 1;
25707       }
25708     }
25709     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25710       /* Acquire an EXCLUSIVE lock */
25711 
25712       /* Remove the shared lock before trying the range.  we'll need to
25713       ** reestablish the shared lock if we can't get the  afpUnlock
25714       */
25715       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25716                          pInode->sharedByte, 1, 0)) ){
25717         int failed2 = SQLITE_OK;
25718         /* now attemmpt to get the exclusive lock range */
25719         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
25720                                SHARED_SIZE, 1);
25721         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
25722                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25723           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25724           ** a critical I/O error
25725           */
25726           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
25727                SQLITE_IOERR_LOCK;
25728           goto afp_end_lock;
25729         }
25730       }else{
25731         rc = failed;
25732       }
25733     }
25734     if( failed ){
25735       rc = failed;
25736     }
25737   }
25738 
25739   if( rc==SQLITE_OK ){
25740     pFile->eFileLock = eFileLock;
25741     pInode->eFileLock = eFileLock;
25742   }else if( eFileLock==EXCLUSIVE_LOCK ){
25743     pFile->eFileLock = PENDING_LOCK;
25744     pInode->eFileLock = PENDING_LOCK;
25745   }
25746 
25747 afp_end_lock:
25748   unixLeaveMutex();
25749   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
25750          rc==SQLITE_OK ? "ok" : "failed"));
25751   return rc;
25752 }
25753 
25754 /*
25755 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25756 ** must be either NO_LOCK or SHARED_LOCK.
25757 **
25758 ** If the locking level of the file descriptor is already at or below
25759 ** the requested locking level, this routine is a no-op.
25760 */
25761 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25762   int rc = SQLITE_OK;
25763   unixFile *pFile = (unixFile*)id;
25764   unixInodeInfo *pInode;
25765   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25766   int skipShared = 0;
25767 #ifdef SQLITE_TEST
25768   int h = pFile->h;
25769 #endif
25770 
25771   assert( pFile );
25772   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25773            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25774            getpid()));
25775 
25776   assert( eFileLock<=SHARED_LOCK );
25777   if( pFile->eFileLock<=eFileLock ){
25778     return SQLITE_OK;
25779   }
25780   unixEnterMutex();
25781   pInode = pFile->pInode;
25782   assert( pInode->nShared!=0 );
25783   if( pFile->eFileLock>SHARED_LOCK ){
25784     assert( pInode->eFileLock==pFile->eFileLock );
25785     SimulateIOErrorBenign(1);
25786     SimulateIOError( h=(-1) )
25787     SimulateIOErrorBenign(0);
25788 
25789 #ifdef SQLITE_DEBUG
25790     /* When reducing a lock such that other processes can start
25791     ** reading the database file again, make sure that the
25792     ** transaction counter was updated if any part of the database
25793     ** file changed.  If the transaction counter is not updated,
25794     ** other connections to the same file might not realize that
25795     ** the file has changed and hence might not know to flush their
25796     ** cache.  The use of a stale cache can lead to database corruption.
25797     */
25798     assert( pFile->inNormalWrite==0
25799            || pFile->dbUpdate==0
25800            || pFile->transCntrChng==1 );
25801     pFile->inNormalWrite = 0;
25802 #endif
25803 
25804     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25805       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25806       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25807         /* only re-establish the shared lock if necessary */
25808         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25809         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25810       } else {
25811         skipShared = 1;
25812       }
25813     }
25814     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25815       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25816     }
25817     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25818       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25819       if( !rc ){
25820         context->reserved = 0;
25821       }
25822     }
25823     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25824       pInode->eFileLock = SHARED_LOCK;
25825     }
25826   }
25827   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25828 
25829     /* Decrement the shared lock counter.  Release the lock using an
25830     ** OS call only when all threads in this same process have released
25831     ** the lock.
25832     */
25833     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25834     pInode->nShared--;
25835     if( pInode->nShared==0 ){
25836       SimulateIOErrorBenign(1);
25837       SimulateIOError( h=(-1) )
25838       SimulateIOErrorBenign(0);
25839       if( !skipShared ){
25840         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25841       }
25842       if( !rc ){
25843         pInode->eFileLock = NO_LOCK;
25844         pFile->eFileLock = NO_LOCK;
25845       }
25846     }
25847     if( rc==SQLITE_OK ){
25848       pInode->nLock--;
25849       assert( pInode->nLock>=0 );
25850       if( pInode->nLock==0 ){
25851         closePendingFds(pFile);
25852       }
25853     }
25854   }
25855 
25856   unixLeaveMutex();
25857   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25858   return rc;
25859 }
25860 
25861 /*
25862 ** Close a file & cleanup AFP specific locking context
25863 */
25864 static int afpClose(sqlite3_file *id) {
25865   int rc = SQLITE_OK;
25866   if( id ){
25867     unixFile *pFile = (unixFile*)id;
25868     afpUnlock(id, NO_LOCK);
25869     unixEnterMutex();
25870     if( pFile->pInode && pFile->pInode->nLock ){
25871       /* If there are outstanding locks, do not actually close the file just
25872       ** yet because that would clear those locks.  Instead, add the file
25873       ** descriptor to pInode->aPending.  It will be automatically closed when
25874       ** the last lock is cleared.
25875       */
25876       setPendingFd(pFile);
25877     }
25878     releaseInodeInfo(pFile);
25879     sqlite3_free(pFile->lockingContext);
25880     rc = closeUnixFile(id);
25881     unixLeaveMutex();
25882   }
25883   return rc;
25884 }
25885 
25886 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25887 /*
25888 ** The code above is the AFP lock implementation.  The code is specific
25889 ** to MacOSX and does not work on other unix platforms.  No alternative
25890 ** is available.  If you don't compile for a mac, then the "unix-afp"
25891 ** VFS is not available.
25892 **
25893 ********************* End of the AFP lock implementation **********************
25894 ******************************************************************************/
25895 
25896 /******************************************************************************
25897 *************************** Begin NFS Locking ********************************/
25898 
25899 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25900 /*
25901  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25902  ** must be either NO_LOCK or SHARED_LOCK.
25903  **
25904  ** If the locking level of the file descriptor is already at or below
25905  ** the requested locking level, this routine is a no-op.
25906  */
25907 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25908   return posixUnlock(id, eFileLock, 1);
25909 }
25910 
25911 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25912 /*
25913 ** The code above is the NFS lock implementation.  The code is specific
25914 ** to MacOSX and does not work on other unix platforms.  No alternative
25915 ** is available.
25916 **
25917 ********************* End of the NFS lock implementation **********************
25918 ******************************************************************************/
25919 
25920 /******************************************************************************
25921 **************** Non-locking sqlite3_file methods *****************************
25922 **
25923 ** The next division contains implementations for all methods of the
25924 ** sqlite3_file object other than the locking methods.  The locking
25925 ** methods were defined in divisions above (one locking method per
25926 ** division).  Those methods that are common to all locking modes
25927 ** are gather together into this division.
25928 */
25929 
25930 /*
25931 ** Seek to the offset passed as the second argument, then read cnt
25932 ** bytes into pBuf. Return the number of bytes actually read.
25933 **
25934 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25935 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25936 ** one system to another.  Since SQLite does not define USE_PREAD
25937 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25938 ** See tickets #2741 and #2681.
25939 **
25940 ** To avoid stomping the errno value on a failed read the lastErrno value
25941 ** is set before returning.
25942 */
25943 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25944   int got;
25945   int prior = 0;
25946 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25947   i64 newOffset;
25948 #endif
25949   TIMER_START;
25950   assert( cnt==(cnt&0x1ffff) );
25951   cnt &= 0x1ffff;
25952   do{
25953 #if defined(USE_PREAD)
25954     got = osPread(id->h, pBuf, cnt, offset);
25955     SimulateIOError( got = -1 );
25956 #elif defined(USE_PREAD64)
25957     got = osPread64(id->h, pBuf, cnt, offset);
25958     SimulateIOError( got = -1 );
25959 #else
25960     newOffset = lseek(id->h, offset, SEEK_SET);
25961     SimulateIOError( newOffset-- );
25962     if( newOffset!=offset ){
25963       if( newOffset == -1 ){
25964         ((unixFile*)id)->lastErrno = errno;
25965       }else{
25966         ((unixFile*)id)->lastErrno = 0;
25967       }
25968       return -1;
25969     }
25970     got = osRead(id->h, pBuf, cnt);
25971 #endif
25972     if( got==cnt ) break;
25973     if( got<0 ){
25974       if( errno==EINTR ){ got = 1; continue; }
25975       prior = 0;
25976       ((unixFile*)id)->lastErrno = errno;
25977       break;
25978     }else if( got>0 ){
25979       cnt -= got;
25980       offset += got;
25981       prior += got;
25982       pBuf = (void*)(got + (char*)pBuf);
25983     }
25984   }while( got>0 );
25985   TIMER_END;
25986   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
25987             id->h, got+prior, offset-prior, TIMER_ELAPSED));
25988   return got+prior;
25989 }
25990 
25991 /*
25992 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25993 ** bytes were read successfully and SQLITE_IOERR if anything goes
25994 ** wrong.
25995 */
25996 static int unixRead(
25997   sqlite3_file *id,
25998   void *pBuf,
25999   int amt,
26000   sqlite3_int64 offset
26001 ){
26002   unixFile *pFile = (unixFile *)id;
26003   int got;
26004   assert( id );
26005 
26006   /* If this is a database file (not a journal, master-journal or temp
26007   ** file), the bytes in the locking range should never be read or written. */
26008 #if 0
26009   assert( pFile->pUnused==0
26010        || offset>=PENDING_BYTE+512
26011        || offset+amt<=PENDING_BYTE
26012   );
26013 #endif
26014 
26015   got = seekAndRead(pFile, offset, pBuf, amt);
26016   if( got==amt ){
26017     return SQLITE_OK;
26018   }else if( got<0 ){
26019     /* lastErrno set by seekAndRead */
26020     return SQLITE_IOERR_READ;
26021   }else{
26022     pFile->lastErrno = 0; /* not a system error */
26023     /* Unread parts of the buffer must be zero-filled */
26024     memset(&((char*)pBuf)[got], 0, amt-got);
26025     return SQLITE_IOERR_SHORT_READ;
26026   }
26027 }
26028 
26029 /*
26030 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
26031 ** Return the number of bytes actually read.  Update the offset.
26032 **
26033 ** To avoid stomping the errno value on a failed write the lastErrno value
26034 ** is set before returning.
26035 */
26036 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26037   int got;
26038 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26039   i64 newOffset;
26040 #endif
26041   assert( cnt==(cnt&0x1ffff) );
26042   cnt &= 0x1ffff;
26043   TIMER_START;
26044 #if defined(USE_PREAD)
26045   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
26046 #elif defined(USE_PREAD64)
26047   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
26048 #else
26049   do{
26050     newOffset = lseek(id->h, offset, SEEK_SET);
26051     SimulateIOError( newOffset-- );
26052     if( newOffset!=offset ){
26053       if( newOffset == -1 ){
26054         ((unixFile*)id)->lastErrno = errno;
26055       }else{
26056         ((unixFile*)id)->lastErrno = 0;
26057       }
26058       return -1;
26059     }
26060     got = osWrite(id->h, pBuf, cnt);
26061   }while( got<0 && errno==EINTR );
26062 #endif
26063   TIMER_END;
26064   if( got<0 ){
26065     ((unixFile*)id)->lastErrno = errno;
26066   }
26067 
26068   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
26069   return got;
26070 }
26071 
26072 
26073 /*
26074 ** Write data from a buffer into a file.  Return SQLITE_OK on success
26075 ** or some other error code on failure.
26076 */
26077 static int unixWrite(
26078   sqlite3_file *id,
26079   const void *pBuf,
26080   int amt,
26081   sqlite3_int64 offset
26082 ){
26083   unixFile *pFile = (unixFile*)id;
26084   int wrote = 0;
26085   assert( id );
26086   assert( amt>0 );
26087 
26088   /* If this is a database file (not a journal, master-journal or temp
26089   ** file), the bytes in the locking range should never be read or written. */
26090 #if 0
26091   assert( pFile->pUnused==0
26092        || offset>=PENDING_BYTE+512
26093        || offset+amt<=PENDING_BYTE
26094   );
26095 #endif
26096 
26097 #ifdef SQLITE_DEBUG
26098   /* If we are doing a normal write to a database file (as opposed to
26099   ** doing a hot-journal rollback or a write to some file other than a
26100   ** normal database file) then record the fact that the database
26101   ** has changed.  If the transaction counter is modified, record that
26102   ** fact too.
26103   */
26104   if( pFile->inNormalWrite ){
26105     pFile->dbUpdate = 1;  /* The database has been modified */
26106     if( offset<=24 && offset+amt>=27 ){
26107       int rc;
26108       char oldCntr[4];
26109       SimulateIOErrorBenign(1);
26110       rc = seekAndRead(pFile, 24, oldCntr, 4);
26111       SimulateIOErrorBenign(0);
26112       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26113         pFile->transCntrChng = 1;  /* The transaction counter has changed */
26114       }
26115     }
26116   }
26117 #endif
26118 
26119   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26120     amt -= wrote;
26121     offset += wrote;
26122     pBuf = &((char*)pBuf)[wrote];
26123   }
26124   SimulateIOError(( wrote=(-1), amt=1 ));
26125   SimulateDiskfullError(( wrote=0, amt=1 ));
26126 
26127   if( amt>0 ){
26128     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26129       /* lastErrno set by seekAndWrite */
26130       return SQLITE_IOERR_WRITE;
26131     }else{
26132       pFile->lastErrno = 0; /* not a system error */
26133       return SQLITE_FULL;
26134     }
26135   }
26136 
26137   return SQLITE_OK;
26138 }
26139 
26140 #ifdef SQLITE_TEST
26141 /*
26142 ** Count the number of fullsyncs and normal syncs.  This is used to test
26143 ** that syncs and fullsyncs are occurring at the right times.
26144 */
26145 SQLITE_API int sqlite3_sync_count = 0;
26146 SQLITE_API int sqlite3_fullsync_count = 0;
26147 #endif
26148 
26149 /*
26150 ** We do not trust systems to provide a working fdatasync().  Some do.
26151 ** Others do no.  To be safe, we will stick with the (slightly slower)
26152 ** fsync(). If you know that your system does support fdatasync() correctly,
26153 ** then simply compile with -Dfdatasync=fdatasync
26154 */
26155 #if !defined(fdatasync)
26156 # define fdatasync fsync
26157 #endif
26158 
26159 /*
26160 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26161 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
26162 ** only available on Mac OS X.  But that could change.
26163 */
26164 #ifdef F_FULLFSYNC
26165 # define HAVE_FULLFSYNC 1
26166 #else
26167 # define HAVE_FULLFSYNC 0
26168 #endif
26169 
26170 
26171 /*
26172 ** The fsync() system call does not work as advertised on many
26173 ** unix systems.  The following procedure is an attempt to make
26174 ** it work better.
26175 **
26176 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26177 ** for testing when we want to run through the test suite quickly.
26178 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26179 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26180 ** or power failure will likely corrupt the database file.
26181 **
26182 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26183 ** The idea behind dataOnly is that it should only write the file content
26184 ** to disk, not the inode.  We only set dataOnly if the file size is
26185 ** unchanged since the file size is part of the inode.  However,
26186 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26187 ** file size has changed.  The only real difference between fdatasync()
26188 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26189 ** inode if the mtime or owner or other inode attributes have changed.
26190 ** We only care about the file size, not the other file attributes, so
26191 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26192 ** So, we always use fdatasync() if it is available, regardless of
26193 ** the value of the dataOnly flag.
26194 */
26195 static int full_fsync(int fd, int fullSync, int dataOnly){
26196   int rc;
26197 
26198   /* The following "ifdef/elif/else/" block has the same structure as
26199   ** the one below. It is replicated here solely to avoid cluttering
26200   ** up the real code with the UNUSED_PARAMETER() macros.
26201   */
26202 #ifdef SQLITE_NO_SYNC
26203   UNUSED_PARAMETER(fd);
26204   UNUSED_PARAMETER(fullSync);
26205   UNUSED_PARAMETER(dataOnly);
26206 #elif HAVE_FULLFSYNC
26207   UNUSED_PARAMETER(dataOnly);
26208 #else
26209   UNUSED_PARAMETER(fullSync);
26210   UNUSED_PARAMETER(dataOnly);
26211 #endif
26212 
26213   /* Record the number of times that we do a normal fsync() and
26214   ** FULLSYNC.  This is used during testing to verify that this procedure
26215   ** gets called with the correct arguments.
26216   */
26217 #ifdef SQLITE_TEST
26218   if( fullSync ) sqlite3_fullsync_count++;
26219   sqlite3_sync_count++;
26220 #endif
26221 
26222   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26223   ** no-op
26224   */
26225 #ifdef SQLITE_NO_SYNC
26226   rc = SQLITE_OK;
26227 #elif HAVE_FULLFSYNC
26228   if( fullSync ){
26229     rc = osFcntl(fd, F_FULLFSYNC, 0);
26230   }else{
26231     rc = 1;
26232   }
26233   /* If the FULLFSYNC failed, fall back to attempting an fsync().
26234   ** It shouldn't be possible for fullfsync to fail on the local
26235   ** file system (on OSX), so failure indicates that FULLFSYNC
26236   ** isn't supported for this file system. So, attempt an fsync
26237   ** and (for now) ignore the overhead of a superfluous fcntl call.
26238   ** It'd be better to detect fullfsync support once and avoid
26239   ** the fcntl call every time sync is called.
26240   */
26241   if( rc ) rc = fsync(fd);
26242 
26243 #elif defined(__APPLE__)
26244   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26245   ** so currently we default to the macro that redefines fdatasync to fsync
26246   */
26247   rc = fsync(fd);
26248 #else
26249   rc = fdatasync(fd);
26250 #if OS_VXWORKS
26251   if( rc==-1 && errno==ENOTSUP ){
26252     rc = fsync(fd);
26253   }
26254 #endif /* OS_VXWORKS */
26255 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26256 
26257   if( OS_VXWORKS && rc!= -1 ){
26258     rc = 0;
26259   }
26260   return rc;
26261 }
26262 
26263 /*
26264 ** Open a file descriptor to the directory containing file zFilename.
26265 ** If successful, *pFd is set to the opened file descriptor and
26266 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26267 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26268 ** value.
26269 **
26270 ** The directory file descriptor is used for only one thing - to
26271 ** fsync() a directory to make sure file creation and deletion events
26272 ** are flushed to disk.  Such fsyncs are not needed on newer
26273 ** journaling filesystems, but are required on older filesystems.
26274 **
26275 ** This routine can be overridden using the xSetSysCall interface.
26276 ** The ability to override this routine was added in support of the
26277 ** chromium sandbox.  Opening a directory is a security risk (we are
26278 ** told) so making it overrideable allows the chromium sandbox to
26279 ** replace this routine with a harmless no-op.  To make this routine
26280 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26281 ** *pFd set to a negative number.
26282 **
26283 ** If SQLITE_OK is returned, the caller is responsible for closing
26284 ** the file descriptor *pFd using close().
26285 */
26286 static int openDirectory(const char *zFilename, int *pFd){
26287   int ii;
26288   int fd = -1;
26289   char zDirname[MAX_PATHNAME+1];
26290 
26291   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26292   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26293   if( ii>0 ){
26294     zDirname[ii] = '\0';
26295     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26296     if( fd>=0 ){
26297       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26298     }
26299   }
26300   *pFd = fd;
26301   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26302 }
26303 
26304 /*
26305 ** Make sure all writes to a particular file are committed to disk.
26306 **
26307 ** If dataOnly==0 then both the file itself and its metadata (file
26308 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
26309 ** file data is synced.
26310 **
26311 ** Under Unix, also make sure that the directory entry for the file
26312 ** has been created by fsync-ing the directory that contains the file.
26313 ** If we do not do this and we encounter a power failure, the directory
26314 ** entry for the journal might not exist after we reboot.  The next
26315 ** SQLite to access the file will not know that the journal exists (because
26316 ** the directory entry for the journal was never created) and the transaction
26317 ** will not roll back - possibly leading to database corruption.
26318 */
26319 static int unixSync(sqlite3_file *id, int flags){
26320   int rc;
26321   unixFile *pFile = (unixFile*)id;
26322 
26323   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26324   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26325 
26326   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26327   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26328       || (flags&0x0F)==SQLITE_SYNC_FULL
26329   );
26330 
26331   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26332   ** line is to test that doing so does not cause any problems.
26333   */
26334   SimulateDiskfullError( return SQLITE_FULL );
26335 
26336   assert( pFile );
26337   OSTRACE(("SYNC    %-3d\n", pFile->h));
26338   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26339   SimulateIOError( rc=1 );
26340   if( rc ){
26341     pFile->lastErrno = errno;
26342     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26343   }
26344 
26345   /* Also fsync the directory containing the file if the DIRSYNC flag
26346   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
26347   ** are unable to fsync a directory, so ignore errors on the fsync.
26348   */
26349   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26350     int dirfd;
26351     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26352             HAVE_FULLFSYNC, isFullsync));
26353     rc = osOpenDirectory(pFile->zPath, &dirfd);
26354     if( rc==SQLITE_OK && dirfd>=0 ){
26355       full_fsync(dirfd, 0, 0);
26356       robust_close(pFile, dirfd, __LINE__);
26357     }else if( rc==SQLITE_CANTOPEN ){
26358       rc = SQLITE_OK;
26359     }
26360     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26361   }
26362   return rc;
26363 }
26364 
26365 /*
26366 ** Truncate an open file to a specified size
26367 */
26368 static int unixTruncate(sqlite3_file *id, i64 nByte){
26369   unixFile *pFile = (unixFile *)id;
26370   int rc;
26371   assert( pFile );
26372   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26373 
26374   /* If the user has configured a chunk-size for this file, truncate the
26375   ** file so that it consists of an integer number of chunks (i.e. the
26376   ** actual file size after the operation may be larger than the requested
26377   ** size).
26378   */
26379   if( pFile->szChunk>0 ){
26380     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26381   }
26382 
26383   rc = robust_ftruncate(pFile->h, (off_t)nByte);
26384   if( rc ){
26385     pFile->lastErrno = errno;
26386     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26387   }else{
26388 #ifdef SQLITE_DEBUG
26389     /* If we are doing a normal write to a database file (as opposed to
26390     ** doing a hot-journal rollback or a write to some file other than a
26391     ** normal database file) and we truncate the file to zero length,
26392     ** that effectively updates the change counter.  This might happen
26393     ** when restoring a database using the backup API from a zero-length
26394     ** source.
26395     */
26396     if( pFile->inNormalWrite && nByte==0 ){
26397       pFile->transCntrChng = 1;
26398     }
26399 #endif
26400 
26401     return SQLITE_OK;
26402   }
26403 }
26404 
26405 /*
26406 ** Determine the current size of a file in bytes
26407 */
26408 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26409   int rc;
26410   struct stat buf;
26411   assert( id );
26412   rc = osFstat(((unixFile*)id)->h, &buf);
26413   SimulateIOError( rc=1 );
26414   if( rc!=0 ){
26415     ((unixFile*)id)->lastErrno = errno;
26416     return SQLITE_IOERR_FSTAT;
26417   }
26418   *pSize = buf.st_size;
26419 
26420   /* When opening a zero-size database, the findInodeInfo() procedure
26421   ** writes a single byte into that file in order to work around a bug
26422   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26423   ** layers, we need to report this file size as zero even though it is
26424   ** really 1.   Ticket #3260.
26425   */
26426   if( *pSize==1 ) *pSize = 0;
26427 
26428 
26429   return SQLITE_OK;
26430 }
26431 
26432 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26433 /*
26434 ** Handler for proxy-locking file-control verbs.  Defined below in the
26435 ** proxying locking division.
26436 */
26437 static int proxyFileControl(sqlite3_file*,int,void*);
26438 #endif
26439 
26440 /*
26441 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
26442 ** file-control operation.  Enlarge the database to nBytes in size
26443 ** (rounded up to the next chunk-size).  If the database is already
26444 ** nBytes or larger, this routine is a no-op.
26445 */
26446 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26447   if( pFile->szChunk>0 ){
26448     i64 nSize;                    /* Required file size */
26449     struct stat buf;              /* Used to hold return values of fstat() */
26450 
26451     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26452 
26453     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26454     if( nSize>(i64)buf.st_size ){
26455 
26456 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26457       /* The code below is handling the return value of osFallocate()
26458       ** correctly. posix_fallocate() is defined to "returns zero on success,
26459       ** or an error number on  failure". See the manpage for details. */
26460       int err;
26461       do{
26462         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26463       }while( err==EINTR );
26464       if( err ) return SQLITE_IOERR_WRITE;
26465 #else
26466       /* If the OS does not have posix_fallocate(), fake it. First use
26467       ** ftruncate() to set the file size, then write a single byte to
26468       ** the last byte in each block within the extended region. This
26469       ** is the same technique used by glibc to implement posix_fallocate()
26470       ** on systems that do not have a real fallocate() system call.
26471       */
26472       int nBlk = buf.st_blksize;  /* File-system block size */
26473       i64 iWrite;                 /* Next offset to write to */
26474 
26475       if( robust_ftruncate(pFile->h, nSize) ){
26476         pFile->lastErrno = errno;
26477         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26478       }
26479       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26480       while( iWrite<nSize ){
26481         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26482         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26483         iWrite += nBlk;
26484       }
26485 #endif
26486     }
26487   }
26488 
26489   return SQLITE_OK;
26490 }
26491 
26492 /*
26493 ** If *pArg is inititially negative then this is a query.  Set *pArg to
26494 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26495 **
26496 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26497 */
26498 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26499   if( *pArg<0 ){
26500     *pArg = (pFile->ctrlFlags & mask)!=0;
26501   }else if( (*pArg)==0 ){
26502     pFile->ctrlFlags &= ~mask;
26503   }else{
26504     pFile->ctrlFlags |= mask;
26505   }
26506 }
26507 
26508 /* Forward declaration */
26509 static int unixGetTempname(int nBuf, char *zBuf);
26510 
26511 /*
26512 ** Information and control of an open file handle.
26513 */
26514 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26515   unixFile *pFile = (unixFile*)id;
26516   switch( op ){
26517     case SQLITE_FCNTL_LOCKSTATE: {
26518       *(int*)pArg = pFile->eFileLock;
26519       return SQLITE_OK;
26520     }
26521     case SQLITE_LAST_ERRNO: {
26522       *(int*)pArg = pFile->lastErrno;
26523       return SQLITE_OK;
26524     }
26525     case SQLITE_FCNTL_CHUNK_SIZE: {
26526       pFile->szChunk = *(int *)pArg;
26527       return SQLITE_OK;
26528     }
26529     case SQLITE_FCNTL_SIZE_HINT: {
26530       int rc;
26531       SimulateIOErrorBenign(1);
26532       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26533       SimulateIOErrorBenign(0);
26534       return rc;
26535     }
26536     case SQLITE_FCNTL_PERSIST_WAL: {
26537       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26538       return SQLITE_OK;
26539     }
26540     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26541       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26542       return SQLITE_OK;
26543     }
26544     case SQLITE_FCNTL_VFSNAME: {
26545       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26546       return SQLITE_OK;
26547     }
26548     case SQLITE_FCNTL_TEMPFILENAME: {
26549       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
26550       if( zTFile ){
26551         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
26552         *(char**)pArg = zTFile;
26553       }
26554       return SQLITE_OK;
26555     }
26556 #ifdef SQLITE_DEBUG
26557     /* The pager calls this method to signal that it has done
26558     ** a rollback and that the database is therefore unchanged and
26559     ** it hence it is OK for the transaction change counter to be
26560     ** unchanged.
26561     */
26562     case SQLITE_FCNTL_DB_UNCHANGED: {
26563       ((unixFile*)id)->dbUpdate = 0;
26564       return SQLITE_OK;
26565     }
26566 #endif
26567 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26568     case SQLITE_SET_LOCKPROXYFILE:
26569     case SQLITE_GET_LOCKPROXYFILE: {
26570       return proxyFileControl(id,op,pArg);
26571     }
26572 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26573   }
26574   return SQLITE_NOTFOUND;
26575 }
26576 
26577 /*
26578 ** Return the sector size in bytes of the underlying block device for
26579 ** the specified file. This is almost always 512 bytes, but may be
26580 ** larger for some devices.
26581 **
26582 ** SQLite code assumes this function cannot fail. It also assumes that
26583 ** if two files are created in the same file-system directory (i.e.
26584 ** a database and its journal file) that the sector size will be the
26585 ** same for both.
26586 */
26587 #ifndef __QNXNTO__
26588 static int unixSectorSize(sqlite3_file *NotUsed){
26589   UNUSED_PARAMETER(NotUsed);
26590   return SQLITE_DEFAULT_SECTOR_SIZE;
26591 }
26592 #endif
26593 
26594 /*
26595 ** The following version of unixSectorSize() is optimized for QNX.
26596 */
26597 #ifdef __QNXNTO__
26598 #include <sys/dcmd_blk.h>
26599 #include <sys/statvfs.h>
26600 static int unixSectorSize(sqlite3_file *id){
26601   unixFile *pFile = (unixFile*)id;
26602   if( pFile->sectorSize == 0 ){
26603     struct statvfs fsInfo;
26604 
26605     /* Set defaults for non-supported filesystems */
26606     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26607     pFile->deviceCharacteristics = 0;
26608     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
26609       return pFile->sectorSize;
26610     }
26611 
26612     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
26613       pFile->sectorSize = fsInfo.f_bsize;
26614       pFile->deviceCharacteristics =
26615         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
26616         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26617                                       ** the write succeeds */
26618         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26619                                       ** so it is ordered */
26620         0;
26621     }else if( strstr(fsInfo.f_basetype, "etfs") ){
26622       pFile->sectorSize = fsInfo.f_bsize;
26623       pFile->deviceCharacteristics =
26624         /* etfs cluster size writes are atomic */
26625         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
26626         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26627                                       ** the write succeeds */
26628         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26629                                       ** so it is ordered */
26630         0;
26631     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
26632       pFile->sectorSize = fsInfo.f_bsize;
26633       pFile->deviceCharacteristics =
26634         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
26635         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26636                                       ** the write succeeds */
26637         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26638                                       ** so it is ordered */
26639         0;
26640     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
26641       pFile->sectorSize = fsInfo.f_bsize;
26642       pFile->deviceCharacteristics =
26643         /* full bitset of atomics from max sector size and smaller */
26644         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26645         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26646                                       ** so it is ordered */
26647         0;
26648     }else if( strstr(fsInfo.f_basetype, "dos") ){
26649       pFile->sectorSize = fsInfo.f_bsize;
26650       pFile->deviceCharacteristics =
26651         /* full bitset of atomics from max sector size and smaller */
26652         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26653         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26654                                       ** so it is ordered */
26655         0;
26656     }else{
26657       pFile->deviceCharacteristics =
26658         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
26659         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26660                                       ** the write succeeds */
26661         0;
26662     }
26663   }
26664   /* Last chance verification.  If the sector size isn't a multiple of 512
26665   ** then it isn't valid.*/
26666   if( pFile->sectorSize % 512 != 0 ){
26667     pFile->deviceCharacteristics = 0;
26668     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26669   }
26670   return pFile->sectorSize;
26671 }
26672 #endif /* __QNXNTO__ */
26673 
26674 /*
26675 ** Return the device characteristics for the file.
26676 **
26677 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
26678 ** However, that choice is contraversial since technically the underlying
26679 ** file system does not always provide powersafe overwrites.  (In other
26680 ** words, after a power-loss event, parts of the file that were never
26681 ** written might end up being altered.)  However, non-PSOW behavior is very,
26682 ** very rare.  And asserting PSOW makes a large reduction in the amount
26683 ** of required I/O for journaling, since a lot of padding is eliminated.
26684 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
26685 ** available to turn it off and URI query parameter available to turn it off.
26686 */
26687 static int unixDeviceCharacteristics(sqlite3_file *id){
26688   unixFile *p = (unixFile*)id;
26689   int rc = 0;
26690 #ifdef __QNXNTO__
26691   if( p->sectorSize==0 ) unixSectorSize(id);
26692   rc = p->deviceCharacteristics;
26693 #endif
26694   if( p->ctrlFlags & UNIXFILE_PSOW ){
26695     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
26696   }
26697   return rc;
26698 }
26699 
26700 #ifndef SQLITE_OMIT_WAL
26701 
26702 
26703 /*
26704 ** Object used to represent an shared memory buffer.
26705 **
26706 ** When multiple threads all reference the same wal-index, each thread
26707 ** has its own unixShm object, but they all point to a single instance
26708 ** of this unixShmNode object.  In other words, each wal-index is opened
26709 ** only once per process.
26710 **
26711 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26712 ** We could coalesce this object into unixInodeInfo, but that would mean
26713 ** every open file that does not use shared memory (in other words, most
26714 ** open files) would have to carry around this extra information.  So
26715 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26716 ** and the unixShmNode object is created only when needed.
26717 **
26718 ** unixMutexHeld() must be true when creating or destroying
26719 ** this object or while reading or writing the following fields:
26720 **
26721 **      nRef
26722 **
26723 ** The following fields are read-only after the object is created:
26724 **
26725 **      fid
26726 **      zFilename
26727 **
26728 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26729 ** unixMutexHeld() is true when reading or writing any other field
26730 ** in this structure.
26731 */
26732 struct unixShmNode {
26733   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26734   sqlite3_mutex *mutex;      /* Mutex to access this object */
26735   char *zFilename;           /* Name of the mmapped file */
26736   int h;                     /* Open file descriptor */
26737   int szRegion;              /* Size of shared-memory regions */
26738   u16 nRegion;               /* Size of array apRegion */
26739   u8 isReadonly;             /* True if read-only */
26740   char **apRegion;           /* Array of mapped shared-memory regions */
26741   int nRef;                  /* Number of unixShm objects pointing to this */
26742   unixShm *pFirst;           /* All unixShm objects pointing to this */
26743 #ifdef SQLITE_DEBUG
26744   u8 exclMask;               /* Mask of exclusive locks held */
26745   u8 sharedMask;             /* Mask of shared locks held */
26746   u8 nextShmId;              /* Next available unixShm.id value */
26747 #endif
26748 };
26749 
26750 /*
26751 ** Structure used internally by this VFS to record the state of an
26752 ** open shared memory connection.
26753 **
26754 ** The following fields are initialized when this object is created and
26755 ** are read-only thereafter:
26756 **
26757 **    unixShm.pFile
26758 **    unixShm.id
26759 **
26760 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26761 ** while accessing any read/write fields.
26762 */
26763 struct unixShm {
26764   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26765   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26766   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26767   u8 id;                     /* Id of this connection within its unixShmNode */
26768   u16 sharedMask;            /* Mask of shared locks held */
26769   u16 exclMask;              /* Mask of exclusive locks held */
26770 };
26771 
26772 /*
26773 ** Constants used for locking
26774 */
26775 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26776 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26777 
26778 /*
26779 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26780 **
26781 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26782 ** otherwise.
26783 */
26784 static int unixShmSystemLock(
26785   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26786   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26787   int ofst,              /* First byte of the locking range */
26788   int n                  /* Number of bytes to lock */
26789 ){
26790   struct flock f;       /* The posix advisory locking structure */
26791   int rc = SQLITE_OK;   /* Result code form fcntl() */
26792 
26793   /* Access to the unixShmNode object is serialized by the caller */
26794   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26795 
26796   /* Shared locks never span more than one byte */
26797   assert( n==1 || lockType!=F_RDLCK );
26798 
26799   /* Locks are within range */
26800   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26801 
26802   if( pShmNode->h>=0 ){
26803     /* Initialize the locking parameters */
26804     memset(&f, 0, sizeof(f));
26805     f.l_type = lockType;
26806     f.l_whence = SEEK_SET;
26807     f.l_start = ofst;
26808     f.l_len = n;
26809 
26810     rc = osFcntl(pShmNode->h, F_SETLK, &f);
26811     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26812   }
26813 
26814   /* Update the global lock state and do debug tracing */
26815 #ifdef SQLITE_DEBUG
26816   { u16 mask;
26817   OSTRACE(("SHM-LOCK "));
26818   mask = (1<<(ofst+n)) - (1<<ofst);
26819   if( rc==SQLITE_OK ){
26820     if( lockType==F_UNLCK ){
26821       OSTRACE(("unlock %d ok", ofst));
26822       pShmNode->exclMask &= ~mask;
26823       pShmNode->sharedMask &= ~mask;
26824     }else if( lockType==F_RDLCK ){
26825       OSTRACE(("read-lock %d ok", ofst));
26826       pShmNode->exclMask &= ~mask;
26827       pShmNode->sharedMask |= mask;
26828     }else{
26829       assert( lockType==F_WRLCK );
26830       OSTRACE(("write-lock %d ok", ofst));
26831       pShmNode->exclMask |= mask;
26832       pShmNode->sharedMask &= ~mask;
26833     }
26834   }else{
26835     if( lockType==F_UNLCK ){
26836       OSTRACE(("unlock %d failed", ofst));
26837     }else if( lockType==F_RDLCK ){
26838       OSTRACE(("read-lock failed"));
26839     }else{
26840       assert( lockType==F_WRLCK );
26841       OSTRACE(("write-lock %d failed", ofst));
26842     }
26843   }
26844   OSTRACE((" - afterwards %03x,%03x\n",
26845            pShmNode->sharedMask, pShmNode->exclMask));
26846   }
26847 #endif
26848 
26849   return rc;
26850 }
26851 
26852 
26853 /*
26854 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26855 **
26856 ** This is not a VFS shared-memory method; it is a utility function called
26857 ** by VFS shared-memory methods.
26858 */
26859 static void unixShmPurge(unixFile *pFd){
26860   unixShmNode *p = pFd->pInode->pShmNode;
26861   assert( unixMutexHeld() );
26862   if( p && p->nRef==0 ){
26863     int i;
26864     assert( p->pInode==pFd->pInode );
26865     sqlite3_mutex_free(p->mutex);
26866     for(i=0; i<p->nRegion; i++){
26867       if( p->h>=0 ){
26868         munmap(p->apRegion[i], p->szRegion);
26869       }else{
26870         sqlite3_free(p->apRegion[i]);
26871       }
26872     }
26873     sqlite3_free(p->apRegion);
26874     if( p->h>=0 ){
26875       robust_close(pFd, p->h, __LINE__);
26876       p->h = -1;
26877     }
26878     p->pInode->pShmNode = 0;
26879     sqlite3_free(p);
26880   }
26881 }
26882 
26883 /*
26884 ** Open a shared-memory area associated with open database file pDbFd.
26885 ** This particular implementation uses mmapped files.
26886 **
26887 ** The file used to implement shared-memory is in the same directory
26888 ** as the open database file and has the same name as the open database
26889 ** file with the "-shm" suffix added.  For example, if the database file
26890 ** is "/home/user1/config.db" then the file that is created and mmapped
26891 ** for shared memory will be called "/home/user1/config.db-shm".
26892 **
26893 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26894 ** some other tmpfs mount. But if a file in a different directory
26895 ** from the database file is used, then differing access permissions
26896 ** or a chroot() might cause two different processes on the same
26897 ** database to end up using different files for shared memory -
26898 ** meaning that their memory would not really be shared - resulting
26899 ** in database corruption.  Nevertheless, this tmpfs file usage
26900 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26901 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26902 ** option results in an incompatible build of SQLite;  builds of SQLite
26903 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26904 ** same database file at the same time, database corruption will likely
26905 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26906 ** "unsupported" and may go away in a future SQLite release.
26907 **
26908 ** When opening a new shared-memory file, if no other instances of that
26909 ** file are currently open, in this process or in other processes, then
26910 ** the file must be truncated to zero length or have its header cleared.
26911 **
26912 ** If the original database file (pDbFd) is using the "unix-excl" VFS
26913 ** that means that an exclusive lock is held on the database file and
26914 ** that no other processes are able to read or write the database.  In
26915 ** that case, we do not really need shared memory.  No shared memory
26916 ** file is created.  The shared memory will be simulated with heap memory.
26917 */
26918 static int unixOpenSharedMemory(unixFile *pDbFd){
26919   struct unixShm *p = 0;          /* The connection to be opened */
26920   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26921   int rc;                         /* Result code */
26922   unixInodeInfo *pInode;          /* The inode of fd */
26923   char *zShmFilename;             /* Name of the file used for SHM */
26924   int nShmFilename;               /* Size of the SHM filename in bytes */
26925 
26926   /* Allocate space for the new unixShm object. */
26927   p = sqlite3_malloc( sizeof(*p) );
26928   if( p==0 ) return SQLITE_NOMEM;
26929   memset(p, 0, sizeof(*p));
26930   assert( pDbFd->pShm==0 );
26931 
26932   /* Check to see if a unixShmNode object already exists. Reuse an existing
26933   ** one if present. Create a new one if necessary.
26934   */
26935   unixEnterMutex();
26936   pInode = pDbFd->pInode;
26937   pShmNode = pInode->pShmNode;
26938   if( pShmNode==0 ){
26939     struct stat sStat;                 /* fstat() info for database file */
26940 
26941     /* Call fstat() to figure out the permissions on the database file. If
26942     ** a new *-shm file is created, an attempt will be made to create it
26943     ** with the same permissions.
26944     */
26945     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
26946       rc = SQLITE_IOERR_FSTAT;
26947       goto shm_open_err;
26948     }
26949 
26950 #ifdef SQLITE_SHM_DIRECTORY
26951     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
26952 #else
26953     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
26954 #endif
26955     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26956     if( pShmNode==0 ){
26957       rc = SQLITE_NOMEM;
26958       goto shm_open_err;
26959     }
26960     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
26961     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26962 #ifdef SQLITE_SHM_DIRECTORY
26963     sqlite3_snprintf(nShmFilename, zShmFilename,
26964                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26965                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26966 #else
26967     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26968     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
26969 #endif
26970     pShmNode->h = -1;
26971     pDbFd->pInode->pShmNode = pShmNode;
26972     pShmNode->pInode = pDbFd->pInode;
26973     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26974     if( pShmNode->mutex==0 ){
26975       rc = SQLITE_NOMEM;
26976       goto shm_open_err;
26977     }
26978 
26979     if( pInode->bProcessLock==0 ){
26980       int openFlags = O_RDWR | O_CREAT;
26981       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
26982         openFlags = O_RDONLY;
26983         pShmNode->isReadonly = 1;
26984       }
26985       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
26986       if( pShmNode->h<0 ){
26987         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
26988         goto shm_open_err;
26989       }
26990 
26991       /* If this process is running as root, make sure that the SHM file
26992       ** is owned by the same user that owns the original database.  Otherwise,
26993       ** the original owner will not be able to connect.
26994       */
26995       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
26996 
26997       /* Check to see if another process is holding the dead-man switch.
26998       ** If not, truncate the file to zero length.
26999       */
27000       rc = SQLITE_OK;
27001       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27002         if( robust_ftruncate(pShmNode->h, 0) ){
27003           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27004         }
27005       }
27006       if( rc==SQLITE_OK ){
27007         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27008       }
27009       if( rc ) goto shm_open_err;
27010     }
27011   }
27012 
27013   /* Make the new connection a child of the unixShmNode */
27014   p->pShmNode = pShmNode;
27015 #ifdef SQLITE_DEBUG
27016   p->id = pShmNode->nextShmId++;
27017 #endif
27018   pShmNode->nRef++;
27019   pDbFd->pShm = p;
27020   unixLeaveMutex();
27021 
27022   /* The reference count on pShmNode has already been incremented under
27023   ** the cover of the unixEnterMutex() mutex and the pointer from the
27024   ** new (struct unixShm) object to the pShmNode has been set. All that is
27025   ** left to do is to link the new object into the linked list starting
27026   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
27027   ** mutex.
27028   */
27029   sqlite3_mutex_enter(pShmNode->mutex);
27030   p->pNext = pShmNode->pFirst;
27031   pShmNode->pFirst = p;
27032   sqlite3_mutex_leave(pShmNode->mutex);
27033   return SQLITE_OK;
27034 
27035   /* Jump here on any error */
27036 shm_open_err:
27037   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27038   sqlite3_free(p);
27039   unixLeaveMutex();
27040   return rc;
27041 }
27042 
27043 /*
27044 ** This function is called to obtain a pointer to region iRegion of the
27045 ** shared-memory associated with the database file fd. Shared-memory regions
27046 ** are numbered starting from zero. Each shared-memory region is szRegion
27047 ** bytes in size.
27048 **
27049 ** If an error occurs, an error code is returned and *pp is set to NULL.
27050 **
27051 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27052 ** region has not been allocated (by any client, including one running in a
27053 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
27054 ** bExtend is non-zero and the requested shared-memory region has not yet
27055 ** been allocated, it is allocated by this function.
27056 **
27057 ** If the shared-memory region has already been allocated or is allocated by
27058 ** this call as described above, then it is mapped into this processes
27059 ** address space (if it is not already), *pp is set to point to the mapped
27060 ** memory and SQLITE_OK returned.
27061 */
27062 static int unixShmMap(
27063   sqlite3_file *fd,               /* Handle open on database file */
27064   int iRegion,                    /* Region to retrieve */
27065   int szRegion,                   /* Size of regions */
27066   int bExtend,                    /* True to extend file if necessary */
27067   void volatile **pp              /* OUT: Mapped memory */
27068 ){
27069   unixFile *pDbFd = (unixFile*)fd;
27070   unixShm *p;
27071   unixShmNode *pShmNode;
27072   int rc = SQLITE_OK;
27073 
27074   /* If the shared-memory file has not yet been opened, open it now. */
27075   if( pDbFd->pShm==0 ){
27076     rc = unixOpenSharedMemory(pDbFd);
27077     if( rc!=SQLITE_OK ) return rc;
27078   }
27079 
27080   p = pDbFd->pShm;
27081   pShmNode = p->pShmNode;
27082   sqlite3_mutex_enter(pShmNode->mutex);
27083   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27084   assert( pShmNode->pInode==pDbFd->pInode );
27085   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27086   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27087 
27088   if( pShmNode->nRegion<=iRegion ){
27089     char **apNew;                      /* New apRegion[] array */
27090     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27091     struct stat sStat;                 /* Used by fstat() */
27092 
27093     pShmNode->szRegion = szRegion;
27094 
27095     if( pShmNode->h>=0 ){
27096       /* The requested region is not mapped into this processes address space.
27097       ** Check to see if it has been allocated (i.e. if the wal-index file is
27098       ** large enough to contain the requested region).
27099       */
27100       if( osFstat(pShmNode->h, &sStat) ){
27101         rc = SQLITE_IOERR_SHMSIZE;
27102         goto shmpage_out;
27103       }
27104 
27105       if( sStat.st_size<nByte ){
27106         /* The requested memory region does not exist. If bExtend is set to
27107         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27108         **
27109         ** Alternatively, if bExtend is true, use ftruncate() to allocate
27110         ** the requested memory region.
27111         */
27112         if( !bExtend ) goto shmpage_out;
27113 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27114         if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
27115           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
27116                             pShmNode->zFilename);
27117           goto shmpage_out;
27118         }
27119 #else
27120         if( robust_ftruncate(pShmNode->h, nByte) ){
27121           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
27122                             pShmNode->zFilename);
27123           goto shmpage_out;
27124         }
27125 #endif
27126       }
27127     }
27128 
27129     /* Map the requested memory region into this processes address space. */
27130     apNew = (char **)sqlite3_realloc(
27131         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27132     );
27133     if( !apNew ){
27134       rc = SQLITE_IOERR_NOMEM;
27135       goto shmpage_out;
27136     }
27137     pShmNode->apRegion = apNew;
27138     while(pShmNode->nRegion<=iRegion){
27139       void *pMem;
27140       if( pShmNode->h>=0 ){
27141         pMem = mmap(0, szRegion,
27142             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
27143             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27144         );
27145         if( pMem==MAP_FAILED ){
27146           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27147           goto shmpage_out;
27148         }
27149       }else{
27150         pMem = sqlite3_malloc(szRegion);
27151         if( pMem==0 ){
27152           rc = SQLITE_NOMEM;
27153           goto shmpage_out;
27154         }
27155         memset(pMem, 0, szRegion);
27156       }
27157       pShmNode->apRegion[pShmNode->nRegion] = pMem;
27158       pShmNode->nRegion++;
27159     }
27160   }
27161 
27162 shmpage_out:
27163   if( pShmNode->nRegion>iRegion ){
27164     *pp = pShmNode->apRegion[iRegion];
27165   }else{
27166     *pp = 0;
27167   }
27168   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27169   sqlite3_mutex_leave(pShmNode->mutex);
27170   return rc;
27171 }
27172 
27173 /*
27174 ** Change the lock state for a shared-memory segment.
27175 **
27176 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27177 ** different here than in posix.  In xShmLock(), one can go from unlocked
27178 ** to shared and back or from unlocked to exclusive and back.  But one may
27179 ** not go from shared to exclusive or from exclusive to shared.
27180 */
27181 static int unixShmLock(
27182   sqlite3_file *fd,          /* Database file holding the shared memory */
27183   int ofst,                  /* First lock to acquire or release */
27184   int n,                     /* Number of locks to acquire or release */
27185   int flags                  /* What to do with the lock */
27186 ){
27187   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
27188   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
27189   unixShm *pX;                          /* For looping over all siblings */
27190   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
27191   int rc = SQLITE_OK;                   /* Result code */
27192   u16 mask;                             /* Mask of locks to take or release */
27193 
27194   assert( pShmNode==pDbFd->pInode->pShmNode );
27195   assert( pShmNode->pInode==pDbFd->pInode );
27196   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27197   assert( n>=1 );
27198   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27199        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27200        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27201        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27202   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27203   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27204   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27205 
27206   mask = (1<<(ofst+n)) - (1<<ofst);
27207   assert( n>1 || mask==(1<<ofst) );
27208   sqlite3_mutex_enter(pShmNode->mutex);
27209   if( flags & SQLITE_SHM_UNLOCK ){
27210     u16 allMask = 0; /* Mask of locks held by siblings */
27211 
27212     /* See if any siblings hold this same lock */
27213     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27214       if( pX==p ) continue;
27215       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27216       allMask |= pX->sharedMask;
27217     }
27218 
27219     /* Unlock the system-level locks */
27220     if( (mask & allMask)==0 ){
27221       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27222     }else{
27223       rc = SQLITE_OK;
27224     }
27225 
27226     /* Undo the local locks */
27227     if( rc==SQLITE_OK ){
27228       p->exclMask &= ~mask;
27229       p->sharedMask &= ~mask;
27230     }
27231   }else if( flags & SQLITE_SHM_SHARED ){
27232     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
27233 
27234     /* Find out which shared locks are already held by sibling connections.
27235     ** If any sibling already holds an exclusive lock, go ahead and return
27236     ** SQLITE_BUSY.
27237     */
27238     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27239       if( (pX->exclMask & mask)!=0 ){
27240         rc = SQLITE_BUSY;
27241         break;
27242       }
27243       allShared |= pX->sharedMask;
27244     }
27245 
27246     /* Get shared locks at the system level, if necessary */
27247     if( rc==SQLITE_OK ){
27248       if( (allShared & mask)==0 ){
27249         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27250       }else{
27251         rc = SQLITE_OK;
27252       }
27253     }
27254 
27255     /* Get the local shared locks */
27256     if( rc==SQLITE_OK ){
27257       p->sharedMask |= mask;
27258     }
27259   }else{
27260     /* Make sure no sibling connections hold locks that will block this
27261     ** lock.  If any do, return SQLITE_BUSY right away.
27262     */
27263     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27264       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27265         rc = SQLITE_BUSY;
27266         break;
27267       }
27268     }
27269 
27270     /* Get the exclusive locks at the system level.  Then if successful
27271     ** also mark the local connection as being locked.
27272     */
27273     if( rc==SQLITE_OK ){
27274       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27275       if( rc==SQLITE_OK ){
27276         assert( (p->sharedMask & mask)==0 );
27277         p->exclMask |= mask;
27278       }
27279     }
27280   }
27281   sqlite3_mutex_leave(pShmNode->mutex);
27282   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27283            p->id, getpid(), p->sharedMask, p->exclMask));
27284   return rc;
27285 }
27286 
27287 /*
27288 ** Implement a memory barrier or memory fence on shared memory.
27289 **
27290 ** All loads and stores begun before the barrier must complete before
27291 ** any load or store begun after the barrier.
27292 */
27293 static void unixShmBarrier(
27294   sqlite3_file *fd                /* Database file holding the shared memory */
27295 ){
27296   UNUSED_PARAMETER(fd);
27297   unixEnterMutex();
27298   unixLeaveMutex();
27299 }
27300 
27301 /*
27302 ** Close a connection to shared-memory.  Delete the underlying
27303 ** storage if deleteFlag is true.
27304 **
27305 ** If there is no shared memory associated with the connection then this
27306 ** routine is a harmless no-op.
27307 */
27308 static int unixShmUnmap(
27309   sqlite3_file *fd,               /* The underlying database file */
27310   int deleteFlag                  /* Delete shared-memory if true */
27311 ){
27312   unixShm *p;                     /* The connection to be closed */
27313   unixShmNode *pShmNode;          /* The underlying shared-memory file */
27314   unixShm **pp;                   /* For looping over sibling connections */
27315   unixFile *pDbFd;                /* The underlying database file */
27316 
27317   pDbFd = (unixFile*)fd;
27318   p = pDbFd->pShm;
27319   if( p==0 ) return SQLITE_OK;
27320   pShmNode = p->pShmNode;
27321 
27322   assert( pShmNode==pDbFd->pInode->pShmNode );
27323   assert( pShmNode->pInode==pDbFd->pInode );
27324 
27325   /* Remove connection p from the set of connections associated
27326   ** with pShmNode */
27327   sqlite3_mutex_enter(pShmNode->mutex);
27328   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27329   *pp = p->pNext;
27330 
27331   /* Free the connection p */
27332   sqlite3_free(p);
27333   pDbFd->pShm = 0;
27334   sqlite3_mutex_leave(pShmNode->mutex);
27335 
27336   /* If pShmNode->nRef has reached 0, then close the underlying
27337   ** shared-memory file, too */
27338   unixEnterMutex();
27339   assert( pShmNode->nRef>0 );
27340   pShmNode->nRef--;
27341   if( pShmNode->nRef==0 ){
27342     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27343     unixShmPurge(pDbFd);
27344   }
27345   unixLeaveMutex();
27346 
27347   return SQLITE_OK;
27348 }
27349 
27350 
27351 #else
27352 # define unixShmMap     0
27353 # define unixShmLock    0
27354 # define unixShmBarrier 0
27355 # define unixShmUnmap   0
27356 #endif /* #ifndef SQLITE_OMIT_WAL */
27357 
27358 /*
27359 ** Here ends the implementation of all sqlite3_file methods.
27360 **
27361 ********************** End sqlite3_file Methods *******************************
27362 ******************************************************************************/
27363 
27364 /*
27365 ** This division contains definitions of sqlite3_io_methods objects that
27366 ** implement various file locking strategies.  It also contains definitions
27367 ** of "finder" functions.  A finder-function is used to locate the appropriate
27368 ** sqlite3_io_methods object for a particular database file.  The pAppData
27369 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27370 ** the correct finder-function for that VFS.
27371 **
27372 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
27373 ** object.  The only interesting finder-function is autolockIoFinder, which
27374 ** looks at the filesystem type and tries to guess the best locking
27375 ** strategy from that.
27376 **
27377 ** For finder-funtion F, two objects are created:
27378 **
27379 **    (1) The real finder-function named "FImpt()".
27380 **
27381 **    (2) A constant pointer to this function named just "F".
27382 **
27383 **
27384 ** A pointer to the F pointer is used as the pAppData value for VFS
27385 ** objects.  We have to do this instead of letting pAppData point
27386 ** directly at the finder-function since C90 rules prevent a void*
27387 ** from be cast into a function pointer.
27388 **
27389 **
27390 ** Each instance of this macro generates two objects:
27391 **
27392 **   *  A constant sqlite3_io_methods object call METHOD that has locking
27393 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27394 **
27395 **   *  An I/O method finder function called FINDER that returns a pointer
27396 **      to the METHOD object in the previous bullet.
27397 */
27398 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
27399 static const sqlite3_io_methods METHOD = {                                   \
27400    VERSION,                    /* iVersion */                                \
27401    CLOSE,                      /* xClose */                                  \
27402    unixRead,                   /* xRead */                                   \
27403    unixWrite,                  /* xWrite */                                  \
27404    unixTruncate,               /* xTruncate */                               \
27405    unixSync,                   /* xSync */                                   \
27406    unixFileSize,               /* xFileSize */                               \
27407    LOCK,                       /* xLock */                                   \
27408    UNLOCK,                     /* xUnlock */                                 \
27409    CKLOCK,                     /* xCheckReservedLock */                      \
27410    unixFileControl,            /* xFileControl */                            \
27411    unixSectorSize,             /* xSectorSize */                             \
27412    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
27413    unixShmMap,                 /* xShmMap */                                 \
27414    unixShmLock,                /* xShmLock */                                \
27415    unixShmBarrier,             /* xShmBarrier */                             \
27416    unixShmUnmap                /* xShmUnmap */                               \
27417 };                                                                           \
27418 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
27419   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
27420   return &METHOD;                                                            \
27421 }                                                                            \
27422 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
27423     = FINDER##Impl;
27424 
27425 /*
27426 ** Here are all of the sqlite3_io_methods objects for each of the
27427 ** locking strategies.  Functions that return pointers to these methods
27428 ** are also created.
27429 */
27430 IOMETHODS(
27431   posixIoFinder,            /* Finder function name */
27432   posixIoMethods,           /* sqlite3_io_methods object name */
27433   2,                        /* shared memory is enabled */
27434   unixClose,                /* xClose method */
27435   unixLock,                 /* xLock method */
27436   unixUnlock,               /* xUnlock method */
27437   unixCheckReservedLock     /* xCheckReservedLock method */
27438 )
27439 IOMETHODS(
27440   nolockIoFinder,           /* Finder function name */
27441   nolockIoMethods,          /* sqlite3_io_methods object name */
27442   1,                        /* shared memory is disabled */
27443   nolockClose,              /* xClose method */
27444   nolockLock,               /* xLock method */
27445   nolockUnlock,             /* xUnlock method */
27446   nolockCheckReservedLock   /* xCheckReservedLock method */
27447 )
27448 IOMETHODS(
27449   dotlockIoFinder,          /* Finder function name */
27450   dotlockIoMethods,         /* sqlite3_io_methods object name */
27451   1,                        /* shared memory is disabled */
27452   dotlockClose,             /* xClose method */
27453   dotlockLock,              /* xLock method */
27454   dotlockUnlock,            /* xUnlock method */
27455   dotlockCheckReservedLock  /* xCheckReservedLock method */
27456 )
27457 
27458 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27459 IOMETHODS(
27460   flockIoFinder,            /* Finder function name */
27461   flockIoMethods,           /* sqlite3_io_methods object name */
27462   1,                        /* shared memory is disabled */
27463   flockClose,               /* xClose method */
27464   flockLock,                /* xLock method */
27465   flockUnlock,              /* xUnlock method */
27466   flockCheckReservedLock    /* xCheckReservedLock method */
27467 )
27468 #endif
27469 
27470 #if OS_VXWORKS
27471 IOMETHODS(
27472   semIoFinder,              /* Finder function name */
27473   semIoMethods,             /* sqlite3_io_methods object name */
27474   1,                        /* shared memory is disabled */
27475   semClose,                 /* xClose method */
27476   semLock,                  /* xLock method */
27477   semUnlock,                /* xUnlock method */
27478   semCheckReservedLock      /* xCheckReservedLock method */
27479 )
27480 #endif
27481 
27482 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27483 IOMETHODS(
27484   afpIoFinder,              /* Finder function name */
27485   afpIoMethods,             /* sqlite3_io_methods object name */
27486   1,                        /* shared memory is disabled */
27487   afpClose,                 /* xClose method */
27488   afpLock,                  /* xLock method */
27489   afpUnlock,                /* xUnlock method */
27490   afpCheckReservedLock      /* xCheckReservedLock method */
27491 )
27492 #endif
27493 
27494 /*
27495 ** The proxy locking method is a "super-method" in the sense that it
27496 ** opens secondary file descriptors for the conch and lock files and
27497 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
27498 ** secondary files.  For this reason, the division that implements
27499 ** proxy locking is located much further down in the file.  But we need
27500 ** to go ahead and define the sqlite3_io_methods and finder function
27501 ** for proxy locking here.  So we forward declare the I/O methods.
27502 */
27503 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27504 static int proxyClose(sqlite3_file*);
27505 static int proxyLock(sqlite3_file*, int);
27506 static int proxyUnlock(sqlite3_file*, int);
27507 static int proxyCheckReservedLock(sqlite3_file*, int*);
27508 IOMETHODS(
27509   proxyIoFinder,            /* Finder function name */
27510   proxyIoMethods,           /* sqlite3_io_methods object name */
27511   1,                        /* shared memory is disabled */
27512   proxyClose,               /* xClose method */
27513   proxyLock,                /* xLock method */
27514   proxyUnlock,              /* xUnlock method */
27515   proxyCheckReservedLock    /* xCheckReservedLock method */
27516 )
27517 #endif
27518 
27519 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
27520 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27521 IOMETHODS(
27522   nfsIoFinder,               /* Finder function name */
27523   nfsIoMethods,              /* sqlite3_io_methods object name */
27524   1,                         /* shared memory is disabled */
27525   unixClose,                 /* xClose method */
27526   unixLock,                  /* xLock method */
27527   nfsUnlock,                 /* xUnlock method */
27528   unixCheckReservedLock      /* xCheckReservedLock method */
27529 )
27530 #endif
27531 
27532 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27533 /*
27534 ** This "finder" function attempts to determine the best locking strategy
27535 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27536 ** object that implements that strategy.
27537 **
27538 ** This is for MacOSX only.
27539 */
27540 static const sqlite3_io_methods *autolockIoFinderImpl(
27541   const char *filePath,    /* name of the database file */
27542   unixFile *pNew           /* open file object for the database file */
27543 ){
27544   static const struct Mapping {
27545     const char *zFilesystem;              /* Filesystem type name */
27546     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
27547   } aMap[] = {
27548     { "hfs",    &posixIoMethods },
27549     { "ufs",    &posixIoMethods },
27550     { "afpfs",  &afpIoMethods },
27551     { "smbfs",  &afpIoMethods },
27552     { "webdav", &nolockIoMethods },
27553     { 0, 0 }
27554   };
27555   int i;
27556   struct statfs fsInfo;
27557   struct flock lockInfo;
27558 
27559   if( !filePath ){
27560     /* If filePath==NULL that means we are dealing with a transient file
27561     ** that does not need to be locked. */
27562     return &nolockIoMethods;
27563   }
27564   if( statfs(filePath, &fsInfo) != -1 ){
27565     if( fsInfo.f_flags & MNT_RDONLY ){
27566       return &nolockIoMethods;
27567     }
27568     for(i=0; aMap[i].zFilesystem; i++){
27569       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
27570         return aMap[i].pMethods;
27571       }
27572     }
27573   }
27574 
27575   /* Default case. Handles, amongst others, "nfs".
27576   ** Test byte-range lock using fcntl(). If the call succeeds,
27577   ** assume that the file-system supports POSIX style locks.
27578   */
27579   lockInfo.l_len = 1;
27580   lockInfo.l_start = 0;
27581   lockInfo.l_whence = SEEK_SET;
27582   lockInfo.l_type = F_RDLCK;
27583   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27584     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
27585       return &nfsIoMethods;
27586     } else {
27587       return &posixIoMethods;
27588     }
27589   }else{
27590     return &dotlockIoMethods;
27591   }
27592 }
27593 static const sqlite3_io_methods
27594   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27595 
27596 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27597 
27598 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
27599 /*
27600 ** This "finder" function attempts to determine the best locking strategy
27601 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27602 ** object that implements that strategy.
27603 **
27604 ** This is for VXWorks only.
27605 */
27606 static const sqlite3_io_methods *autolockIoFinderImpl(
27607   const char *filePath,    /* name of the database file */
27608   unixFile *pNew           /* the open file object */
27609 ){
27610   struct flock lockInfo;
27611 
27612   if( !filePath ){
27613     /* If filePath==NULL that means we are dealing with a transient file
27614     ** that does not need to be locked. */
27615     return &nolockIoMethods;
27616   }
27617 
27618   /* Test if fcntl() is supported and use POSIX style locks.
27619   ** Otherwise fall back to the named semaphore method.
27620   */
27621   lockInfo.l_len = 1;
27622   lockInfo.l_start = 0;
27623   lockInfo.l_whence = SEEK_SET;
27624   lockInfo.l_type = F_RDLCK;
27625   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27626     return &posixIoMethods;
27627   }else{
27628     return &semIoMethods;
27629   }
27630 }
27631 static const sqlite3_io_methods
27632   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27633 
27634 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
27635 
27636 /*
27637 ** An abstract type for a pointer to a IO method finder function:
27638 */
27639 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
27640 
27641 
27642 /****************************************************************************
27643 **************************** sqlite3_vfs methods ****************************
27644 **
27645 ** This division contains the implementation of methods on the
27646 ** sqlite3_vfs object.
27647 */
27648 
27649 /*
27650 ** Initialize the contents of the unixFile structure pointed to by pId.
27651 */
27652 static int fillInUnixFile(
27653   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
27654   int h,                  /* Open file descriptor of file being opened */
27655   sqlite3_file *pId,      /* Write to the unixFile structure here */
27656   const char *zFilename,  /* Name of the file being opened */
27657   int ctrlFlags           /* Zero or more UNIXFILE_* values */
27658 ){
27659   const sqlite3_io_methods *pLockingStyle;
27660   unixFile *pNew = (unixFile *)pId;
27661   int rc = SQLITE_OK;
27662 
27663   assert( pNew->pInode==NULL );
27664 
27665   /* Usually the path zFilename should not be a relative pathname. The
27666   ** exception is when opening the proxy "conch" file in builds that
27667   ** include the special Apple locking styles.
27668   */
27669 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27670   assert( zFilename==0 || zFilename[0]=='/'
27671     || pVfs->pAppData==(void*)&autolockIoFinder );
27672 #else
27673   assert( zFilename==0 || zFilename[0]=='/' );
27674 #endif
27675 
27676   /* No locking occurs in temporary files */
27677   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
27678 
27679   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
27680   pNew->h = h;
27681   pNew->pVfs = pVfs;
27682   pNew->zPath = zFilename;
27683   pNew->ctrlFlags = (u8)ctrlFlags;
27684   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
27685                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
27686     pNew->ctrlFlags |= UNIXFILE_PSOW;
27687   }
27688   if( strcmp(pVfs->zName,"unix-excl")==0 ){
27689     pNew->ctrlFlags |= UNIXFILE_EXCL;
27690   }
27691 
27692 #if OS_VXWORKS
27693   pNew->pId = vxworksFindFileId(zFilename);
27694   if( pNew->pId==0 ){
27695     ctrlFlags |= UNIXFILE_NOLOCK;
27696     rc = SQLITE_NOMEM;
27697   }
27698 #endif
27699 
27700   if( ctrlFlags & UNIXFILE_NOLOCK ){
27701     pLockingStyle = &nolockIoMethods;
27702   }else{
27703     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
27704 #if SQLITE_ENABLE_LOCKING_STYLE
27705     /* Cache zFilename in the locking context (AFP and dotlock override) for
27706     ** proxyLock activation is possible (remote proxy is based on db name)
27707     ** zFilename remains valid until file is closed, to support */
27708     pNew->lockingContext = (void*)zFilename;
27709 #endif
27710   }
27711 
27712   if( pLockingStyle == &posixIoMethods
27713 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27714     || pLockingStyle == &nfsIoMethods
27715 #endif
27716   ){
27717     unixEnterMutex();
27718     rc = findInodeInfo(pNew, &pNew->pInode);
27719     if( rc!=SQLITE_OK ){
27720       /* If an error occurred in findInodeInfo(), close the file descriptor
27721       ** immediately, before releasing the mutex. findInodeInfo() may fail
27722       ** in two scenarios:
27723       **
27724       **   (a) A call to fstat() failed.
27725       **   (b) A malloc failed.
27726       **
27727       ** Scenario (b) may only occur if the process is holding no other
27728       ** file descriptors open on the same file. If there were other file
27729       ** descriptors on this file, then no malloc would be required by
27730       ** findInodeInfo(). If this is the case, it is quite safe to close
27731       ** handle h - as it is guaranteed that no posix locks will be released
27732       ** by doing so.
27733       **
27734       ** If scenario (a) caused the error then things are not so safe. The
27735       ** implicit assumption here is that if fstat() fails, things are in
27736       ** such bad shape that dropping a lock or two doesn't matter much.
27737       */
27738       robust_close(pNew, h, __LINE__);
27739       h = -1;
27740     }
27741     unixLeaveMutex();
27742   }
27743 
27744 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27745   else if( pLockingStyle == &afpIoMethods ){
27746     /* AFP locking uses the file path so it needs to be included in
27747     ** the afpLockingContext.
27748     */
27749     afpLockingContext *pCtx;
27750     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27751     if( pCtx==0 ){
27752       rc = SQLITE_NOMEM;
27753     }else{
27754       /* NB: zFilename exists and remains valid until the file is closed
27755       ** according to requirement F11141.  So we do not need to make a
27756       ** copy of the filename. */
27757       pCtx->dbPath = zFilename;
27758       pCtx->reserved = 0;
27759       srandomdev();
27760       unixEnterMutex();
27761       rc = findInodeInfo(pNew, &pNew->pInode);
27762       if( rc!=SQLITE_OK ){
27763         sqlite3_free(pNew->lockingContext);
27764         robust_close(pNew, h, __LINE__);
27765         h = -1;
27766       }
27767       unixLeaveMutex();
27768     }
27769   }
27770 #endif
27771 
27772   else if( pLockingStyle == &dotlockIoMethods ){
27773     /* Dotfile locking uses the file path so it needs to be included in
27774     ** the dotlockLockingContext
27775     */
27776     char *zLockFile;
27777     int nFilename;
27778     assert( zFilename!=0 );
27779     nFilename = (int)strlen(zFilename) + 6;
27780     zLockFile = (char *)sqlite3_malloc(nFilename);
27781     if( zLockFile==0 ){
27782       rc = SQLITE_NOMEM;
27783     }else{
27784       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27785     }
27786     pNew->lockingContext = zLockFile;
27787   }
27788 
27789 #if OS_VXWORKS
27790   else if( pLockingStyle == &semIoMethods ){
27791     /* Named semaphore locking uses the file path so it needs to be
27792     ** included in the semLockingContext
27793     */
27794     unixEnterMutex();
27795     rc = findInodeInfo(pNew, &pNew->pInode);
27796     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27797       char *zSemName = pNew->pInode->aSemName;
27798       int n;
27799       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27800                        pNew->pId->zCanonicalName);
27801       for( n=1; zSemName[n]; n++ )
27802         if( zSemName[n]=='/' ) zSemName[n] = '_';
27803       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27804       if( pNew->pInode->pSem == SEM_FAILED ){
27805         rc = SQLITE_NOMEM;
27806         pNew->pInode->aSemName[0] = '\0';
27807       }
27808     }
27809     unixLeaveMutex();
27810   }
27811 #endif
27812 
27813   pNew->lastErrno = 0;
27814 #if OS_VXWORKS
27815   if( rc!=SQLITE_OK ){
27816     if( h>=0 ) robust_close(pNew, h, __LINE__);
27817     h = -1;
27818     osUnlink(zFilename);
27819     isDelete = 0;
27820   }
27821   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
27822 #endif
27823   if( rc!=SQLITE_OK ){
27824     if( h>=0 ) robust_close(pNew, h, __LINE__);
27825   }else{
27826     pNew->pMethod = pLockingStyle;
27827     OpenCounter(+1);
27828   }
27829   return rc;
27830 }
27831 
27832 /*
27833 ** Return the name of a directory in which to put temporary files.
27834 ** If no suitable temporary file directory can be found, return NULL.
27835 */
27836 static const char *unixTempFileDir(void){
27837   static const char *azDirs[] = {
27838      0,
27839      0,
27840      "/var/tmp",
27841      "/usr/tmp",
27842      "/tmp",
27843      0        /* List terminator */
27844   };
27845   unsigned int i;
27846   struct stat buf;
27847   const char *zDir = 0;
27848 
27849   azDirs[0] = sqlite3_temp_directory;
27850   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27851   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27852     if( zDir==0 ) continue;
27853     if( osStat(zDir, &buf) ) continue;
27854     if( !S_ISDIR(buf.st_mode) ) continue;
27855     if( osAccess(zDir, 07) ) continue;
27856     break;
27857   }
27858   return zDir;
27859 }
27860 
27861 /*
27862 ** Create a temporary file name in zBuf.  zBuf must be allocated
27863 ** by the calling process and must be big enough to hold at least
27864 ** pVfs->mxPathname bytes.
27865 */
27866 static int unixGetTempname(int nBuf, char *zBuf){
27867   static const unsigned char zChars[] =
27868     "abcdefghijklmnopqrstuvwxyz"
27869     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27870     "0123456789";
27871   unsigned int i, j;
27872   const char *zDir;
27873 
27874   /* It's odd to simulate an io-error here, but really this is just
27875   ** using the io-error infrastructure to test that SQLite handles this
27876   ** function failing.
27877   */
27878   SimulateIOError( return SQLITE_IOERR );
27879 
27880   zDir = unixTempFileDir();
27881   if( zDir==0 ) zDir = ".";
27882 
27883   /* Check that the output buffer is large enough for the temporary file
27884   ** name. If it is not, return SQLITE_ERROR.
27885   */
27886   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
27887     return SQLITE_ERROR;
27888   }
27889 
27890   do{
27891     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27892     j = (int)strlen(zBuf);
27893     sqlite3_randomness(15, &zBuf[j]);
27894     for(i=0; i<15; i++, j++){
27895       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27896     }
27897     zBuf[j] = 0;
27898     zBuf[j+1] = 0;
27899   }while( osAccess(zBuf,0)==0 );
27900   return SQLITE_OK;
27901 }
27902 
27903 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27904 /*
27905 ** Routine to transform a unixFile into a proxy-locking unixFile.
27906 ** Implementation in the proxy-lock division, but used by unixOpen()
27907 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27908 */
27909 static int proxyTransformUnixFile(unixFile*, const char*);
27910 #endif
27911 
27912 /*
27913 ** Search for an unused file descriptor that was opened on the database
27914 ** file (not a journal or master-journal file) identified by pathname
27915 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27916 ** argument to this function.
27917 **
27918 ** Such a file descriptor may exist if a database connection was closed
27919 ** but the associated file descriptor could not be closed because some
27920 ** other file descriptor open on the same file is holding a file-lock.
27921 ** Refer to comments in the unixClose() function and the lengthy comment
27922 ** describing "Posix Advisory Locking" at the start of this file for
27923 ** further details. Also, ticket #4018.
27924 **
27925 ** If a suitable file descriptor is found, then it is returned. If no
27926 ** such file descriptor is located, -1 is returned.
27927 */
27928 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27929   UnixUnusedFd *pUnused = 0;
27930 
27931   /* Do not search for an unused file descriptor on vxworks. Not because
27932   ** vxworks would not benefit from the change (it might, we're not sure),
27933   ** but because no way to test it is currently available. It is better
27934   ** not to risk breaking vxworks support for the sake of such an obscure
27935   ** feature.  */
27936 #if !OS_VXWORKS
27937   struct stat sStat;                   /* Results of stat() call */
27938 
27939   /* A stat() call may fail for various reasons. If this happens, it is
27940   ** almost certain that an open() call on the same path will also fail.
27941   ** For this reason, if an error occurs in the stat() call here, it is
27942   ** ignored and -1 is returned. The caller will try to open a new file
27943   ** descriptor on the same path, fail, and return an error to SQLite.
27944   **
27945   ** Even if a subsequent open() call does succeed, the consequences of
27946   ** not searching for a resusable file descriptor are not dire.  */
27947   if( 0==osStat(zPath, &sStat) ){
27948     unixInodeInfo *pInode;
27949 
27950     unixEnterMutex();
27951     pInode = inodeList;
27952     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27953                      || pInode->fileId.ino!=sStat.st_ino) ){
27954        pInode = pInode->pNext;
27955     }
27956     if( pInode ){
27957       UnixUnusedFd **pp;
27958       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27959       pUnused = *pp;
27960       if( pUnused ){
27961         *pp = pUnused->pNext;
27962       }
27963     }
27964     unixLeaveMutex();
27965   }
27966 #endif    /* if !OS_VXWORKS */
27967   return pUnused;
27968 }
27969 
27970 /*
27971 ** This function is called by unixOpen() to determine the unix permissions
27972 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27973 ** and a value suitable for passing as the third argument to open(2) is
27974 ** written to *pMode. If an IO error occurs, an SQLite error code is
27975 ** returned and the value of *pMode is not modified.
27976 **
27977 ** In most cases cases, this routine sets *pMode to 0, which will become
27978 ** an indication to robust_open() to create the file using
27979 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
27980 ** But if the file being opened is a WAL or regular journal file, then
27981 ** this function queries the file-system for the permissions on the
27982 ** corresponding database file and sets *pMode to this value. Whenever
27983 ** possible, WAL and journal files are created using the same permissions
27984 ** as the associated database file.
27985 **
27986 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
27987 ** original filename is unavailable.  But 8_3_NAMES is only used for
27988 ** FAT filesystems and permissions do not matter there, so just use
27989 ** the default permissions.
27990 */
27991 static int findCreateFileMode(
27992   const char *zPath,              /* Path of file (possibly) being created */
27993   int flags,                      /* Flags passed as 4th argument to xOpen() */
27994   mode_t *pMode,                  /* OUT: Permissions to open file with */
27995   uid_t *pUid,                    /* OUT: uid to set on the file */
27996   gid_t *pGid                     /* OUT: gid to set on the file */
27997 ){
27998   int rc = SQLITE_OK;             /* Return Code */
27999   *pMode = 0;
28000   *pUid = 0;
28001   *pGid = 0;
28002   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28003     char zDb[MAX_PATHNAME+1];     /* Database file path */
28004     int nDb;                      /* Number of valid bytes in zDb */
28005     struct stat sStat;            /* Output of stat() on database file */
28006 
28007     /* zPath is a path to a WAL or journal file. The following block derives
28008     ** the path to the associated database file from zPath. This block handles
28009     ** the following naming conventions:
28010     **
28011     **   "<path to db>-journal"
28012     **   "<path to db>-wal"
28013     **   "<path to db>-journalNN"
28014     **   "<path to db>-walNN"
28015     **
28016     ** where NN is a decimal number. The NN naming schemes are
28017     ** used by the test_multiplex.c module.
28018     */
28019     nDb = sqlite3Strlen30(zPath) - 1;
28020 #ifdef SQLITE_ENABLE_8_3_NAMES
28021     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
28022     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
28023 #else
28024     while( zPath[nDb]!='-' ){
28025       assert( nDb>0 );
28026       assert( zPath[nDb]!='\n' );
28027       nDb--;
28028     }
28029 #endif
28030     memcpy(zDb, zPath, nDb);
28031     zDb[nDb] = '\0';
28032 
28033     if( 0==osStat(zDb, &sStat) ){
28034       *pMode = sStat.st_mode & 0777;
28035       *pUid = sStat.st_uid;
28036       *pGid = sStat.st_gid;
28037     }else{
28038       rc = SQLITE_IOERR_FSTAT;
28039     }
28040   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28041     *pMode = 0600;
28042   }
28043   return rc;
28044 }
28045 
28046 /*
28047 ** Open the file zPath.
28048 **
28049 ** Previously, the SQLite OS layer used three functions in place of this
28050 ** one:
28051 **
28052 **     sqlite3OsOpenReadWrite();
28053 **     sqlite3OsOpenReadOnly();
28054 **     sqlite3OsOpenExclusive();
28055 **
28056 ** These calls correspond to the following combinations of flags:
28057 **
28058 **     ReadWrite() ->     (READWRITE | CREATE)
28059 **     ReadOnly()  ->     (READONLY)
28060 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28061 **
28062 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28063 ** true, the file was configured to be automatically deleted when the
28064 ** file handle closed. To achieve the same effect using this new
28065 ** interface, add the DELETEONCLOSE flag to those specified above for
28066 ** OpenExclusive().
28067 */
28068 static int unixOpen(
28069   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28070   const char *zPath,           /* Pathname of file to be opened */
28071   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28072   int flags,                   /* Input flags to control the opening */
28073   int *pOutFlags               /* Output flags returned to SQLite core */
28074 ){
28075   unixFile *p = (unixFile *)pFile;
28076   int fd = -1;                   /* File descriptor returned by open() */
28077   int openFlags = 0;             /* Flags to pass to open() */
28078   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28079   int noLock;                    /* True to omit locking primitives */
28080   int rc = SQLITE_OK;            /* Function Return Code */
28081   int ctrlFlags = 0;             /* UNIXFILE_* flags */
28082 
28083   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28084   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28085   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28086   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28087   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28088 #if SQLITE_ENABLE_LOCKING_STYLE
28089   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
28090 #endif
28091 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28092   struct statfs fsInfo;
28093 #endif
28094 
28095   /* If creating a master or main-file journal, this function will open
28096   ** a file-descriptor on the directory too. The first time unixSync()
28097   ** is called the directory file descriptor will be fsync()ed and close()d.
28098   */
28099   int syncDir = (isCreate && (
28100         eType==SQLITE_OPEN_MASTER_JOURNAL
28101      || eType==SQLITE_OPEN_MAIN_JOURNAL
28102      || eType==SQLITE_OPEN_WAL
28103   ));
28104 
28105   /* If argument zPath is a NULL pointer, this function is required to open
28106   ** a temporary file. Use this buffer to store the file name in.
28107   */
28108   char zTmpname[MAX_PATHNAME+2];
28109   const char *zName = zPath;
28110 
28111   /* Check the following statements are true:
28112   **
28113   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
28114   **   (b) if CREATE is set, then READWRITE must also be set, and
28115   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
28116   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
28117   */
28118   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28119   assert(isCreate==0 || isReadWrite);
28120   assert(isExclusive==0 || isCreate);
28121   assert(isDelete==0 || isCreate);
28122 
28123   /* The main DB, main journal, WAL file and master journal are never
28124   ** automatically deleted. Nor are they ever temporary files.  */
28125   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28126   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28127   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28128   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28129 
28130   /* Assert that the upper layer has set one of the "file-type" flags. */
28131   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
28132        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
28133        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
28134        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28135   );
28136 
28137   memset(p, 0, sizeof(unixFile));
28138 
28139   if( eType==SQLITE_OPEN_MAIN_DB ){
28140     UnixUnusedFd *pUnused;
28141     pUnused = findReusableFd(zName, flags);
28142     if( pUnused ){
28143       fd = pUnused->fd;
28144     }else{
28145       pUnused = sqlite3_malloc(sizeof(*pUnused));
28146       if( !pUnused ){
28147         return SQLITE_NOMEM;
28148       }
28149     }
28150     p->pUnused = pUnused;
28151 
28152     /* Database filenames are double-zero terminated if they are not
28153     ** URIs with parameters.  Hence, they can always be passed into
28154     ** sqlite3_uri_parameter(). */
28155     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28156 
28157   }else if( !zName ){
28158     /* If zName is NULL, the upper layer is requesting a temp file. */
28159     assert(isDelete && !syncDir);
28160     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28161     if( rc!=SQLITE_OK ){
28162       return rc;
28163     }
28164     zName = zTmpname;
28165 
28166     /* Generated temporary filenames are always double-zero terminated
28167     ** for use by sqlite3_uri_parameter(). */
28168     assert( zName[strlen(zName)+1]==0 );
28169   }
28170 
28171   /* Determine the value of the flags parameter passed to POSIX function
28172   ** open(). These must be calculated even if open() is not called, as
28173   ** they may be stored as part of the file handle and used by the
28174   ** 'conch file' locking functions later on.  */
28175   if( isReadonly )  openFlags |= O_RDONLY;
28176   if( isReadWrite ) openFlags |= O_RDWR;
28177   if( isCreate )    openFlags |= O_CREAT;
28178   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28179   openFlags |= (O_LARGEFILE|O_BINARY);
28180 
28181   if( fd<0 ){
28182     mode_t openMode;              /* Permissions to create file with */
28183     uid_t uid;                    /* Userid for the file */
28184     gid_t gid;                    /* Groupid for the file */
28185     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28186     if( rc!=SQLITE_OK ){
28187       assert( !p->pUnused );
28188       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
28189       return rc;
28190     }
28191     fd = robust_open(zName, openFlags, openMode);
28192     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
28193     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
28194       /* Failed to open the file for read/write access. Try read-only. */
28195       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28196       openFlags &= ~(O_RDWR|O_CREAT);
28197       flags |= SQLITE_OPEN_READONLY;
28198       openFlags |= O_RDONLY;
28199       isReadonly = 1;
28200       fd = robust_open(zName, openFlags, openMode);
28201     }
28202     if( fd<0 ){
28203       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
28204       goto open_finished;
28205     }
28206 
28207     /* If this process is running as root and if creating a new rollback
28208     ** journal or WAL file, set the ownership of the journal or WAL to be
28209     ** the same as the original database.
28210     */
28211     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28212       osFchown(fd, uid, gid);
28213     }
28214   }
28215   assert( fd>=0 );
28216   if( pOutFlags ){
28217     *pOutFlags = flags;
28218   }
28219 
28220   if( p->pUnused ){
28221     p->pUnused->fd = fd;
28222     p->pUnused->flags = flags;
28223   }
28224 
28225   if( isDelete ){
28226 #if OS_VXWORKS
28227     zPath = zName;
28228 #else
28229     osUnlink(zName);
28230 #endif
28231   }
28232 #if SQLITE_ENABLE_LOCKING_STYLE
28233   else{
28234     p->openFlags = openFlags;
28235   }
28236 #endif
28237 
28238   noLock = eType!=SQLITE_OPEN_MAIN_DB;
28239 
28240 
28241 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28242   if( fstatfs(fd, &fsInfo) == -1 ){
28243     ((unixFile*)pFile)->lastErrno = errno;
28244     robust_close(p, fd, __LINE__);
28245     return SQLITE_IOERR_ACCESS;
28246   }
28247   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
28248     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
28249   }
28250 #endif
28251 
28252   /* Set up appropriate ctrlFlags */
28253   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
28254   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
28255   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
28256   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
28257   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
28258 
28259 #if SQLITE_ENABLE_LOCKING_STYLE
28260 #if SQLITE_PREFER_PROXY_LOCKING
28261   isAutoProxy = 1;
28262 #endif
28263   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
28264     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
28265     int useProxy = 0;
28266 
28267     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
28268     ** never use proxy, NULL means use proxy for non-local files only.  */
28269     if( envforce!=NULL ){
28270       useProxy = atoi(envforce)>0;
28271     }else{
28272       if( statfs(zPath, &fsInfo) == -1 ){
28273         /* In theory, the close(fd) call is sub-optimal. If the file opened
28274         ** with fd is a database file, and there are other connections open
28275         ** on that file that are currently holding advisory locks on it,
28276         ** then the call to close() will cancel those locks. In practice,
28277         ** we're assuming that statfs() doesn't fail very often. At least
28278         ** not while other file descriptors opened by the same process on
28279         ** the same file are working.  */
28280         p->lastErrno = errno;
28281         robust_close(p, fd, __LINE__);
28282         rc = SQLITE_IOERR_ACCESS;
28283         goto open_finished;
28284       }
28285       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28286     }
28287     if( useProxy ){
28288       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28289       if( rc==SQLITE_OK ){
28290         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28291         if( rc!=SQLITE_OK ){
28292           /* Use unixClose to clean up the resources added in fillInUnixFile
28293           ** and clear all the structure's references.  Specifically,
28294           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
28295           */
28296           unixClose(pFile);
28297           return rc;
28298         }
28299       }
28300       goto open_finished;
28301     }
28302   }
28303 #endif
28304 
28305   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28306 
28307 open_finished:
28308   if( rc!=SQLITE_OK ){
28309     sqlite3_free(p->pUnused);
28310   }
28311   return rc;
28312 }
28313 
28314 
28315 /*
28316 ** Delete the file at zPath. If the dirSync argument is true, fsync()
28317 ** the directory after deleting the file.
28318 */
28319 static int unixDelete(
28320   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
28321   const char *zPath,        /* Name of file to be deleted */
28322   int dirSync               /* If true, fsync() directory after deleting file */
28323 ){
28324   int rc = SQLITE_OK;
28325   UNUSED_PARAMETER(NotUsed);
28326   SimulateIOError(return SQLITE_IOERR_DELETE);
28327   if( osUnlink(zPath)==(-1) ){
28328     if( errno==ENOENT ){
28329       rc = SQLITE_IOERR_DELETE_NOENT;
28330     }else{
28331       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28332     }
28333     return rc;
28334   }
28335 #ifndef SQLITE_DISABLE_DIRSYNC
28336   if( (dirSync & 1)!=0 ){
28337     int fd;
28338     rc = osOpenDirectory(zPath, &fd);
28339     if( rc==SQLITE_OK ){
28340 #if OS_VXWORKS
28341       if( fsync(fd)==-1 )
28342 #else
28343       if( fsync(fd) )
28344 #endif
28345       {
28346         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28347       }
28348       robust_close(0, fd, __LINE__);
28349     }else if( rc==SQLITE_CANTOPEN ){
28350       rc = SQLITE_OK;
28351     }
28352   }
28353 #endif
28354   return rc;
28355 }
28356 
28357 /*
28358 ** Test the existence of or access permissions of file zPath. The
28359 ** test performed depends on the value of flags:
28360 **
28361 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28362 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28363 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28364 **
28365 ** Otherwise return 0.
28366 */
28367 static int unixAccess(
28368   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
28369   const char *zPath,      /* Path of the file to examine */
28370   int flags,              /* What do we want to learn about the zPath file? */
28371   int *pResOut            /* Write result boolean here */
28372 ){
28373   int amode = 0;
28374   UNUSED_PARAMETER(NotUsed);
28375   SimulateIOError( return SQLITE_IOERR_ACCESS; );
28376   switch( flags ){
28377     case SQLITE_ACCESS_EXISTS:
28378       amode = F_OK;
28379       break;
28380     case SQLITE_ACCESS_READWRITE:
28381       amode = W_OK|R_OK;
28382       break;
28383     case SQLITE_ACCESS_READ:
28384       amode = R_OK;
28385       break;
28386 
28387     default:
28388       assert(!"Invalid flags argument");
28389   }
28390   *pResOut = (osAccess(zPath, amode)==0);
28391   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28392     struct stat buf;
28393     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28394       *pResOut = 0;
28395     }
28396   }
28397   return SQLITE_OK;
28398 }
28399 
28400 
28401 /*
28402 ** Turn a relative pathname into a full pathname. The relative path
28403 ** is stored as a nul-terminated string in the buffer pointed to by
28404 ** zPath.
28405 **
28406 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
28407 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
28408 ** this buffer before returning.
28409 */
28410 static int unixFullPathname(
28411   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28412   const char *zPath,            /* Possibly relative input path */
28413   int nOut,                     /* Size of output buffer in bytes */
28414   char *zOut                    /* Output buffer */
28415 ){
28416 
28417   /* It's odd to simulate an io-error here, but really this is just
28418   ** using the io-error infrastructure to test that SQLite handles this
28419   ** function failing. This function could fail if, for example, the
28420   ** current working directory has been unlinked.
28421   */
28422   SimulateIOError( return SQLITE_ERROR );
28423 
28424   assert( pVfs->mxPathname==MAX_PATHNAME );
28425   UNUSED_PARAMETER(pVfs);
28426 
28427   zOut[nOut-1] = '\0';
28428   if( zPath[0]=='/' ){
28429     sqlite3_snprintf(nOut, zOut, "%s", zPath);
28430   }else{
28431     int nCwd;
28432     if( osGetcwd(zOut, nOut-1)==0 ){
28433       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
28434     }
28435     nCwd = (int)strlen(zOut);
28436     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
28437   }
28438   return SQLITE_OK;
28439 }
28440 
28441 
28442 #ifndef SQLITE_OMIT_LOAD_EXTENSION
28443 /*
28444 ** Interfaces for opening a shared library, finding entry points
28445 ** within the shared library, and closing the shared library.
28446 */
28447 #include <dlfcn.h>
28448 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
28449   UNUSED_PARAMETER(NotUsed);
28450   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
28451 }
28452 
28453 /*
28454 ** SQLite calls this function immediately after a call to unixDlSym() or
28455 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
28456 ** message is available, it is written to zBufOut. If no error message
28457 ** is available, zBufOut is left unmodified and SQLite uses a default
28458 ** error message.
28459 */
28460 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
28461   const char *zErr;
28462   UNUSED_PARAMETER(NotUsed);
28463   unixEnterMutex();
28464   zErr = dlerror();
28465   if( zErr ){
28466     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
28467   }
28468   unixLeaveMutex();
28469 }
28470 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
28471   /*
28472   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
28473   ** cast into a pointer to a function.  And yet the library dlsym() routine
28474   ** returns a void* which is really a pointer to a function.  So how do we
28475   ** use dlsym() with -pedantic-errors?
28476   **
28477   ** Variable x below is defined to be a pointer to a function taking
28478   ** parameters void* and const char* and returning a pointer to a function.
28479   ** We initialize x by assigning it a pointer to the dlsym() function.
28480   ** (That assignment requires a cast.)  Then we call the function that
28481   ** x points to.
28482   **
28483   ** This work-around is unlikely to work correctly on any system where
28484   ** you really cannot cast a function pointer into void*.  But then, on the
28485   ** other hand, dlsym() will not work on such a system either, so we have
28486   ** not really lost anything.
28487   */
28488   void (*(*x)(void*,const char*))(void);
28489   UNUSED_PARAMETER(NotUsed);
28490   x = (void(*(*)(void*,const char*))(void))dlsym;
28491   return (*x)(p, zSym);
28492 }
28493 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
28494   UNUSED_PARAMETER(NotUsed);
28495   dlclose(pHandle);
28496 }
28497 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28498   #define unixDlOpen  0
28499   #define unixDlError 0
28500   #define unixDlSym   0
28501   #define unixDlClose 0
28502 #endif
28503 
28504 /*
28505 ** Write nBuf bytes of random data to the supplied buffer zBuf.
28506 */
28507 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
28508   UNUSED_PARAMETER(NotUsed);
28509   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
28510 
28511   /* We have to initialize zBuf to prevent valgrind from reporting
28512   ** errors.  The reports issued by valgrind are incorrect - we would
28513   ** prefer that the randomness be increased by making use of the
28514   ** uninitialized space in zBuf - but valgrind errors tend to worry
28515   ** some users.  Rather than argue, it seems easier just to initialize
28516   ** the whole array and silence valgrind, even if that means less randomness
28517   ** in the random seed.
28518   **
28519   ** When testing, initializing zBuf[] to zero is all we do.  That means
28520   ** that we always use the same random number sequence.  This makes the
28521   ** tests repeatable.
28522   */
28523   memset(zBuf, 0, nBuf);
28524 #if !defined(SQLITE_TEST)
28525   {
28526     int pid, fd, got;
28527     fd = robust_open("/dev/urandom", O_RDONLY, 0);
28528     if( fd<0 ){
28529       time_t t;
28530       time(&t);
28531       memcpy(zBuf, &t, sizeof(t));
28532       pid = getpid();
28533       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
28534       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
28535       nBuf = sizeof(t) + sizeof(pid);
28536     }else{
28537       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
28538       robust_close(0, fd, __LINE__);
28539     }
28540   }
28541 #endif
28542   return nBuf;
28543 }
28544 
28545 
28546 /*
28547 ** Sleep for a little while.  Return the amount of time slept.
28548 ** The argument is the number of microseconds we want to sleep.
28549 ** The return value is the number of microseconds of sleep actually
28550 ** requested from the underlying operating system, a number which
28551 ** might be greater than or equal to the argument, but not less
28552 ** than the argument.
28553 */
28554 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
28555 #if OS_VXWORKS
28556   struct timespec sp;
28557 
28558   sp.tv_sec = microseconds / 1000000;
28559   sp.tv_nsec = (microseconds % 1000000) * 1000;
28560   nanosleep(&sp, NULL);
28561   UNUSED_PARAMETER(NotUsed);
28562   return microseconds;
28563 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
28564   usleep(microseconds);
28565   UNUSED_PARAMETER(NotUsed);
28566   return microseconds;
28567 #else
28568   int seconds = (microseconds+999999)/1000000;
28569   sleep(seconds);
28570   UNUSED_PARAMETER(NotUsed);
28571   return seconds*1000000;
28572 #endif
28573 }
28574 
28575 /*
28576 ** The following variable, if set to a non-zero value, is interpreted as
28577 ** the number of seconds since 1970 and is used to set the result of
28578 ** sqlite3OsCurrentTime() during testing.
28579 */
28580 #ifdef SQLITE_TEST
28581 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
28582 #endif
28583 
28584 /*
28585 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
28586 ** the current time and date as a Julian Day number times 86_400_000.  In
28587 ** other words, write into *piNow the number of milliseconds since the Julian
28588 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
28589 ** proleptic Gregorian calendar.
28590 **
28591 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
28592 ** cannot be found.
28593 */
28594 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
28595   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
28596   int rc = SQLITE_OK;
28597 #if defined(NO_GETTOD)
28598   time_t t;
28599   time(&t);
28600   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
28601 #elif OS_VXWORKS
28602   struct timespec sNow;
28603   clock_gettime(CLOCK_REALTIME, &sNow);
28604   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
28605 #else
28606   struct timeval sNow;
28607   if( gettimeofday(&sNow, 0)==0 ){
28608     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
28609   }else{
28610     rc = SQLITE_ERROR;
28611   }
28612 #endif
28613 
28614 #ifdef SQLITE_TEST
28615   if( sqlite3_current_time ){
28616     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
28617   }
28618 #endif
28619   UNUSED_PARAMETER(NotUsed);
28620   return rc;
28621 }
28622 
28623 /*
28624 ** Find the current time (in Universal Coordinated Time).  Write the
28625 ** current time and date as a Julian Day number into *prNow and
28626 ** return 0.  Return 1 if the time and date cannot be found.
28627 */
28628 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
28629   sqlite3_int64 i = 0;
28630   int rc;
28631   UNUSED_PARAMETER(NotUsed);
28632   rc = unixCurrentTimeInt64(0, &i);
28633   *prNow = i/86400000.0;
28634   return rc;
28635 }
28636 
28637 /*
28638 ** We added the xGetLastError() method with the intention of providing
28639 ** better low-level error messages when operating-system problems come up
28640 ** during SQLite operation.  But so far, none of that has been implemented
28641 ** in the core.  So this routine is never called.  For now, it is merely
28642 ** a place-holder.
28643 */
28644 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
28645   UNUSED_PARAMETER(NotUsed);
28646   UNUSED_PARAMETER(NotUsed2);
28647   UNUSED_PARAMETER(NotUsed3);
28648   return 0;
28649 }
28650 
28651 
28652 /*
28653 ************************ End of sqlite3_vfs methods ***************************
28654 ******************************************************************************/
28655 
28656 /******************************************************************************
28657 ************************** Begin Proxy Locking ********************************
28658 **
28659 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
28660 ** other locking methods on secondary lock files.  Proxy locking is a
28661 ** meta-layer over top of the primitive locking implemented above.  For
28662 ** this reason, the division that implements of proxy locking is deferred
28663 ** until late in the file (here) after all of the other I/O methods have
28664 ** been defined - so that the primitive locking methods are available
28665 ** as services to help with the implementation of proxy locking.
28666 **
28667 ****
28668 **
28669 ** The default locking schemes in SQLite use byte-range locks on the
28670 ** database file to coordinate safe, concurrent access by multiple readers
28671 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
28672 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
28673 ** as POSIX read & write locks over fixed set of locations (via fsctl),
28674 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
28675 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
28676 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
28677 ** address in the shared range is taken for a SHARED lock, the entire
28678 ** shared range is taken for an EXCLUSIVE lock):
28679 **
28680 **      PENDING_BYTE        0x40000000
28681 **      RESERVED_BYTE       0x40000001
28682 **      SHARED_RANGE        0x40000002 -> 0x40000200
28683 **
28684 ** This works well on the local file system, but shows a nearly 100x
28685 ** slowdown in read performance on AFP because the AFP client disables
28686 ** the read cache when byte-range locks are present.  Enabling the read
28687 ** cache exposes a cache coherency problem that is present on all OS X
28688 ** supported network file systems.  NFS and AFP both observe the
28689 ** close-to-open semantics for ensuring cache coherency
28690 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
28691 ** address the requirements for concurrent database access by multiple
28692 ** readers and writers
28693 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
28694 **
28695 ** To address the performance and cache coherency issues, proxy file locking
28696 ** changes the way database access is controlled by limiting access to a
28697 ** single host at a time and moving file locks off of the database file
28698 ** and onto a proxy file on the local file system.
28699 **
28700 **
28701 ** Using proxy locks
28702 ** -----------------
28703 **
28704 ** C APIs
28705 **
28706 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
28707 **                       <proxy_path> | ":auto:");
28708 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
28709 **
28710 **
28711 ** SQL pragmas
28712 **
28713 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
28714 **  PRAGMA [database.]lock_proxy_file
28715 **
28716 ** Specifying ":auto:" means that if there is a conch file with a matching
28717 ** host ID in it, the proxy path in the conch file will be used, otherwise
28718 ** a proxy path based on the user's temp dir
28719 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
28720 ** actual proxy file name is generated from the name and path of the
28721 ** database file.  For example:
28722 **
28723 **       For database path "/Users/me/foo.db"
28724 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
28725 **
28726 ** Once a lock proxy is configured for a database connection, it can not
28727 ** be removed, however it may be switched to a different proxy path via
28728 ** the above APIs (assuming the conch file is not being held by another
28729 ** connection or process).
28730 **
28731 **
28732 ** How proxy locking works
28733 ** -----------------------
28734 **
28735 ** Proxy file locking relies primarily on two new supporting files:
28736 **
28737 **   *  conch file to limit access to the database file to a single host
28738 **      at a time
28739 **
28740 **   *  proxy file to act as a proxy for the advisory locks normally
28741 **      taken on the database
28742 **
28743 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28744 ** by taking an sqlite-style shared lock on the conch file, reading the
28745 ** contents and comparing the host's unique host ID (see below) and lock
28746 ** proxy path against the values stored in the conch.  The conch file is
28747 ** stored in the same directory as the database file and the file name
28748 ** is patterned after the database file name as ".<databasename>-conch".
28749 ** If the conch file does not exist, or it's contents do not match the
28750 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28751 ** lock and the conch file contents is updated with the host ID and proxy
28752 ** path and the lock is downgraded to a shared lock again.  If the conch
28753 ** is held by another process (with a shared lock), the exclusive lock
28754 ** will fail and SQLITE_BUSY is returned.
28755 **
28756 ** The proxy file - a single-byte file used for all advisory file locks
28757 ** normally taken on the database file.   This allows for safe sharing
28758 ** of the database file for multiple readers and writers on the same
28759 ** host (the conch ensures that they all use the same local lock file).
28760 **
28761 ** Requesting the lock proxy does not immediately take the conch, it is
28762 ** only taken when the first request to lock database file is made.
28763 ** This matches the semantics of the traditional locking behavior, where
28764 ** opening a connection to a database file does not take a lock on it.
28765 ** The shared lock and an open file descriptor are maintained until
28766 ** the connection to the database is closed.
28767 **
28768 ** The proxy file and the lock file are never deleted so they only need
28769 ** to be created the first time they are used.
28770 **
28771 ** Configuration options
28772 ** ---------------------
28773 **
28774 **  SQLITE_PREFER_PROXY_LOCKING
28775 **
28776 **       Database files accessed on non-local file systems are
28777 **       automatically configured for proxy locking, lock files are
28778 **       named automatically using the same logic as
28779 **       PRAGMA lock_proxy_file=":auto:"
28780 **
28781 **  SQLITE_PROXY_DEBUG
28782 **
28783 **       Enables the logging of error messages during host id file
28784 **       retrieval and creation
28785 **
28786 **  LOCKPROXYDIR
28787 **
28788 **       Overrides the default directory used for lock proxy files that
28789 **       are named automatically via the ":auto:" setting
28790 **
28791 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28792 **
28793 **       Permissions to use when creating a directory for storing the
28794 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28795 **
28796 **
28797 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28798 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28799 ** force proxy locking to be used for every database file opened, and 0
28800 ** will force automatic proxy locking to be disabled for all database
28801 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28802 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28803 */
28804 
28805 /*
28806 ** Proxy locking is only available on MacOSX
28807 */
28808 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28809 
28810 /*
28811 ** The proxyLockingContext has the path and file structures for the remote
28812 ** and local proxy files in it
28813 */
28814 typedef struct proxyLockingContext proxyLockingContext;
28815 struct proxyLockingContext {
28816   unixFile *conchFile;         /* Open conch file */
28817   char *conchFilePath;         /* Name of the conch file */
28818   unixFile *lockProxy;         /* Open proxy lock file */
28819   char *lockProxyPath;         /* Name of the proxy lock file */
28820   char *dbPath;                /* Name of the open file */
28821   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28822   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28823   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28824 };
28825 
28826 /*
28827 ** The proxy lock file path for the database at dbPath is written into lPath,
28828 ** which must point to valid, writable memory large enough for a maxLen length
28829 ** file path.
28830 */
28831 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28832   int len;
28833   int dbLen;
28834   int i;
28835 
28836 #ifdef LOCKPROXYDIR
28837   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28838 #else
28839 # ifdef _CS_DARWIN_USER_TEMP_DIR
28840   {
28841     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28842       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28843                lPath, errno, getpid()));
28844       return SQLITE_IOERR_LOCK;
28845     }
28846     len = strlcat(lPath, "sqliteplocks", maxLen);
28847   }
28848 # else
28849   len = strlcpy(lPath, "/tmp/", maxLen);
28850 # endif
28851 #endif
28852 
28853   if( lPath[len-1]!='/' ){
28854     len = strlcat(lPath, "/", maxLen);
28855   }
28856 
28857   /* transform the db path to a unique cache name */
28858   dbLen = (int)strlen(dbPath);
28859   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28860     char c = dbPath[i];
28861     lPath[i+len] = (c=='/')?'_':c;
28862   }
28863   lPath[i+len]='\0';
28864   strlcat(lPath, ":auto:", maxLen);
28865   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28866   return SQLITE_OK;
28867 }
28868 
28869 /*
28870  ** Creates the lock file and any missing directories in lockPath
28871  */
28872 static int proxyCreateLockPath(const char *lockPath){
28873   int i, len;
28874   char buf[MAXPATHLEN];
28875   int start = 0;
28876 
28877   assert(lockPath!=NULL);
28878   /* try to create all the intermediate directories */
28879   len = (int)strlen(lockPath);
28880   buf[0] = lockPath[0];
28881   for( i=1; i<len; i++ ){
28882     if( lockPath[i] == '/' && (i - start > 0) ){
28883       /* only mkdir if leaf dir != "." or "/" or ".." */
28884       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
28885          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28886         buf[i]='\0';
28887         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28888           int err=errno;
28889           if( err!=EEXIST ) {
28890             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28891                      "'%s' proxy lock path=%s pid=%d\n",
28892                      buf, strerror(err), lockPath, getpid()));
28893             return err;
28894           }
28895         }
28896       }
28897       start=i+1;
28898     }
28899     buf[i] = lockPath[i];
28900   }
28901   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28902   return 0;
28903 }
28904 
28905 /*
28906 ** Create a new VFS file descriptor (stored in memory obtained from
28907 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28908 **
28909 ** The caller is responsible not only for closing the file descriptor
28910 ** but also for freeing the memory associated with the file descriptor.
28911 */
28912 static int proxyCreateUnixFile(
28913     const char *path,        /* path for the new unixFile */
28914     unixFile **ppFile,       /* unixFile created and returned by ref */
28915     int islockfile           /* if non zero missing dirs will be created */
28916 ) {
28917   int fd = -1;
28918   unixFile *pNew;
28919   int rc = SQLITE_OK;
28920   int openFlags = O_RDWR | O_CREAT;
28921   sqlite3_vfs dummyVfs;
28922   int terrno = 0;
28923   UnixUnusedFd *pUnused = NULL;
28924 
28925   /* 1. first try to open/create the file
28926   ** 2. if that fails, and this is a lock file (not-conch), try creating
28927   ** the parent directories and then try again.
28928   ** 3. if that fails, try to open the file read-only
28929   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28930   */
28931   pUnused = findReusableFd(path, openFlags);
28932   if( pUnused ){
28933     fd = pUnused->fd;
28934   }else{
28935     pUnused = sqlite3_malloc(sizeof(*pUnused));
28936     if( !pUnused ){
28937       return SQLITE_NOMEM;
28938     }
28939   }
28940   if( fd<0 ){
28941     fd = robust_open(path, openFlags, 0);
28942     terrno = errno;
28943     if( fd<0 && errno==ENOENT && islockfile ){
28944       if( proxyCreateLockPath(path) == SQLITE_OK ){
28945         fd = robust_open(path, openFlags, 0);
28946       }
28947     }
28948   }
28949   if( fd<0 ){
28950     openFlags = O_RDONLY;
28951     fd = robust_open(path, openFlags, 0);
28952     terrno = errno;
28953   }
28954   if( fd<0 ){
28955     if( islockfile ){
28956       return SQLITE_BUSY;
28957     }
28958     switch (terrno) {
28959       case EACCES:
28960         return SQLITE_PERM;
28961       case EIO:
28962         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28963       default:
28964         return SQLITE_CANTOPEN_BKPT;
28965     }
28966   }
28967 
28968   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28969   if( pNew==NULL ){
28970     rc = SQLITE_NOMEM;
28971     goto end_create_proxy;
28972   }
28973   memset(pNew, 0, sizeof(unixFile));
28974   pNew->openFlags = openFlags;
28975   memset(&dummyVfs, 0, sizeof(dummyVfs));
28976   dummyVfs.pAppData = (void*)&autolockIoFinder;
28977   dummyVfs.zName = "dummy";
28978   pUnused->fd = fd;
28979   pUnused->flags = openFlags;
28980   pNew->pUnused = pUnused;
28981 
28982   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
28983   if( rc==SQLITE_OK ){
28984     *ppFile = pNew;
28985     return SQLITE_OK;
28986   }
28987 end_create_proxy:
28988   robust_close(pNew, fd, __LINE__);
28989   sqlite3_free(pNew);
28990   sqlite3_free(pUnused);
28991   return rc;
28992 }
28993 
28994 #ifdef SQLITE_TEST
28995 /* simulate multiple hosts by creating unique hostid file paths */
28996 SQLITE_API int sqlite3_hostid_num = 0;
28997 #endif
28998 
28999 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
29000 
29001 /* Not always defined in the headers as it ought to be */
29002 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29003 
29004 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
29005 ** bytes of writable memory.
29006 */
29007 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29008   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29009   memset(pHostID, 0, PROXY_HOSTIDLEN);
29010 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29011                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29012   {
29013     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29014     if( gethostuuid(pHostID, &timeout) ){
29015       int err = errno;
29016       if( pError ){
29017         *pError = err;
29018       }
29019       return SQLITE_IOERR;
29020     }
29021   }
29022 #else
29023   UNUSED_PARAMETER(pError);
29024 #endif
29025 #ifdef SQLITE_TEST
29026   /* simulate multiple hosts by creating unique hostid file paths */
29027   if( sqlite3_hostid_num != 0){
29028     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29029   }
29030 #endif
29031 
29032   return SQLITE_OK;
29033 }
29034 
29035 /* The conch file contains the header, host id and lock file path
29036  */
29037 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29038 #define PROXY_HEADERLEN    1   /* conch file header length */
29039 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29040 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29041 
29042 /*
29043 ** Takes an open conch file, copies the contents to a new path and then moves
29044 ** it back.  The newly created file's file descriptor is assigned to the
29045 ** conch file structure and finally the original conch file descriptor is
29046 ** closed.  Returns zero if successful.
29047 */
29048 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29049   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29050   unixFile *conchFile = pCtx->conchFile;
29051   char tPath[MAXPATHLEN];
29052   char buf[PROXY_MAXCONCHLEN];
29053   char *cPath = pCtx->conchFilePath;
29054   size_t readLen = 0;
29055   size_t pathLen = 0;
29056   char errmsg[64] = "";
29057   int fd = -1;
29058   int rc = -1;
29059   UNUSED_PARAMETER(myHostID);
29060 
29061   /* create a new path by replace the trailing '-conch' with '-break' */
29062   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29063   if( pathLen>MAXPATHLEN || pathLen<6 ||
29064      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29065     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29066     goto end_breaklock;
29067   }
29068   /* read the conch content */
29069   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29070   if( readLen<PROXY_PATHINDEX ){
29071     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29072     goto end_breaklock;
29073   }
29074   /* write it out to the temporary break file */
29075   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29076   if( fd<0 ){
29077     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29078     goto end_breaklock;
29079   }
29080   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29081     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29082     goto end_breaklock;
29083   }
29084   if( rename(tPath, cPath) ){
29085     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29086     goto end_breaklock;
29087   }
29088   rc = 0;
29089   fprintf(stderr, "broke stale lock on %s\n", cPath);
29090   robust_close(pFile, conchFile->h, __LINE__);
29091   conchFile->h = fd;
29092   conchFile->openFlags = O_RDWR | O_CREAT;
29093 
29094 end_breaklock:
29095   if( rc ){
29096     if( fd>=0 ){
29097       osUnlink(tPath);
29098       robust_close(pFile, fd, __LINE__);
29099     }
29100     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29101   }
29102   return rc;
29103 }
29104 
29105 /* Take the requested lock on the conch file and break a stale lock if the
29106 ** host id matches.
29107 */
29108 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29109   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29110   unixFile *conchFile = pCtx->conchFile;
29111   int rc = SQLITE_OK;
29112   int nTries = 0;
29113   struct timespec conchModTime;
29114 
29115   memset(&conchModTime, 0, sizeof(conchModTime));
29116   do {
29117     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29118     nTries ++;
29119     if( rc==SQLITE_BUSY ){
29120       /* If the lock failed (busy):
29121        * 1st try: get the mod time of the conch, wait 0.5s and try again.
29122        * 2nd try: fail if the mod time changed or host id is different, wait
29123        *           10 sec and try again
29124        * 3rd try: break the lock unless the mod time has changed.
29125        */
29126       struct stat buf;
29127       if( osFstat(conchFile->h, &buf) ){
29128         pFile->lastErrno = errno;
29129         return SQLITE_IOERR_LOCK;
29130       }
29131 
29132       if( nTries==1 ){
29133         conchModTime = buf.st_mtimespec;
29134         usleep(500000); /* wait 0.5 sec and try the lock again*/
29135         continue;
29136       }
29137 
29138       assert( nTries>1 );
29139       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
29140          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29141         return SQLITE_BUSY;
29142       }
29143 
29144       if( nTries==2 ){
29145         char tBuf[PROXY_MAXCONCHLEN];
29146         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29147         if( len<0 ){
29148           pFile->lastErrno = errno;
29149           return SQLITE_IOERR_LOCK;
29150         }
29151         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29152           /* don't break the lock if the host id doesn't match */
29153           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29154             return SQLITE_BUSY;
29155           }
29156         }else{
29157           /* don't break the lock on short read or a version mismatch */
29158           return SQLITE_BUSY;
29159         }
29160         usleep(10000000); /* wait 10 sec and try the lock again */
29161         continue;
29162       }
29163 
29164       assert( nTries==3 );
29165       if( 0==proxyBreakConchLock(pFile, myHostID) ){
29166         rc = SQLITE_OK;
29167         if( lockType==EXCLUSIVE_LOCK ){
29168           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
29169         }
29170         if( !rc ){
29171           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29172         }
29173       }
29174     }
29175   } while( rc==SQLITE_BUSY && nTries<3 );
29176 
29177   return rc;
29178 }
29179 
29180 /* Takes the conch by taking a shared lock and read the contents conch, if
29181 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
29182 ** lockPath means that the lockPath in the conch file will be used if the
29183 ** host IDs match, or a new lock path will be generated automatically
29184 ** and written to the conch file.
29185 */
29186 static int proxyTakeConch(unixFile *pFile){
29187   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29188 
29189   if( pCtx->conchHeld!=0 ){
29190     return SQLITE_OK;
29191   }else{
29192     unixFile *conchFile = pCtx->conchFile;
29193     uuid_t myHostID;
29194     int pError = 0;
29195     char readBuf[PROXY_MAXCONCHLEN];
29196     char lockPath[MAXPATHLEN];
29197     char *tempLockPath = NULL;
29198     int rc = SQLITE_OK;
29199     int createConch = 0;
29200     int hostIdMatch = 0;
29201     int readLen = 0;
29202     int tryOldLockPath = 0;
29203     int forceNewLockPath = 0;
29204 
29205     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
29206              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
29207 
29208     rc = proxyGetHostID(myHostID, &pError);
29209     if( (rc&0xff)==SQLITE_IOERR ){
29210       pFile->lastErrno = pError;
29211       goto end_takeconch;
29212     }
29213     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
29214     if( rc!=SQLITE_OK ){
29215       goto end_takeconch;
29216     }
29217     /* read the existing conch file */
29218     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
29219     if( readLen<0 ){
29220       /* I/O error: lastErrno set by seekAndRead */
29221       pFile->lastErrno = conchFile->lastErrno;
29222       rc = SQLITE_IOERR_READ;
29223       goto end_takeconch;
29224     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
29225              readBuf[0]!=(char)PROXY_CONCHVERSION ){
29226       /* a short read or version format mismatch means we need to create a new
29227       ** conch file.
29228       */
29229       createConch = 1;
29230     }
29231     /* if the host id matches and the lock path already exists in the conch
29232     ** we'll try to use the path there, if we can't open that path, we'll
29233     ** retry with a new auto-generated path
29234     */
29235     do { /* in case we need to try again for an :auto: named lock file */
29236 
29237       if( !createConch && !forceNewLockPath ){
29238         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
29239                                   PROXY_HOSTIDLEN);
29240         /* if the conch has data compare the contents */
29241         if( !pCtx->lockProxyPath ){
29242           /* for auto-named local lock file, just check the host ID and we'll
29243            ** use the local lock file path that's already in there
29244            */
29245           if( hostIdMatch ){
29246             size_t pathLen = (readLen - PROXY_PATHINDEX);
29247 
29248             if( pathLen>=MAXPATHLEN ){
29249               pathLen=MAXPATHLEN-1;
29250             }
29251             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
29252             lockPath[pathLen] = 0;
29253             tempLockPath = lockPath;
29254             tryOldLockPath = 1;
29255             /* create a copy of the lock path if the conch is taken */
29256             goto end_takeconch;
29257           }
29258         }else if( hostIdMatch
29259                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
29260                            readLen-PROXY_PATHINDEX)
29261         ){
29262           /* conch host and lock path match */
29263           goto end_takeconch;
29264         }
29265       }
29266 
29267       /* if the conch isn't writable and doesn't match, we can't take it */
29268       if( (conchFile->openFlags&O_RDWR) == 0 ){
29269         rc = SQLITE_BUSY;
29270         goto end_takeconch;
29271       }
29272 
29273       /* either the conch didn't match or we need to create a new one */
29274       if( !pCtx->lockProxyPath ){
29275         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
29276         tempLockPath = lockPath;
29277         /* create a copy of the lock path _only_ if the conch is taken */
29278       }
29279 
29280       /* update conch with host and path (this will fail if other process
29281       ** has a shared lock already), if the host id matches, use the big
29282       ** stick.
29283       */
29284       futimes(conchFile->h, NULL);
29285       if( hostIdMatch && !createConch ){
29286         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29287           /* We are trying for an exclusive lock but another thread in this
29288            ** same process is still holding a shared lock. */
29289           rc = SQLITE_BUSY;
29290         } else {
29291           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29292         }
29293       }else{
29294         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29295       }
29296       if( rc==SQLITE_OK ){
29297         char writeBuffer[PROXY_MAXCONCHLEN];
29298         int writeSize = 0;
29299 
29300         writeBuffer[0] = (char)PROXY_CONCHVERSION;
29301         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29302         if( pCtx->lockProxyPath!=NULL ){
29303           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29304         }else{
29305           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29306         }
29307         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29308         robust_ftruncate(conchFile->h, writeSize);
29309         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29310         fsync(conchFile->h);
29311         /* If we created a new conch file (not just updated the contents of a
29312          ** valid conch file), try to match the permissions of the database
29313          */
29314         if( rc==SQLITE_OK && createConch ){
29315           struct stat buf;
29316           int err = osFstat(pFile->h, &buf);
29317           if( err==0 ){
29318             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29319                                         S_IROTH|S_IWOTH);
29320             /* try to match the database file R/W permissions, ignore failure */
29321 #ifndef SQLITE_PROXY_DEBUG
29322             osFchmod(conchFile->h, cmode);
29323 #else
29324             do{
29325               rc = osFchmod(conchFile->h, cmode);
29326             }while( rc==(-1) && errno==EINTR );
29327             if( rc!=0 ){
29328               int code = errno;
29329               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29330                       cmode, code, strerror(code));
29331             } else {
29332               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29333             }
29334           }else{
29335             int code = errno;
29336             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
29337                     err, code, strerror(code));
29338 #endif
29339           }
29340         }
29341       }
29342       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29343 
29344     end_takeconch:
29345       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
29346       if( rc==SQLITE_OK && pFile->openFlags ){
29347         int fd;
29348         if( pFile->h>=0 ){
29349           robust_close(pFile, pFile->h, __LINE__);
29350         }
29351         pFile->h = -1;
29352         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29353         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
29354         if( fd>=0 ){
29355           pFile->h = fd;
29356         }else{
29357           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29358            during locking */
29359         }
29360       }
29361       if( rc==SQLITE_OK && !pCtx->lockProxy ){
29362         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29363         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29364         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29365           /* we couldn't create the proxy lock file with the old lock file path
29366            ** so try again via auto-naming
29367            */
29368           forceNewLockPath = 1;
29369           tryOldLockPath = 0;
29370           continue; /* go back to the do {} while start point, try again */
29371         }
29372       }
29373       if( rc==SQLITE_OK ){
29374         /* Need to make a copy of path if we extracted the value
29375          ** from the conch file or the path was allocated on the stack
29376          */
29377         if( tempLockPath ){
29378           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29379           if( !pCtx->lockProxyPath ){
29380             rc = SQLITE_NOMEM;
29381           }
29382         }
29383       }
29384       if( rc==SQLITE_OK ){
29385         pCtx->conchHeld = 1;
29386 
29387         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29388           afpLockingContext *afpCtx;
29389           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29390           afpCtx->dbPath = pCtx->lockProxyPath;
29391         }
29392       } else {
29393         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29394       }
29395       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
29396                rc==SQLITE_OK?"ok":"failed"));
29397       return rc;
29398     } while (1); /* in case we need to retry the :auto: lock file -
29399                  ** we should never get here except via the 'continue' call. */
29400   }
29401 }
29402 
29403 /*
29404 ** If pFile holds a lock on a conch file, then release that lock.
29405 */
29406 static int proxyReleaseConch(unixFile *pFile){
29407   int rc = SQLITE_OK;         /* Subroutine return code */
29408   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
29409   unixFile *conchFile;        /* Name of the conch file */
29410 
29411   pCtx = (proxyLockingContext *)pFile->lockingContext;
29412   conchFile = pCtx->conchFile;
29413   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
29414            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
29415            getpid()));
29416   if( pCtx->conchHeld>0 ){
29417     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29418   }
29419   pCtx->conchHeld = 0;
29420   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
29421            (rc==SQLITE_OK ? "ok" : "failed")));
29422   return rc;
29423 }
29424 
29425 /*
29426 ** Given the name of a database file, compute the name of its conch file.
29427 ** Store the conch filename in memory obtained from sqlite3_malloc().
29428 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
29429 ** or SQLITE_NOMEM if unable to obtain memory.
29430 **
29431 ** The caller is responsible for ensuring that the allocated memory
29432 ** space is eventually freed.
29433 **
29434 ** *pConchPath is set to NULL if a memory allocation error occurs.
29435 */
29436 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
29437   int i;                        /* Loop counter */
29438   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
29439   char *conchPath;              /* buffer in which to construct conch name */
29440 
29441   /* Allocate space for the conch filename and initialize the name to
29442   ** the name of the original database file. */
29443   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
29444   if( conchPath==0 ){
29445     return SQLITE_NOMEM;
29446   }
29447   memcpy(conchPath, dbPath, len+1);
29448 
29449   /* now insert a "." before the last / character */
29450   for( i=(len-1); i>=0; i-- ){
29451     if( conchPath[i]=='/' ){
29452       i++;
29453       break;
29454     }
29455   }
29456   conchPath[i]='.';
29457   while ( i<len ){
29458     conchPath[i+1]=dbPath[i];
29459     i++;
29460   }
29461 
29462   /* append the "-conch" suffix to the file */
29463   memcpy(&conchPath[i+1], "-conch", 7);
29464   assert( (int)strlen(conchPath) == len+7 );
29465 
29466   return SQLITE_OK;
29467 }
29468 
29469 
29470 /* Takes a fully configured proxy locking-style unix file and switches
29471 ** the local lock file path
29472 */
29473 static int switchLockProxyPath(unixFile *pFile, const char *path) {
29474   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29475   char *oldPath = pCtx->lockProxyPath;
29476   int rc = SQLITE_OK;
29477 
29478   if( pFile->eFileLock!=NO_LOCK ){
29479     return SQLITE_BUSY;
29480   }
29481 
29482   /* nothing to do if the path is NULL, :auto: or matches the existing path */
29483   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
29484     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
29485     return SQLITE_OK;
29486   }else{
29487     unixFile *lockProxy = pCtx->lockProxy;
29488     pCtx->lockProxy=NULL;
29489     pCtx->conchHeld = 0;
29490     if( lockProxy!=NULL ){
29491       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
29492       if( rc ) return rc;
29493       sqlite3_free(lockProxy);
29494     }
29495     sqlite3_free(oldPath);
29496     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
29497   }
29498 
29499   return rc;
29500 }
29501 
29502 /*
29503 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
29504 ** is a string buffer at least MAXPATHLEN+1 characters in size.
29505 **
29506 ** This routine find the filename associated with pFile and writes it
29507 ** int dbPath.
29508 */
29509 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
29510 #if defined(__APPLE__)
29511   if( pFile->pMethod == &afpIoMethods ){
29512     /* afp style keeps a reference to the db path in the filePath field
29513     ** of the struct */
29514     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29515     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
29516   } else
29517 #endif
29518   if( pFile->pMethod == &dotlockIoMethods ){
29519     /* dot lock style uses the locking context to store the dot lock
29520     ** file path */
29521     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
29522     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
29523   }else{
29524     /* all other styles use the locking context to store the db file path */
29525     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29526     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
29527   }
29528   return SQLITE_OK;
29529 }
29530 
29531 /*
29532 ** Takes an already filled in unix file and alters it so all file locking
29533 ** will be performed on the local proxy lock file.  The following fields
29534 ** are preserved in the locking context so that they can be restored and
29535 ** the unix structure properly cleaned up at close time:
29536 **  ->lockingContext
29537 **  ->pMethod
29538 */
29539 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
29540   proxyLockingContext *pCtx;
29541   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
29542   char *lockPath=NULL;
29543   int rc = SQLITE_OK;
29544 
29545   if( pFile->eFileLock!=NO_LOCK ){
29546     return SQLITE_BUSY;
29547   }
29548   proxyGetDbPathForUnixFile(pFile, dbPath);
29549   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
29550     lockPath=NULL;
29551   }else{
29552     lockPath=(char *)path;
29553   }
29554 
29555   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
29556            (lockPath ? lockPath : ":auto:"), getpid()));
29557 
29558   pCtx = sqlite3_malloc( sizeof(*pCtx) );
29559   if( pCtx==0 ){
29560     return SQLITE_NOMEM;
29561   }
29562   memset(pCtx, 0, sizeof(*pCtx));
29563 
29564   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
29565   if( rc==SQLITE_OK ){
29566     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
29567     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
29568       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
29569       ** (c) the file system is read-only, then enable no-locking access.
29570       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
29571       ** that openFlags will have only one of O_RDONLY or O_RDWR.
29572       */
29573       struct statfs fsInfo;
29574       struct stat conchInfo;
29575       int goLockless = 0;
29576 
29577       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
29578         int err = errno;
29579         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
29580           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
29581         }
29582       }
29583       if( goLockless ){
29584         pCtx->conchHeld = -1; /* read only FS/ lockless */
29585         rc = SQLITE_OK;
29586       }
29587     }
29588   }
29589   if( rc==SQLITE_OK && lockPath ){
29590     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
29591   }
29592 
29593   if( rc==SQLITE_OK ){
29594     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
29595     if( pCtx->dbPath==NULL ){
29596       rc = SQLITE_NOMEM;
29597     }
29598   }
29599   if( rc==SQLITE_OK ){
29600     /* all memory is allocated, proxys are created and assigned,
29601     ** switch the locking context and pMethod then return.
29602     */
29603     pCtx->oldLockingContext = pFile->lockingContext;
29604     pFile->lockingContext = pCtx;
29605     pCtx->pOldMethod = pFile->pMethod;
29606     pFile->pMethod = &proxyIoMethods;
29607   }else{
29608     if( pCtx->conchFile ){
29609       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
29610       sqlite3_free(pCtx->conchFile);
29611     }
29612     sqlite3DbFree(0, pCtx->lockProxyPath);
29613     sqlite3_free(pCtx->conchFilePath);
29614     sqlite3_free(pCtx);
29615   }
29616   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
29617            (rc==SQLITE_OK ? "ok" : "failed")));
29618   return rc;
29619 }
29620 
29621 
29622 /*
29623 ** This routine handles sqlite3_file_control() calls that are specific
29624 ** to proxy locking.
29625 */
29626 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
29627   switch( op ){
29628     case SQLITE_GET_LOCKPROXYFILE: {
29629       unixFile *pFile = (unixFile*)id;
29630       if( pFile->pMethod == &proxyIoMethods ){
29631         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29632         proxyTakeConch(pFile);
29633         if( pCtx->lockProxyPath ){
29634           *(const char **)pArg = pCtx->lockProxyPath;
29635         }else{
29636           *(const char **)pArg = ":auto: (not held)";
29637         }
29638       } else {
29639         *(const char **)pArg = NULL;
29640       }
29641       return SQLITE_OK;
29642     }
29643     case SQLITE_SET_LOCKPROXYFILE: {
29644       unixFile *pFile = (unixFile*)id;
29645       int rc = SQLITE_OK;
29646       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
29647       if( pArg==NULL || (const char *)pArg==0 ){
29648         if( isProxyStyle ){
29649           /* turn off proxy locking - not supported */
29650           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
29651         }else{
29652           /* turn off proxy locking - already off - NOOP */
29653           rc = SQLITE_OK;
29654         }
29655       }else{
29656         const char *proxyPath = (const char *)pArg;
29657         if( isProxyStyle ){
29658           proxyLockingContext *pCtx =
29659             (proxyLockingContext*)pFile->lockingContext;
29660           if( !strcmp(pArg, ":auto:")
29661            || (pCtx->lockProxyPath &&
29662                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
29663           ){
29664             rc = SQLITE_OK;
29665           }else{
29666             rc = switchLockProxyPath(pFile, proxyPath);
29667           }
29668         }else{
29669           /* turn on proxy file locking */
29670           rc = proxyTransformUnixFile(pFile, proxyPath);
29671         }
29672       }
29673       return rc;
29674     }
29675     default: {
29676       assert( 0 );  /* The call assures that only valid opcodes are sent */
29677     }
29678   }
29679   /*NOTREACHED*/
29680   return SQLITE_ERROR;
29681 }
29682 
29683 /*
29684 ** Within this division (the proxying locking implementation) the procedures
29685 ** above this point are all utilities.  The lock-related methods of the
29686 ** proxy-locking sqlite3_io_method object follow.
29687 */
29688 
29689 
29690 /*
29691 ** This routine checks if there is a RESERVED lock held on the specified
29692 ** file by this or any other process. If such a lock is held, set *pResOut
29693 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29694 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29695 */
29696 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
29697   unixFile *pFile = (unixFile*)id;
29698   int rc = proxyTakeConch(pFile);
29699   if( rc==SQLITE_OK ){
29700     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29701     if( pCtx->conchHeld>0 ){
29702       unixFile *proxy = pCtx->lockProxy;
29703       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
29704     }else{ /* conchHeld < 0 is lockless */
29705       pResOut=0;
29706     }
29707   }
29708   return rc;
29709 }
29710 
29711 /*
29712 ** Lock the file with the lock specified by parameter eFileLock - one
29713 ** of the following:
29714 **
29715 **     (1) SHARED_LOCK
29716 **     (2) RESERVED_LOCK
29717 **     (3) PENDING_LOCK
29718 **     (4) EXCLUSIVE_LOCK
29719 **
29720 ** Sometimes when requesting one lock state, additional lock states
29721 ** are inserted in between.  The locking might fail on one of the later
29722 ** transitions leaving the lock state different from what it started but
29723 ** still short of its goal.  The following chart shows the allowed
29724 ** transitions and the inserted intermediate states:
29725 **
29726 **    UNLOCKED -> SHARED
29727 **    SHARED -> RESERVED
29728 **    SHARED -> (PENDING) -> EXCLUSIVE
29729 **    RESERVED -> (PENDING) -> EXCLUSIVE
29730 **    PENDING -> EXCLUSIVE
29731 **
29732 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29733 ** routine to lower a locking level.
29734 */
29735 static int proxyLock(sqlite3_file *id, int eFileLock) {
29736   unixFile *pFile = (unixFile*)id;
29737   int rc = proxyTakeConch(pFile);
29738   if( rc==SQLITE_OK ){
29739     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29740     if( pCtx->conchHeld>0 ){
29741       unixFile *proxy = pCtx->lockProxy;
29742       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29743       pFile->eFileLock = proxy->eFileLock;
29744     }else{
29745       /* conchHeld < 0 is lockless */
29746     }
29747   }
29748   return rc;
29749 }
29750 
29751 
29752 /*
29753 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29754 ** must be either NO_LOCK or SHARED_LOCK.
29755 **
29756 ** If the locking level of the file descriptor is already at or below
29757 ** the requested locking level, this routine is a no-op.
29758 */
29759 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29760   unixFile *pFile = (unixFile*)id;
29761   int rc = proxyTakeConch(pFile);
29762   if( rc==SQLITE_OK ){
29763     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29764     if( pCtx->conchHeld>0 ){
29765       unixFile *proxy = pCtx->lockProxy;
29766       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29767       pFile->eFileLock = proxy->eFileLock;
29768     }else{
29769       /* conchHeld < 0 is lockless */
29770     }
29771   }
29772   return rc;
29773 }
29774 
29775 /*
29776 ** Close a file that uses proxy locks.
29777 */
29778 static int proxyClose(sqlite3_file *id) {
29779   if( id ){
29780     unixFile *pFile = (unixFile*)id;
29781     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29782     unixFile *lockProxy = pCtx->lockProxy;
29783     unixFile *conchFile = pCtx->conchFile;
29784     int rc = SQLITE_OK;
29785 
29786     if( lockProxy ){
29787       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29788       if( rc ) return rc;
29789       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29790       if( rc ) return rc;
29791       sqlite3_free(lockProxy);
29792       pCtx->lockProxy = 0;
29793     }
29794     if( conchFile ){
29795       if( pCtx->conchHeld ){
29796         rc = proxyReleaseConch(pFile);
29797         if( rc ) return rc;
29798       }
29799       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29800       if( rc ) return rc;
29801       sqlite3_free(conchFile);
29802     }
29803     sqlite3DbFree(0, pCtx->lockProxyPath);
29804     sqlite3_free(pCtx->conchFilePath);
29805     sqlite3DbFree(0, pCtx->dbPath);
29806     /* restore the original locking context and pMethod then close it */
29807     pFile->lockingContext = pCtx->oldLockingContext;
29808     pFile->pMethod = pCtx->pOldMethod;
29809     sqlite3_free(pCtx);
29810     return pFile->pMethod->xClose(id);
29811   }
29812   return SQLITE_OK;
29813 }
29814 
29815 
29816 
29817 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29818 /*
29819 ** The proxy locking style is intended for use with AFP filesystems.
29820 ** And since AFP is only supported on MacOSX, the proxy locking is also
29821 ** restricted to MacOSX.
29822 **
29823 **
29824 ******************* End of the proxy lock implementation **********************
29825 ******************************************************************************/
29826 
29827 /*
29828 ** Initialize the operating system interface.
29829 **
29830 ** This routine registers all VFS implementations for unix-like operating
29831 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29832 ** should be the only routines in this file that are visible from other
29833 ** files.
29834 **
29835 ** This routine is called once during SQLite initialization and by a
29836 ** single thread.  The memory allocation and mutex subsystems have not
29837 ** necessarily been initialized when this routine is called, and so they
29838 ** should not be used.
29839 */
29840 SQLITE_API int sqlite3_os_init(void){
29841   /*
29842   ** The following macro defines an initializer for an sqlite3_vfs object.
29843   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29844   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29845   ** silly C90 rules prohibit a void* from being cast to a function pointer
29846   ** and so we have to go through the intermediate pointer to avoid problems
29847   ** when compiling with -pedantic-errors on GCC.)
29848   **
29849   ** The FINDER parameter to this macro is the name of the pointer to the
29850   ** finder-function.  The finder-function returns a pointer to the
29851   ** sqlite_io_methods object that implements the desired locking
29852   ** behaviors.  See the division above that contains the IOMETHODS
29853   ** macro for addition information on finder-functions.
29854   **
29855   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29856   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29857   ** more than that; it looks at the filesystem type that hosts the
29858   ** database file and tries to choose an locking method appropriate for
29859   ** that filesystem time.
29860   */
29861   #define UNIXVFS(VFSNAME, FINDER) {                        \
29862     3,                    /* iVersion */                    \
29863     sizeof(unixFile),     /* szOsFile */                    \
29864     MAX_PATHNAME,         /* mxPathname */                  \
29865     0,                    /* pNext */                       \
29866     VFSNAME,              /* zName */                       \
29867     (void*)&FINDER,       /* pAppData */                    \
29868     unixOpen,             /* xOpen */                       \
29869     unixDelete,           /* xDelete */                     \
29870     unixAccess,           /* xAccess */                     \
29871     unixFullPathname,     /* xFullPathname */               \
29872     unixDlOpen,           /* xDlOpen */                     \
29873     unixDlError,          /* xDlError */                    \
29874     unixDlSym,            /* xDlSym */                      \
29875     unixDlClose,          /* xDlClose */                    \
29876     unixRandomness,       /* xRandomness */                 \
29877     unixSleep,            /* xSleep */                      \
29878     unixCurrentTime,      /* xCurrentTime */                \
29879     unixGetLastError,     /* xGetLastError */               \
29880     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29881     unixSetSystemCall,    /* xSetSystemCall */              \
29882     unixGetSystemCall,    /* xGetSystemCall */              \
29883     unixNextSystemCall,   /* xNextSystemCall */             \
29884   }
29885 
29886   /*
29887   ** All default VFSes for unix are contained in the following array.
29888   **
29889   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29890   ** by the SQLite core when the VFS is registered.  So the following
29891   ** array cannot be const.
29892   */
29893   static sqlite3_vfs aVfs[] = {
29894 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29895     UNIXVFS("unix",          autolockIoFinder ),
29896 #else
29897     UNIXVFS("unix",          posixIoFinder ),
29898 #endif
29899     UNIXVFS("unix-none",     nolockIoFinder ),
29900     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29901     UNIXVFS("unix-excl",     posixIoFinder ),
29902 #if OS_VXWORKS
29903     UNIXVFS("unix-namedsem", semIoFinder ),
29904 #endif
29905 #if SQLITE_ENABLE_LOCKING_STYLE
29906     UNIXVFS("unix-posix",    posixIoFinder ),
29907 #if !OS_VXWORKS
29908     UNIXVFS("unix-flock",    flockIoFinder ),
29909 #endif
29910 #endif
29911 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29912     UNIXVFS("unix-afp",      afpIoFinder ),
29913     UNIXVFS("unix-nfs",      nfsIoFinder ),
29914     UNIXVFS("unix-proxy",    proxyIoFinder ),
29915 #endif
29916   };
29917   unsigned int i;          /* Loop counter */
29918 
29919   /* Double-check that the aSyscall[] array has been constructed
29920   ** correctly.  See ticket [bb3a86e890c8e96ab] */
29921   assert( ArraySize(aSyscall)==21 );
29922 
29923   /* Register all VFSes defined in the aVfs[] array */
29924   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29925     sqlite3_vfs_register(&aVfs[i], i==0);
29926   }
29927   return SQLITE_OK;
29928 }
29929 
29930 /*
29931 ** Shutdown the operating system interface.
29932 **
29933 ** Some operating systems might need to do some cleanup in this routine,
29934 ** to release dynamically allocated objects.  But not on unix.
29935 ** This routine is a no-op for unix.
29936 */
29937 SQLITE_API int sqlite3_os_end(void){
29938   return SQLITE_OK;
29939 }
29940 
29941 #endif /* SQLITE_OS_UNIX */
29942 
29943 /************** End of os_unix.c *********************************************/
29944 /************** Begin file os_win.c ******************************************/
29945 /*
29946 ** 2004 May 22
29947 **
29948 ** The author disclaims copyright to this source code.  In place of
29949 ** a legal notice, here is a blessing:
29950 **
29951 **    May you do good and not evil.
29952 **    May you find forgiveness for yourself and forgive others.
29953 **    May you share freely, never taking more than you give.
29954 **
29955 ******************************************************************************
29956 **
29957 ** This file contains code that is specific to Windows.
29958 */
29959 #if SQLITE_OS_WIN               /* This file is used for Windows only */
29960 
29961 #ifdef __CYGWIN__
29962 # include <sys/cygwin.h>
29963 #endif
29964 
29965 /*
29966 ** Include code that is common to all os_*.c files
29967 */
29968 /************** Include os_common.h in the middle of os_win.c ****************/
29969 /************** Begin file os_common.h ***************************************/
29970 /*
29971 ** 2004 May 22
29972 **
29973 ** The author disclaims copyright to this source code.  In place of
29974 ** a legal notice, here is a blessing:
29975 **
29976 **    May you do good and not evil.
29977 **    May you find forgiveness for yourself and forgive others.
29978 **    May you share freely, never taking more than you give.
29979 **
29980 ******************************************************************************
29981 **
29982 ** This file contains macros and a little bit of code that is common to
29983 ** all of the platform-specific files (os_*.c) and is #included into those
29984 ** files.
29985 **
29986 ** This file should be #included by the os_*.c files only.  It is not a
29987 ** general purpose header file.
29988 */
29989 #ifndef _OS_COMMON_H_
29990 #define _OS_COMMON_H_
29991 
29992 /*
29993 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29994 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29995 ** switch.  The following code should catch this problem at compile-time.
29996 */
29997 #ifdef MEMORY_DEBUG
29998 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29999 #endif
30000 
30001 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30002 # ifndef SQLITE_DEBUG_OS_TRACE
30003 #   define SQLITE_DEBUG_OS_TRACE 0
30004 # endif
30005   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
30006 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30007 #else
30008 # define OSTRACE(X)
30009 #endif
30010 
30011 /*
30012 ** Macros for performance tracing.  Normally turned off.  Only works
30013 ** on i486 hardware.
30014 */
30015 #ifdef SQLITE_PERFORMANCE_TRACE
30016 
30017 /*
30018 ** hwtime.h contains inline assembler code for implementing
30019 ** high-performance timing routines.
30020 */
30021 /************** Include hwtime.h in the middle of os_common.h ****************/
30022 /************** Begin file hwtime.h ******************************************/
30023 /*
30024 ** 2008 May 27
30025 **
30026 ** The author disclaims copyright to this source code.  In place of
30027 ** a legal notice, here is a blessing:
30028 **
30029 **    May you do good and not evil.
30030 **    May you find forgiveness for yourself and forgive others.
30031 **    May you share freely, never taking more than you give.
30032 **
30033 ******************************************************************************
30034 **
30035 ** This file contains inline asm code for retrieving "high-performance"
30036 ** counters for x86 class CPUs.
30037 */
30038 #ifndef _HWTIME_H_
30039 #define _HWTIME_H_
30040 
30041 /*
30042 ** The following routine only works on pentium-class (or newer) processors.
30043 ** It uses the RDTSC opcode to read the cycle count value out of the
30044 ** processor and returns that value.  This can be used for high-res
30045 ** profiling.
30046 */
30047 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30048       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30049 
30050   #if defined(__GNUC__)
30051 
30052   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30053      unsigned int lo, hi;
30054      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30055      return (sqlite_uint64)hi << 32 | lo;
30056   }
30057 
30058   #elif defined(_MSC_VER)
30059 
30060   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30061      __asm {
30062         rdtsc
30063         ret       ; return value at EDX:EAX
30064      }
30065   }
30066 
30067   #endif
30068 
30069 #elif (defined(__GNUC__) && defined(__x86_64__))
30070 
30071   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30072       unsigned long val;
30073       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30074       return val;
30075   }
30076 
30077 #elif (defined(__GNUC__) && defined(__ppc__))
30078 
30079   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30080       unsigned long long retval;
30081       unsigned long junk;
30082       __asm__ __volatile__ ("\n\
30083           1:      mftbu   %1\n\
30084                   mftb    %L0\n\
30085                   mftbu   %0\n\
30086                   cmpw    %0,%1\n\
30087                   bne     1b"
30088                   : "=r" (retval), "=r" (junk));
30089       return retval;
30090   }
30091 
30092 #else
30093 
30094   #error Need implementation of sqlite3Hwtime() for your platform.
30095 
30096   /*
30097   ** To compile without implementing sqlite3Hwtime() for your platform,
30098   ** you can remove the above #error and use the following
30099   ** stub function.  You will lose timing support for many
30100   ** of the debugging and testing utilities, but it should at
30101   ** least compile and run.
30102   */
30103 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30104 
30105 #endif
30106 
30107 #endif /* !defined(_HWTIME_H_) */
30108 
30109 /************** End of hwtime.h **********************************************/
30110 /************** Continuing where we left off in os_common.h ******************/
30111 
30112 static sqlite_uint64 g_start;
30113 static sqlite_uint64 g_elapsed;
30114 #define TIMER_START       g_start=sqlite3Hwtime()
30115 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30116 #define TIMER_ELAPSED     g_elapsed
30117 #else
30118 #define TIMER_START
30119 #define TIMER_END
30120 #define TIMER_ELAPSED     ((sqlite_uint64)0)
30121 #endif
30122 
30123 /*
30124 ** If we compile with the SQLITE_TEST macro set, then the following block
30125 ** of code will give us the ability to simulate a disk I/O error.  This
30126 ** is used for testing the I/O recovery logic.
30127 */
30128 #ifdef SQLITE_TEST
30129 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
30130 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
30131 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
30132 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
30133 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
30134 SQLITE_API int sqlite3_diskfull_pending = 0;
30135 SQLITE_API int sqlite3_diskfull = 0;
30136 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30137 #define SimulateIOError(CODE)  \
30138   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30139        || sqlite3_io_error_pending-- == 1 )  \
30140               { local_ioerr(); CODE; }
30141 static void local_ioerr(){
30142   IOTRACE(("IOERR\n"));
30143   sqlite3_io_error_hit++;
30144   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30145 }
30146 #define SimulateDiskfullError(CODE) \
30147    if( sqlite3_diskfull_pending ){ \
30148      if( sqlite3_diskfull_pending == 1 ){ \
30149        local_ioerr(); \
30150        sqlite3_diskfull = 1; \
30151        sqlite3_io_error_hit = 1; \
30152        CODE; \
30153      }else{ \
30154        sqlite3_diskfull_pending--; \
30155      } \
30156    }
30157 #else
30158 #define SimulateIOErrorBenign(X)
30159 #define SimulateIOError(A)
30160 #define SimulateDiskfullError(A)
30161 #endif
30162 
30163 /*
30164 ** When testing, keep a count of the number of open files.
30165 */
30166 #ifdef SQLITE_TEST
30167 SQLITE_API int sqlite3_open_file_count = 0;
30168 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
30169 #else
30170 #define OpenCounter(X)
30171 #endif
30172 
30173 #endif /* !defined(_OS_COMMON_H_) */
30174 
30175 /************** End of os_common.h *******************************************/
30176 /************** Continuing where we left off in os_win.c *********************/
30177 
30178 /*
30179 ** Compiling and using WAL mode requires several APIs that are only
30180 ** available in Windows platforms based on the NT kernel.
30181 */
30182 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30183 # error "WAL mode requires support from the Windows NT kernel, compile\
30184  with SQLITE_OMIT_WAL."
30185 #endif
30186 
30187 /*
30188 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
30189 ** based on the sub-platform)?
30190 */
30191 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30192 #  define SQLITE_WIN32_HAS_ANSI
30193 #endif
30194 
30195 /*
30196 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
30197 ** based on the sub-platform)?
30198 */
30199 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30200 #  define SQLITE_WIN32_HAS_WIDE
30201 #endif
30202 
30203 /*
30204 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
30205 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
30206 ** are not present in the header file)?
30207 */
30208 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
30209 /*
30210 ** Two of the file mapping APIs are different under WinRT.  Figure out which
30211 ** set we need.
30212 */
30213 #if SQLITE_OS_WINRT
30214 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
30215         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
30216 
30217 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
30218 #else
30219 #if defined(SQLITE_WIN32_HAS_ANSI)
30220 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
30221         DWORD, DWORD, DWORD, LPCSTR);
30222 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
30223 
30224 #if defined(SQLITE_WIN32_HAS_WIDE)
30225 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
30226         DWORD, DWORD, DWORD, LPCWSTR);
30227 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
30228 
30229 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
30230 #endif /* SQLITE_OS_WINRT */
30231 
30232 /*
30233 ** This file mapping API is common to both Win32 and WinRT.
30234 */
30235 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30236 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30237 
30238 /*
30239 ** Macro to find the minimum of two numeric values.
30240 */
30241 #ifndef MIN
30242 # define MIN(x,y) ((x)<(y)?(x):(y))
30243 #endif
30244 
30245 /*
30246 ** Some Microsoft compilers lack this definition.
30247 */
30248 #ifndef INVALID_FILE_ATTRIBUTES
30249 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
30250 #endif
30251 
30252 #ifndef FILE_FLAG_MASK
30253 # define FILE_FLAG_MASK          (0xFF3C0000)
30254 #endif
30255 
30256 #ifndef FILE_ATTRIBUTE_MASK
30257 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
30258 #endif
30259 
30260 #ifndef SQLITE_OMIT_WAL
30261 /* Forward references */
30262 typedef struct winShm winShm;           /* A connection to shared-memory */
30263 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
30264 #endif
30265 
30266 /*
30267 ** WinCE lacks native support for file locking so we have to fake it
30268 ** with some code of our own.
30269 */
30270 #if SQLITE_OS_WINCE
30271 typedef struct winceLock {
30272   int nReaders;       /* Number of reader locks obtained */
30273   BOOL bPending;      /* Indicates a pending lock has been obtained */
30274   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
30275   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
30276 } winceLock;
30277 #endif
30278 
30279 /*
30280 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
30281 ** portability layer.
30282 */
30283 typedef struct winFile winFile;
30284 struct winFile {
30285   const sqlite3_io_methods *pMethod; /*** Must be first ***/
30286   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
30287   HANDLE h;               /* Handle for accessing the file */
30288   u8 locktype;            /* Type of lock currently held on this file */
30289   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
30290   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
30291   DWORD lastErrno;        /* The Windows errno from the last I/O error */
30292 #ifndef SQLITE_OMIT_WAL
30293   winShm *pShm;           /* Instance of shared memory on this file */
30294 #endif
30295   const char *zPath;      /* Full pathname of this file */
30296   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
30297 #if SQLITE_OS_WINCE
30298   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
30299   HANDLE hMutex;          /* Mutex used to control access to shared lock */
30300   HANDLE hShared;         /* Shared memory segment used for locking */
30301   winceLock local;        /* Locks obtained by this instance of winFile */
30302   winceLock *shared;      /* Global shared lock memory for the file  */
30303 #endif
30304 };
30305 
30306 /*
30307 ** Allowed values for winFile.ctrlFlags
30308 */
30309 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
30310 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30311 
30312 /*
30313  * The size of the buffer used by sqlite3_win32_write_debug().
30314  */
30315 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
30316 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
30317 #endif
30318 
30319 /*
30320  * The value used with sqlite3_win32_set_directory() to specify that
30321  * the data directory should be changed.
30322  */
30323 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
30324 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
30325 #endif
30326 
30327 /*
30328  * The value used with sqlite3_win32_set_directory() to specify that
30329  * the temporary directory should be changed.
30330  */
30331 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
30332 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
30333 #endif
30334 
30335 /*
30336  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
30337  * various Win32 API heap functions instead of our own.
30338  */
30339 #ifdef SQLITE_WIN32_MALLOC
30340 
30341 /*
30342  * If this is non-zero, an isolated heap will be created by the native Win32
30343  * allocator subsystem; otherwise, the default process heap will be used.  This
30344  * setting has no effect when compiling for WinRT.  By default, this is enabled
30345  * and an isolated heap will be created to store all allocated data.
30346  *
30347  ******************************************************************************
30348  * WARNING: It is important to note that when this setting is non-zero and the
30349  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
30350  *          function), all data that was allocated using the isolated heap will
30351  *          be freed immediately and any attempt to access any of that freed
30352  *          data will almost certainly result in an immediate access violation.
30353  ******************************************************************************
30354  */
30355 #ifndef SQLITE_WIN32_HEAP_CREATE
30356 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
30357 #endif
30358 
30359 /*
30360  * The initial size of the Win32-specific heap.  This value may be zero.
30361  */
30362 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30363 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30364                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30365 #endif
30366 
30367 /*
30368  * The maximum size of the Win32-specific heap.  This value may be zero.
30369  */
30370 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30371 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
30372 #endif
30373 
30374 /*
30375  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
30376  * zero for the default behavior.
30377  */
30378 #ifndef SQLITE_WIN32_HEAP_FLAGS
30379 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
30380 #endif
30381 
30382 /*
30383 ** The winMemData structure stores information required by the Win32-specific
30384 ** sqlite3_mem_methods implementation.
30385 */
30386 typedef struct winMemData winMemData;
30387 struct winMemData {
30388 #ifndef NDEBUG
30389   u32 magic;    /* Magic number to detect structure corruption. */
30390 #endif
30391   HANDLE hHeap; /* The handle to our heap. */
30392   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
30393 };
30394 
30395 #ifndef NDEBUG
30396 #define WINMEM_MAGIC     0x42b2830b
30397 #endif
30398 
30399 static struct winMemData win_mem_data = {
30400 #ifndef NDEBUG
30401   WINMEM_MAGIC,
30402 #endif
30403   NULL, FALSE
30404 };
30405 
30406 #ifndef NDEBUG
30407 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30408 #else
30409 #define winMemAssertMagic()
30410 #endif
30411 
30412 #define winMemGetHeap() win_mem_data.hHeap
30413 
30414 static void *winMemMalloc(int nBytes);
30415 static void winMemFree(void *pPrior);
30416 static void *winMemRealloc(void *pPrior, int nBytes);
30417 static int winMemSize(void *p);
30418 static int winMemRoundup(int n);
30419 static int winMemInit(void *pAppData);
30420 static void winMemShutdown(void *pAppData);
30421 
30422 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
30423 #endif /* SQLITE_WIN32_MALLOC */
30424 
30425 /*
30426 ** The following variable is (normally) set once and never changes
30427 ** thereafter.  It records whether the operating system is Win9x
30428 ** or WinNT.
30429 **
30430 ** 0:   Operating system unknown.
30431 ** 1:   Operating system is Win9x.
30432 ** 2:   Operating system is WinNT.
30433 **
30434 ** In order to facilitate testing on a WinNT system, the test fixture
30435 ** can manually set this value to 1 to emulate Win98 behavior.
30436 */
30437 #ifdef SQLITE_TEST
30438 SQLITE_API int sqlite3_os_type = 0;
30439 #else
30440 static int sqlite3_os_type = 0;
30441 #endif
30442 
30443 #ifndef SYSCALL
30444 #  define SYSCALL sqlite3_syscall_ptr
30445 #endif
30446 
30447 /*
30448 ** This function is not available on Windows CE or WinRT.
30449  */
30450 
30451 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
30452 #  define osAreFileApisANSI()       1
30453 #endif
30454 
30455 /*
30456 ** Many system calls are accessed through pointer-to-functions so that
30457 ** they may be overridden at runtime to facilitate fault injection during
30458 ** testing and sandboxing.  The following array holds the names and pointers
30459 ** to all overrideable system calls.
30460 */
30461 static struct win_syscall {
30462   const char *zName;            /* Name of the system call */
30463   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30464   sqlite3_syscall_ptr pDefault; /* Default value */
30465 } aSyscall[] = {
30466 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30467   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
30468 #else
30469   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
30470 #endif
30471 
30472 #ifndef osAreFileApisANSI
30473 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
30474 #endif
30475 
30476 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30477   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
30478 #else
30479   { "CharLowerW",              (SYSCALL)0,                       0 },
30480 #endif
30481 
30482 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
30483 
30484 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
30485   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
30486 #else
30487   { "CharUpperW",              (SYSCALL)0,                       0 },
30488 #endif
30489 
30490 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
30491 
30492   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
30493 
30494 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
30495 
30496 #if defined(SQLITE_WIN32_HAS_ANSI)
30497   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
30498 #else
30499   { "CreateFileA",             (SYSCALL)0,                       0 },
30500 #endif
30501 
30502 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
30503         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
30504 
30505 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30506   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
30507 #else
30508   { "CreateFileW",             (SYSCALL)0,                       0 },
30509 #endif
30510 
30511 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
30512         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
30513 
30514 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
30515         !defined(SQLITE_OMIT_WAL))
30516   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
30517 #else
30518   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
30519 #endif
30520 
30521 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30522         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
30523 
30524 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30525         !defined(SQLITE_OMIT_WAL))
30526   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
30527 #else
30528   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
30529 #endif
30530 
30531 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
30532         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
30533 
30534 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30535   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
30536 #else
30537   { "CreateMutexW",            (SYSCALL)0,                       0 },
30538 #endif
30539 
30540 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
30541         LPCWSTR))aSyscall[8].pCurrent)
30542 
30543 #if defined(SQLITE_WIN32_HAS_ANSI)
30544   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
30545 #else
30546   { "DeleteFileA",             (SYSCALL)0,                       0 },
30547 #endif
30548 
30549 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
30550 
30551 #if defined(SQLITE_WIN32_HAS_WIDE)
30552   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
30553 #else
30554   { "DeleteFileW",             (SYSCALL)0,                       0 },
30555 #endif
30556 
30557 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
30558 
30559 #if SQLITE_OS_WINCE
30560   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
30561 #else
30562   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
30563 #endif
30564 
30565 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30566         LPFILETIME))aSyscall[11].pCurrent)
30567 
30568 #if SQLITE_OS_WINCE
30569   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
30570 #else
30571   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
30572 #endif
30573 
30574 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
30575         LPSYSTEMTIME))aSyscall[12].pCurrent)
30576 
30577   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
30578 
30579 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
30580 
30581 #if defined(SQLITE_WIN32_HAS_ANSI)
30582   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
30583 #else
30584   { "FormatMessageA",          (SYSCALL)0,                       0 },
30585 #endif
30586 
30587 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
30588         DWORD,va_list*))aSyscall[14].pCurrent)
30589 
30590 #if defined(SQLITE_WIN32_HAS_WIDE)
30591   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
30592 #else
30593   { "FormatMessageW",          (SYSCALL)0,                       0 },
30594 #endif
30595 
30596 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
30597         DWORD,va_list*))aSyscall[15].pCurrent)
30598 
30599 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
30600   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
30601 #else
30602   { "FreeLibrary",             (SYSCALL)0,                       0 },
30603 #endif
30604 
30605 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
30606 
30607   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
30608 
30609 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
30610 
30611 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30612   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
30613 #else
30614   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
30615 #endif
30616 
30617 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
30618         LPDWORD))aSyscall[18].pCurrent)
30619 
30620 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30621   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
30622 #else
30623   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
30624 #endif
30625 
30626 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
30627         LPDWORD))aSyscall[19].pCurrent)
30628 
30629 #if defined(SQLITE_WIN32_HAS_ANSI)
30630   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
30631 #else
30632   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
30633 #endif
30634 
30635 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
30636 
30637 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30638   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
30639 #else
30640   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
30641 #endif
30642 
30643 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
30644 
30645 #if defined(SQLITE_WIN32_HAS_WIDE)
30646   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
30647 #else
30648   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
30649 #endif
30650 
30651 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
30652         LPVOID))aSyscall[22].pCurrent)
30653 
30654 #if !SQLITE_OS_WINRT
30655   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
30656 #else
30657   { "GetFileSize",             (SYSCALL)0,                       0 },
30658 #endif
30659 
30660 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
30661 
30662 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
30663   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
30664 #else
30665   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
30666 #endif
30667 
30668 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
30669         LPSTR*))aSyscall[24].pCurrent)
30670 
30671 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30672   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
30673 #else
30674   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
30675 #endif
30676 
30677 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
30678         LPWSTR*))aSyscall[25].pCurrent)
30679 
30680   { "GetLastError",            (SYSCALL)GetLastError,            0 },
30681 
30682 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
30683 
30684 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
30685 #if SQLITE_OS_WINCE
30686   /* The GetProcAddressA() routine is only available on Windows CE. */
30687   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
30688 #else
30689   /* All other Windows platforms expect GetProcAddress() to take
30690   ** an ANSI string regardless of the _UNICODE setting */
30691   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
30692 #endif
30693 #else
30694   { "GetProcAddressA",         (SYSCALL)0,                       0 },
30695 #endif
30696 
30697 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
30698         LPCSTR))aSyscall[27].pCurrent)
30699 
30700 #if !SQLITE_OS_WINRT
30701   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
30702 #else
30703   { "GetSystemInfo",           (SYSCALL)0,                       0 },
30704 #endif
30705 
30706 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
30707 
30708   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
30709 
30710 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
30711 
30712 #if !SQLITE_OS_WINCE
30713   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
30714 #else
30715   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
30716 #endif
30717 
30718 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
30719         LPFILETIME))aSyscall[30].pCurrent)
30720 
30721 #if defined(SQLITE_WIN32_HAS_ANSI)
30722   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
30723 #else
30724   { "GetTempPathA",            (SYSCALL)0,                       0 },
30725 #endif
30726 
30727 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
30728 
30729 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
30730   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
30731 #else
30732   { "GetTempPathW",            (SYSCALL)0,                       0 },
30733 #endif
30734 
30735 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
30736 
30737 #if !SQLITE_OS_WINRT
30738   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
30739 #else
30740   { "GetTickCount",            (SYSCALL)0,                       0 },
30741 #endif
30742 
30743 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
30744 
30745 #if defined(SQLITE_WIN32_HAS_ANSI)
30746   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
30747 #else
30748   { "GetVersionExA",           (SYSCALL)0,                       0 },
30749 #endif
30750 
30751 #define osGetVersionExA ((BOOL(WINAPI*)( \
30752         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
30753 
30754   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
30755 
30756 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
30757         SIZE_T))aSyscall[35].pCurrent)
30758 
30759 #if !SQLITE_OS_WINRT
30760   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
30761 #else
30762   { "HeapCreate",              (SYSCALL)0,                       0 },
30763 #endif
30764 
30765 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
30766         SIZE_T))aSyscall[36].pCurrent)
30767 
30768 #if !SQLITE_OS_WINRT
30769   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
30770 #else
30771   { "HeapDestroy",             (SYSCALL)0,                       0 },
30772 #endif
30773 
30774 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
30775 
30776   { "HeapFree",                (SYSCALL)HeapFree,                0 },
30777 
30778 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
30779 
30780   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
30781 
30782 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
30783         SIZE_T))aSyscall[39].pCurrent)
30784 
30785   { "HeapSize",                (SYSCALL)HeapSize,                0 },
30786 
30787 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
30788         LPCVOID))aSyscall[40].pCurrent)
30789 
30790 #if !SQLITE_OS_WINRT
30791   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
30792 #else
30793   { "HeapValidate",            (SYSCALL)0,                       0 },
30794 #endif
30795 
30796 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
30797         LPCVOID))aSyscall[41].pCurrent)
30798 
30799 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
30800   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
30801 #else
30802   { "LoadLibraryA",            (SYSCALL)0,                       0 },
30803 #endif
30804 
30805 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
30806 
30807 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
30808         !defined(SQLITE_OMIT_LOAD_EXTENSION)
30809   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
30810 #else
30811   { "LoadLibraryW",            (SYSCALL)0,                       0 },
30812 #endif
30813 
30814 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
30815 
30816 #if !SQLITE_OS_WINRT
30817   { "LocalFree",               (SYSCALL)LocalFree,               0 },
30818 #else
30819   { "LocalFree",               (SYSCALL)0,                       0 },
30820 #endif
30821 
30822 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
30823 
30824 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30825   { "LockFile",                (SYSCALL)LockFile,                0 },
30826 #else
30827   { "LockFile",                (SYSCALL)0,                       0 },
30828 #endif
30829 
30830 #ifndef osLockFile
30831 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30832         DWORD))aSyscall[45].pCurrent)
30833 #endif
30834 
30835 #if !SQLITE_OS_WINCE
30836   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
30837 #else
30838   { "LockFileEx",              (SYSCALL)0,                       0 },
30839 #endif
30840 
30841 #ifndef osLockFileEx
30842 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
30843         LPOVERLAPPED))aSyscall[46].pCurrent)
30844 #endif
30845 
30846 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
30847   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
30848 #else
30849   { "MapViewOfFile",           (SYSCALL)0,                       0 },
30850 #endif
30851 
30852 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30853         SIZE_T))aSyscall[47].pCurrent)
30854 
30855   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
30856 
30857 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
30858         int))aSyscall[48].pCurrent)
30859 
30860   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
30861 
30862 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
30863         LARGE_INTEGER*))aSyscall[49].pCurrent)
30864 
30865   { "ReadFile",                (SYSCALL)ReadFile,                0 },
30866 
30867 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
30868         LPOVERLAPPED))aSyscall[50].pCurrent)
30869 
30870   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
30871 
30872 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
30873 
30874 #if !SQLITE_OS_WINRT
30875   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
30876 #else
30877   { "SetFilePointer",          (SYSCALL)0,                       0 },
30878 #endif
30879 
30880 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
30881         DWORD))aSyscall[52].pCurrent)
30882 
30883 #if !SQLITE_OS_WINRT
30884   { "Sleep",                   (SYSCALL)Sleep,                   0 },
30885 #else
30886   { "Sleep",                   (SYSCALL)0,                       0 },
30887 #endif
30888 
30889 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
30890 
30891   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
30892 
30893 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
30894         LPFILETIME))aSyscall[54].pCurrent)
30895 
30896 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30897   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
30898 #else
30899   { "UnlockFile",              (SYSCALL)0,                       0 },
30900 #endif
30901 
30902 #ifndef osUnlockFile
30903 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30904         DWORD))aSyscall[55].pCurrent)
30905 #endif
30906 
30907 #if !SQLITE_OS_WINCE
30908   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
30909 #else
30910   { "UnlockFileEx",            (SYSCALL)0,                       0 },
30911 #endif
30912 
30913 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
30914         LPOVERLAPPED))aSyscall[56].pCurrent)
30915 
30916 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
30917   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
30918 #else
30919   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
30920 #endif
30921 
30922 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
30923 
30924   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
30925 
30926 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
30927         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
30928 
30929   { "WriteFile",               (SYSCALL)WriteFile,               0 },
30930 
30931 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
30932         LPOVERLAPPED))aSyscall[59].pCurrent)
30933 
30934 #if SQLITE_OS_WINRT
30935   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
30936 #else
30937   { "CreateEventExW",          (SYSCALL)0,                       0 },
30938 #endif
30939 
30940 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
30941         DWORD,DWORD))aSyscall[60].pCurrent)
30942 
30943 #if !SQLITE_OS_WINRT
30944   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
30945 #else
30946   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
30947 #endif
30948 
30949 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
30950         DWORD))aSyscall[61].pCurrent)
30951 
30952 #if SQLITE_OS_WINRT
30953   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
30954 #else
30955   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
30956 #endif
30957 
30958 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
30959         BOOL))aSyscall[62].pCurrent)
30960 
30961 #if SQLITE_OS_WINRT
30962   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
30963 #else
30964   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
30965 #endif
30966 
30967 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
30968         PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
30969 
30970 #if SQLITE_OS_WINRT
30971   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
30972 #else
30973   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
30974 #endif
30975 
30976 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
30977         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
30978 
30979 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
30980   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
30981 #else
30982   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
30983 #endif
30984 
30985 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
30986         SIZE_T))aSyscall[65].pCurrent)
30987 
30988 #if SQLITE_OS_WINRT
30989   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
30990 #else
30991   { "CreateFile2",             (SYSCALL)0,                       0 },
30992 #endif
30993 
30994 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
30995         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
30996 
30997 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
30998   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
30999 #else
31000   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
31001 #endif
31002 
31003 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
31004         DWORD))aSyscall[67].pCurrent)
31005 
31006 #if SQLITE_OS_WINRT
31007   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
31008 #else
31009   { "GetTickCount64",          (SYSCALL)0,                       0 },
31010 #endif
31011 
31012 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
31013 
31014 #if SQLITE_OS_WINRT
31015   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
31016 #else
31017   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
31018 #endif
31019 
31020 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
31021         LPSYSTEM_INFO))aSyscall[69].pCurrent)
31022 
31023 #if defined(SQLITE_WIN32_HAS_ANSI)
31024   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
31025 #else
31026   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
31027 #endif
31028 
31029 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
31030 
31031 #if defined(SQLITE_WIN32_HAS_WIDE)
31032   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
31033 #else
31034   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
31035 #endif
31036 
31037 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
31038 
31039   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
31040 
31041 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
31042 
31043 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31044   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
31045 #else
31046   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
31047 #endif
31048 
31049 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
31050         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
31051 
31052 }; /* End of the overrideable system calls */
31053 
31054 /*
31055 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
31056 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
31057 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
31058 ** system call named zName.
31059 */
31060 static int winSetSystemCall(
31061   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
31062   const char *zName,            /* Name of system call to override */
31063   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
31064 ){
31065   unsigned int i;
31066   int rc = SQLITE_NOTFOUND;
31067 
31068   UNUSED_PARAMETER(pNotUsed);
31069   if( zName==0 ){
31070     /* If no zName is given, restore all system calls to their default
31071     ** settings and return NULL
31072     */
31073     rc = SQLITE_OK;
31074     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31075       if( aSyscall[i].pDefault ){
31076         aSyscall[i].pCurrent = aSyscall[i].pDefault;
31077       }
31078     }
31079   }else{
31080     /* If zName is specified, operate on only the one system call
31081     ** specified.
31082     */
31083     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31084       if( strcmp(zName, aSyscall[i].zName)==0 ){
31085         if( aSyscall[i].pDefault==0 ){
31086           aSyscall[i].pDefault = aSyscall[i].pCurrent;
31087         }
31088         rc = SQLITE_OK;
31089         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
31090         aSyscall[i].pCurrent = pNewFunc;
31091         break;
31092       }
31093     }
31094   }
31095   return rc;
31096 }
31097 
31098 /*
31099 ** Return the value of a system call.  Return NULL if zName is not a
31100 ** recognized system call name.  NULL is also returned if the system call
31101 ** is currently undefined.
31102 */
31103 static sqlite3_syscall_ptr winGetSystemCall(
31104   sqlite3_vfs *pNotUsed,
31105   const char *zName
31106 ){
31107   unsigned int i;
31108 
31109   UNUSED_PARAMETER(pNotUsed);
31110   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31111     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
31112   }
31113   return 0;
31114 }
31115 
31116 /*
31117 ** Return the name of the first system call after zName.  If zName==NULL
31118 ** then return the name of the first system call.  Return NULL if zName
31119 ** is the last system call or if zName is not the name of a valid
31120 ** system call.
31121 */
31122 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
31123   int i = -1;
31124 
31125   UNUSED_PARAMETER(p);
31126   if( zName ){
31127     for(i=0; i<ArraySize(aSyscall)-1; i++){
31128       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31129     }
31130   }
31131   for(i++; i<ArraySize(aSyscall); i++){
31132     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31133   }
31134   return 0;
31135 }
31136 
31137 /*
31138 ** This function outputs the specified (ANSI) string to the Win32 debugger
31139 ** (if available).
31140 */
31141 
31142 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
31143   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
31144   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
31145   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
31146   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
31147 #if defined(SQLITE_WIN32_HAS_ANSI)
31148   if( nMin>0 ){
31149     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31150     memcpy(zDbgBuf, zBuf, nMin);
31151     osOutputDebugStringA(zDbgBuf);
31152   }else{
31153     osOutputDebugStringA(zBuf);
31154   }
31155 #elif defined(SQLITE_WIN32_HAS_WIDE)
31156   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31157   if ( osMultiByteToWideChar(
31158           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
31159           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
31160     return;
31161   }
31162   osOutputDebugStringW((LPCWSTR)zDbgBuf);
31163 #else
31164   if( nMin>0 ){
31165     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31166     memcpy(zDbgBuf, zBuf, nMin);
31167     fprintf(stderr, "%s", zDbgBuf);
31168   }else{
31169     fprintf(stderr, "%s", zBuf);
31170   }
31171 #endif
31172 }
31173 
31174 /*
31175 ** The following routine suspends the current thread for at least ms
31176 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
31177 */
31178 #if SQLITE_OS_WINRT
31179 static HANDLE sleepObj = NULL;
31180 #endif
31181 
31182 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
31183 #if SQLITE_OS_WINRT
31184   if ( sleepObj==NULL ){
31185     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
31186                                 SYNCHRONIZE);
31187   }
31188   assert( sleepObj!=NULL );
31189   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
31190 #else
31191   osSleep(milliseconds);
31192 #endif
31193 }
31194 
31195 /*
31196 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31197 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31198 **
31199 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31200 ** the LockFileEx() API.  But we can still statically link against that
31201 ** API as long as we don't call it when running Win95/98/ME.  A call to
31202 ** this routine is used to determine if the host is Win95/98/ME or
31203 ** WinNT/2K/XP so that we will know whether or not we can safely call
31204 ** the LockFileEx() API.
31205 */
31206 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31207 # define isNT()  (1)
31208 #elif !defined(SQLITE_WIN32_HAS_WIDE)
31209 # define isNT()  (0)
31210 #else
31211   static int isNT(void){
31212     if( sqlite3_os_type==0 ){
31213       OSVERSIONINFOA sInfo;
31214       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31215       osGetVersionExA(&sInfo);
31216       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31217     }
31218     return sqlite3_os_type==2;
31219   }
31220 #endif
31221 
31222 #ifdef SQLITE_WIN32_MALLOC
31223 /*
31224 ** Allocate nBytes of memory.
31225 */
31226 static void *winMemMalloc(int nBytes){
31227   HANDLE hHeap;
31228   void *p;
31229 
31230   winMemAssertMagic();
31231   hHeap = winMemGetHeap();
31232   assert( hHeap!=0 );
31233   assert( hHeap!=INVALID_HANDLE_VALUE );
31234 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31235   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31236 #endif
31237   assert( nBytes>=0 );
31238   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31239   if( !p ){
31240     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31241                 nBytes, osGetLastError(), (void*)hHeap);
31242   }
31243   return p;
31244 }
31245 
31246 /*
31247 ** Free memory.
31248 */
31249 static void winMemFree(void *pPrior){
31250   HANDLE hHeap;
31251 
31252   winMemAssertMagic();
31253   hHeap = winMemGetHeap();
31254   assert( hHeap!=0 );
31255   assert( hHeap!=INVALID_HANDLE_VALUE );
31256 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31257   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31258 #endif
31259   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31260   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31261     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31262                 pPrior, osGetLastError(), (void*)hHeap);
31263   }
31264 }
31265 
31266 /*
31267 ** Change the size of an existing memory allocation
31268 */
31269 static void *winMemRealloc(void *pPrior, int nBytes){
31270   HANDLE hHeap;
31271   void *p;
31272 
31273   winMemAssertMagic();
31274   hHeap = winMemGetHeap();
31275   assert( hHeap!=0 );
31276   assert( hHeap!=INVALID_HANDLE_VALUE );
31277 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31278   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31279 #endif
31280   assert( nBytes>=0 );
31281   if( !pPrior ){
31282     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31283   }else{
31284     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31285   }
31286   if( !p ){
31287     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31288                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
31289                 (void*)hHeap);
31290   }
31291   return p;
31292 }
31293 
31294 /*
31295 ** Return the size of an outstanding allocation, in bytes.
31296 */
31297 static int winMemSize(void *p){
31298   HANDLE hHeap;
31299   SIZE_T n;
31300 
31301   winMemAssertMagic();
31302   hHeap = winMemGetHeap();
31303   assert( hHeap!=0 );
31304   assert( hHeap!=INVALID_HANDLE_VALUE );
31305 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31306   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31307 #endif
31308   if( !p ) return 0;
31309   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31310   if( n==(SIZE_T)-1 ){
31311     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31312                 p, osGetLastError(), (void*)hHeap);
31313     return 0;
31314   }
31315   return (int)n;
31316 }
31317 
31318 /*
31319 ** Round up a request size to the next valid allocation size.
31320 */
31321 static int winMemRoundup(int n){
31322   return n;
31323 }
31324 
31325 /*
31326 ** Initialize this module.
31327 */
31328 static int winMemInit(void *pAppData){
31329   winMemData *pWinMemData = (winMemData *)pAppData;
31330 
31331   if( !pWinMemData ) return SQLITE_ERROR;
31332   assert( pWinMemData->magic==WINMEM_MAGIC );
31333 
31334 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
31335   if( !pWinMemData->hHeap ){
31336     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31337                                       SQLITE_WIN32_HEAP_INIT_SIZE,
31338                                       SQLITE_WIN32_HEAP_MAX_SIZE);
31339     if( !pWinMemData->hHeap ){
31340       sqlite3_log(SQLITE_NOMEM,
31341           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31342           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
31343           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
31344       return SQLITE_NOMEM;
31345     }
31346     pWinMemData->bOwned = TRUE;
31347     assert( pWinMemData->bOwned );
31348   }
31349 #else
31350   pWinMemData->hHeap = osGetProcessHeap();
31351   if( !pWinMemData->hHeap ){
31352     sqlite3_log(SQLITE_NOMEM,
31353         "failed to GetProcessHeap (%d)", osGetLastError());
31354     return SQLITE_NOMEM;
31355   }
31356   pWinMemData->bOwned = FALSE;
31357   assert( !pWinMemData->bOwned );
31358 #endif
31359   assert( pWinMemData->hHeap!=0 );
31360   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31361 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31362   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31363 #endif
31364   return SQLITE_OK;
31365 }
31366 
31367 /*
31368 ** Deinitialize this module.
31369 */
31370 static void winMemShutdown(void *pAppData){
31371   winMemData *pWinMemData = (winMemData *)pAppData;
31372 
31373   if( !pWinMemData ) return;
31374   if( pWinMemData->hHeap ){
31375     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31376 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31377     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31378 #endif
31379     if( pWinMemData->bOwned ){
31380       if( !osHeapDestroy(pWinMemData->hHeap) ){
31381         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31382                     osGetLastError(), (void*)pWinMemData->hHeap);
31383       }
31384       pWinMemData->bOwned = FALSE;
31385     }
31386     pWinMemData->hHeap = NULL;
31387   }
31388 }
31389 
31390 /*
31391 ** Populate the low-level memory allocation function pointers in
31392 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31393 ** arguments specify the block of memory to manage.
31394 **
31395 ** This routine is only called by sqlite3_config(), and therefore
31396 ** is not required to be threadsafe (it is not).
31397 */
31398 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31399   static const sqlite3_mem_methods winMemMethods = {
31400     winMemMalloc,
31401     winMemFree,
31402     winMemRealloc,
31403     winMemSize,
31404     winMemRoundup,
31405     winMemInit,
31406     winMemShutdown,
31407     &win_mem_data
31408   };
31409   return &winMemMethods;
31410 }
31411 
31412 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31413   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31414 }
31415 #endif /* SQLITE_WIN32_MALLOC */
31416 
31417 /*
31418 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
31419 **
31420 ** Space to hold the returned string is obtained from malloc.
31421 */
31422 static LPWSTR utf8ToUnicode(const char *zFilename){
31423   int nChar;
31424   LPWSTR zWideFilename;
31425 
31426   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31427   if( nChar==0 ){
31428     return 0;
31429   }
31430   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
31431   if( zWideFilename==0 ){
31432     return 0;
31433   }
31434   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
31435                                 nChar);
31436   if( nChar==0 ){
31437     sqlite3_free(zWideFilename);
31438     zWideFilename = 0;
31439   }
31440   return zWideFilename;
31441 }
31442 
31443 /*
31444 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
31445 ** obtained from sqlite3_malloc().
31446 */
31447 static char *unicodeToUtf8(LPCWSTR zWideFilename){
31448   int nByte;
31449   char *zFilename;
31450 
31451   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31452   if( nByte == 0 ){
31453     return 0;
31454   }
31455   zFilename = sqlite3MallocZero( nByte );
31456   if( zFilename==0 ){
31457     return 0;
31458   }
31459   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31460                                 0, 0);
31461   if( nByte == 0 ){
31462     sqlite3_free(zFilename);
31463     zFilename = 0;
31464   }
31465   return zFilename;
31466 }
31467 
31468 /*
31469 ** Convert an ANSI string to Microsoft Unicode, based on the
31470 ** current codepage settings for file apis.
31471 **
31472 ** Space to hold the returned string is obtained
31473 ** from sqlite3_malloc.
31474 */
31475 static LPWSTR mbcsToUnicode(const char *zFilename){
31476   int nByte;
31477   LPWSTR zMbcsFilename;
31478   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31479 
31480   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
31481                                 0)*sizeof(WCHAR);
31482   if( nByte==0 ){
31483     return 0;
31484   }
31485   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
31486   if( zMbcsFilename==0 ){
31487     return 0;
31488   }
31489   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
31490                                 nByte);
31491   if( nByte==0 ){
31492     sqlite3_free(zMbcsFilename);
31493     zMbcsFilename = 0;
31494   }
31495   return zMbcsFilename;
31496 }
31497 
31498 /*
31499 ** Convert Microsoft Unicode to multi-byte character string, based on the
31500 ** user's ANSI codepage.
31501 **
31502 ** Space to hold the returned string is obtained from
31503 ** sqlite3_malloc().
31504 */
31505 static char *unicodeToMbcs(LPCWSTR zWideFilename){
31506   int nByte;
31507   char *zFilename;
31508   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
31509 
31510   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31511   if( nByte == 0 ){
31512     return 0;
31513   }
31514   zFilename = sqlite3MallocZero( nByte );
31515   if( zFilename==0 ){
31516     return 0;
31517   }
31518   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
31519                                 nByte, 0, 0);
31520   if( nByte == 0 ){
31521     sqlite3_free(zFilename);
31522     zFilename = 0;
31523   }
31524   return zFilename;
31525 }
31526 
31527 /*
31528 ** Convert multibyte character string to UTF-8.  Space to hold the
31529 ** returned string is obtained from sqlite3_malloc().
31530 */
31531 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31532   char *zFilenameUtf8;
31533   LPWSTR zTmpWide;
31534 
31535   zTmpWide = mbcsToUnicode(zFilename);
31536   if( zTmpWide==0 ){
31537     return 0;
31538   }
31539   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31540   sqlite3_free(zTmpWide);
31541   return zFilenameUtf8;
31542 }
31543 
31544 /*
31545 ** Convert UTF-8 to multibyte character string.  Space to hold the
31546 ** returned string is obtained from sqlite3_malloc().
31547 */
31548 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
31549   char *zFilenameMbcs;
31550   LPWSTR zTmpWide;
31551 
31552   zTmpWide = utf8ToUnicode(zFilename);
31553   if( zTmpWide==0 ){
31554     return 0;
31555   }
31556   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31557   sqlite3_free(zTmpWide);
31558   return zFilenameMbcs;
31559 }
31560 
31561 /*
31562 ** This function sets the data directory or the temporary directory based on
31563 ** the provided arguments.  The type argument must be 1 in order to set the
31564 ** data directory or 2 in order to set the temporary directory.  The zValue
31565 ** argument is the name of the directory to use.  The return value will be
31566 ** SQLITE_OK if successful.
31567 */
31568 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
31569   char **ppDirectory = 0;
31570 #ifndef SQLITE_OMIT_AUTOINIT
31571   int rc = sqlite3_initialize();
31572   if( rc ) return rc;
31573 #endif
31574   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
31575     ppDirectory = &sqlite3_data_directory;
31576   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
31577     ppDirectory = &sqlite3_temp_directory;
31578   }
31579   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
31580           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31581   );
31582   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
31583   if( ppDirectory ){
31584     char *zValueUtf8 = 0;
31585     if( zValue && zValue[0] ){
31586       zValueUtf8 = unicodeToUtf8(zValue);
31587       if ( zValueUtf8==0 ){
31588         return SQLITE_NOMEM;
31589       }
31590     }
31591     sqlite3_free(*ppDirectory);
31592     *ppDirectory = zValueUtf8;
31593     return SQLITE_OK;
31594   }
31595   return SQLITE_ERROR;
31596 }
31597 
31598 /*
31599 ** The return value of getLastErrorMsg
31600 ** is zero if the error message fits in the buffer, or non-zero
31601 ** otherwise (if the message was truncated).
31602 */
31603 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
31604   /* FormatMessage returns 0 on failure.  Otherwise it
31605   ** returns the number of TCHARs written to the output
31606   ** buffer, excluding the terminating null char.
31607   */
31608   DWORD dwLen = 0;
31609   char *zOut = 0;
31610 
31611   if( isNT() ){
31612 #if SQLITE_OS_WINRT
31613     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
31614     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
31615                              FORMAT_MESSAGE_IGNORE_INSERTS,
31616                              NULL,
31617                              lastErrno,
31618                              0,
31619                              zTempWide,
31620                              MAX_PATH,
31621                              0);
31622 #else
31623     LPWSTR zTempWide = NULL;
31624     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31625                              FORMAT_MESSAGE_FROM_SYSTEM |
31626                              FORMAT_MESSAGE_IGNORE_INSERTS,
31627                              NULL,
31628                              lastErrno,
31629                              0,
31630                              (LPWSTR) &zTempWide,
31631                              0,
31632                              0);
31633 #endif
31634     if( dwLen > 0 ){
31635       /* allocate a buffer and convert to UTF8 */
31636       sqlite3BeginBenignMalloc();
31637       zOut = unicodeToUtf8(zTempWide);
31638       sqlite3EndBenignMalloc();
31639 #if !SQLITE_OS_WINRT
31640       /* free the system buffer allocated by FormatMessage */
31641       osLocalFree(zTempWide);
31642 #endif
31643     }
31644   }
31645 #ifdef SQLITE_WIN32_HAS_ANSI
31646   else{
31647     char *zTemp = NULL;
31648     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
31649                              FORMAT_MESSAGE_FROM_SYSTEM |
31650                              FORMAT_MESSAGE_IGNORE_INSERTS,
31651                              NULL,
31652                              lastErrno,
31653                              0,
31654                              (LPSTR) &zTemp,
31655                              0,
31656                              0);
31657     if( dwLen > 0 ){
31658       /* allocate a buffer and convert to UTF8 */
31659       sqlite3BeginBenignMalloc();
31660       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31661       sqlite3EndBenignMalloc();
31662       /* free the system buffer allocated by FormatMessage */
31663       osLocalFree(zTemp);
31664     }
31665   }
31666 #endif
31667   if( 0 == dwLen ){
31668     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
31669   }else{
31670     /* copy a maximum of nBuf chars to output buffer */
31671     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31672     /* free the UTF8 buffer */
31673     sqlite3_free(zOut);
31674   }
31675   return 0;
31676 }
31677 
31678 /*
31679 **
31680 ** This function - winLogErrorAtLine() - is only ever called via the macro
31681 ** winLogError().
31682 **
31683 ** This routine is invoked after an error occurs in an OS function.
31684 ** It logs a message using sqlite3_log() containing the current value of
31685 ** error code and, if possible, the human-readable equivalent from
31686 ** FormatMessage.
31687 **
31688 ** The first argument passed to the macro should be the error code that
31689 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
31690 ** The two subsequent arguments should be the name of the OS function that
31691 ** failed and the associated file-system path, if any.
31692 */
31693 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
31694 static int winLogErrorAtLine(
31695   int errcode,                    /* SQLite error code */
31696   DWORD lastErrno,                /* Win32 last error */
31697   const char *zFunc,              /* Name of OS function that failed */
31698   const char *zPath,              /* File path associated with error */
31699   int iLine                       /* Source line number where error occurred */
31700 ){
31701   char zMsg[500];                 /* Human readable error text */
31702   int i;                          /* Loop counter */
31703 
31704   zMsg[0] = 0;
31705   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
31706   assert( errcode!=SQLITE_OK );
31707   if( zPath==0 ) zPath = "";
31708   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
31709   zMsg[i] = 0;
31710   sqlite3_log(errcode,
31711       "os_win.c:%d: (%d) %s(%s) - %s",
31712       iLine, lastErrno, zFunc, zPath, zMsg
31713   );
31714 
31715   return errcode;
31716 }
31717 
31718 /*
31719 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
31720 ** will be retried following a locking error - probably caused by
31721 ** antivirus software.  Also the initial delay before the first retry.
31722 ** The delay increases linearly with each retry.
31723 */
31724 #ifndef SQLITE_WIN32_IOERR_RETRY
31725 # define SQLITE_WIN32_IOERR_RETRY 10
31726 #endif
31727 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
31728 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
31729 #endif
31730 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
31731 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
31732 
31733 /*
31734 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
31735 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
31736 ** to give up with an error.
31737 */
31738 static int retryIoerr(int *pnRetry, DWORD *pError){
31739   DWORD e = osGetLastError();
31740   if( *pnRetry>=win32IoerrRetry ){
31741     if( pError ){
31742       *pError = e;
31743     }
31744     return 0;
31745   }
31746   if( e==ERROR_ACCESS_DENIED ||
31747       e==ERROR_LOCK_VIOLATION ||
31748       e==ERROR_SHARING_VIOLATION ){
31749     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
31750     ++*pnRetry;
31751     return 1;
31752   }
31753   if( pError ){
31754     *pError = e;
31755   }
31756   return 0;
31757 }
31758 
31759 /*
31760 ** Log a I/O error retry episode.
31761 */
31762 static void logIoerr(int nRetry){
31763   if( nRetry ){
31764     sqlite3_log(SQLITE_IOERR,
31765       "delayed %dms for lock/sharing conflict",
31766       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
31767     );
31768   }
31769 }
31770 
31771 #if SQLITE_OS_WINCE
31772 /*************************************************************************
31773 ** This section contains code for WinCE only.
31774 */
31775 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
31776 /*
31777 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
31778 ** create a substitute.
31779 */
31780 /* #include <time.h> */
31781 struct tm *__cdecl localtime(const time_t *t)
31782 {
31783   static struct tm y;
31784   FILETIME uTm, lTm;
31785   SYSTEMTIME pTm;
31786   sqlite3_int64 t64;
31787   t64 = *t;
31788   t64 = (t64 + 11644473600)*10000000;
31789   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31790   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31791   osFileTimeToLocalFileTime(&uTm,&lTm);
31792   osFileTimeToSystemTime(&lTm,&pTm);
31793   y.tm_year = pTm.wYear - 1900;
31794   y.tm_mon = pTm.wMonth - 1;
31795   y.tm_wday = pTm.wDayOfWeek;
31796   y.tm_mday = pTm.wDay;
31797   y.tm_hour = pTm.wHour;
31798   y.tm_min = pTm.wMinute;
31799   y.tm_sec = pTm.wSecond;
31800   return &y;
31801 }
31802 #endif
31803 
31804 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31805 
31806 /*
31807 ** Acquire a lock on the handle h
31808 */
31809 static void winceMutexAcquire(HANDLE h){
31810    DWORD dwErr;
31811    do {
31812      dwErr = osWaitForSingleObject(h, INFINITE);
31813    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31814 }
31815 /*
31816 ** Release a lock acquired by winceMutexAcquire()
31817 */
31818 #define winceMutexRelease(h) ReleaseMutex(h)
31819 
31820 /*
31821 ** Create the mutex and shared memory used for locking in the file
31822 ** descriptor pFile
31823 */
31824 static int winceCreateLock(const char *zFilename, winFile *pFile){
31825   LPWSTR zTok;
31826   LPWSTR zName;
31827   DWORD lastErrno;
31828   BOOL bLogged = FALSE;
31829   BOOL bInit = TRUE;
31830 
31831   zName = utf8ToUnicode(zFilename);
31832   if( zName==0 ){
31833     /* out of memory */
31834     return SQLITE_IOERR_NOMEM;
31835   }
31836 
31837   /* Initialize the local lockdata */
31838   memset(&pFile->local, 0, sizeof(pFile->local));
31839 
31840   /* Replace the backslashes from the filename and lowercase it
31841   ** to derive a mutex name. */
31842   zTok = osCharLowerW(zName);
31843   for (;*zTok;zTok++){
31844     if (*zTok == '\\') *zTok = '_';
31845   }
31846 
31847   /* Create/open the named mutex */
31848   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
31849   if (!pFile->hMutex){
31850     pFile->lastErrno = osGetLastError();
31851     winLogError(SQLITE_IOERR, pFile->lastErrno,
31852                 "winceCreateLock1", zFilename);
31853     sqlite3_free(zName);
31854     return SQLITE_IOERR;
31855   }
31856 
31857   /* Acquire the mutex before continuing */
31858   winceMutexAcquire(pFile->hMutex);
31859 
31860   /* Since the names of named mutexes, semaphores, file mappings etc are
31861   ** case-sensitive, take advantage of that by uppercasing the mutex name
31862   ** and using that as the shared filemapping name.
31863   */
31864   osCharUpperW(zName);
31865   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31866                                         PAGE_READWRITE, 0, sizeof(winceLock),
31867                                         zName);
31868 
31869   /* Set a flag that indicates we're the first to create the memory so it
31870   ** must be zero-initialized */
31871   lastErrno = osGetLastError();
31872   if (lastErrno == ERROR_ALREADY_EXISTS){
31873     bInit = FALSE;
31874   }
31875 
31876   sqlite3_free(zName);
31877 
31878   /* If we succeeded in making the shared memory handle, map it. */
31879   if( pFile->hShared ){
31880     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
31881              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31882     /* If mapping failed, close the shared memory handle and erase it */
31883     if( !pFile->shared ){
31884       pFile->lastErrno = osGetLastError();
31885       winLogError(SQLITE_IOERR, pFile->lastErrno,
31886                   "winceCreateLock2", zFilename);
31887       bLogged = TRUE;
31888       osCloseHandle(pFile->hShared);
31889       pFile->hShared = NULL;
31890     }
31891   }
31892 
31893   /* If shared memory could not be created, then close the mutex and fail */
31894   if( pFile->hShared==NULL ){
31895     if( !bLogged ){
31896       pFile->lastErrno = lastErrno;
31897       winLogError(SQLITE_IOERR, pFile->lastErrno,
31898                   "winceCreateLock3", zFilename);
31899       bLogged = TRUE;
31900     }
31901     winceMutexRelease(pFile->hMutex);
31902     osCloseHandle(pFile->hMutex);
31903     pFile->hMutex = NULL;
31904     return SQLITE_IOERR;
31905   }
31906 
31907   /* Initialize the shared memory if we're supposed to */
31908   if( bInit ){
31909     memset(pFile->shared, 0, sizeof(winceLock));
31910   }
31911 
31912   winceMutexRelease(pFile->hMutex);
31913   return SQLITE_OK;
31914 }
31915 
31916 /*
31917 ** Destroy the part of winFile that deals with wince locks
31918 */
31919 static void winceDestroyLock(winFile *pFile){
31920   if (pFile->hMutex){
31921     /* Acquire the mutex */
31922     winceMutexAcquire(pFile->hMutex);
31923 
31924     /* The following blocks should probably assert in debug mode, but they
31925        are to cleanup in case any locks remained open */
31926     if (pFile->local.nReaders){
31927       pFile->shared->nReaders --;
31928     }
31929     if (pFile->local.bReserved){
31930       pFile->shared->bReserved = FALSE;
31931     }
31932     if (pFile->local.bPending){
31933       pFile->shared->bPending = FALSE;
31934     }
31935     if (pFile->local.bExclusive){
31936       pFile->shared->bExclusive = FALSE;
31937     }
31938 
31939     /* De-reference and close our copy of the shared memory handle */
31940     osUnmapViewOfFile(pFile->shared);
31941     osCloseHandle(pFile->hShared);
31942 
31943     /* Done with the mutex */
31944     winceMutexRelease(pFile->hMutex);
31945     osCloseHandle(pFile->hMutex);
31946     pFile->hMutex = NULL;
31947   }
31948 }
31949 
31950 /*
31951 ** An implementation of the LockFile() API of Windows for CE
31952 */
31953 static BOOL winceLockFile(
31954   LPHANDLE phFile,
31955   DWORD dwFileOffsetLow,
31956   DWORD dwFileOffsetHigh,
31957   DWORD nNumberOfBytesToLockLow,
31958   DWORD nNumberOfBytesToLockHigh
31959 ){
31960   winFile *pFile = HANDLE_TO_WINFILE(phFile);
31961   BOOL bReturn = FALSE;
31962 
31963   UNUSED_PARAMETER(dwFileOffsetHigh);
31964   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
31965 
31966   if (!pFile->hMutex) return TRUE;
31967   winceMutexAcquire(pFile->hMutex);
31968 
31969   /* Wanting an exclusive lock? */
31970   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
31971        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
31972     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
31973        pFile->shared->bExclusive = TRUE;
31974        pFile->local.bExclusive = TRUE;
31975        bReturn = TRUE;
31976     }
31977   }
31978 
31979   /* Want a read-only lock? */
31980   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
31981            nNumberOfBytesToLockLow == 1){
31982     if (pFile->shared->bExclusive == 0){
31983       pFile->local.nReaders ++;
31984       if (pFile->local.nReaders == 1){
31985         pFile->shared->nReaders ++;
31986       }
31987       bReturn = TRUE;
31988     }
31989   }
31990 
31991   /* Want a pending lock? */
31992   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
31993            && nNumberOfBytesToLockLow == 1){
31994     /* If no pending lock has been acquired, then acquire it */
31995     if (pFile->shared->bPending == 0) {
31996       pFile->shared->bPending = TRUE;
31997       pFile->local.bPending = TRUE;
31998       bReturn = TRUE;
31999     }
32000   }
32001 
32002   /* Want a reserved lock? */
32003   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32004            && nNumberOfBytesToLockLow == 1){
32005     if (pFile->shared->bReserved == 0) {
32006       pFile->shared->bReserved = TRUE;
32007       pFile->local.bReserved = TRUE;
32008       bReturn = TRUE;
32009     }
32010   }
32011 
32012   winceMutexRelease(pFile->hMutex);
32013   return bReturn;
32014 }
32015 
32016 /*
32017 ** An implementation of the UnlockFile API of Windows for CE
32018 */
32019 static BOOL winceUnlockFile(
32020   LPHANDLE phFile,
32021   DWORD dwFileOffsetLow,
32022   DWORD dwFileOffsetHigh,
32023   DWORD nNumberOfBytesToUnlockLow,
32024   DWORD nNumberOfBytesToUnlockHigh
32025 ){
32026   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32027   BOOL bReturn = FALSE;
32028 
32029   UNUSED_PARAMETER(dwFileOffsetHigh);
32030   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32031 
32032   if (!pFile->hMutex) return TRUE;
32033   winceMutexAcquire(pFile->hMutex);
32034 
32035   /* Releasing a reader lock or an exclusive lock */
32036   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32037     /* Did we have an exclusive lock? */
32038     if (pFile->local.bExclusive){
32039       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32040       pFile->local.bExclusive = FALSE;
32041       pFile->shared->bExclusive = FALSE;
32042       bReturn = TRUE;
32043     }
32044 
32045     /* Did we just have a reader lock? */
32046     else if (pFile->local.nReaders){
32047       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
32048              || nNumberOfBytesToUnlockLow == 1);
32049       pFile->local.nReaders --;
32050       if (pFile->local.nReaders == 0)
32051       {
32052         pFile->shared->nReaders --;
32053       }
32054       bReturn = TRUE;
32055     }
32056   }
32057 
32058   /* Releasing a pending lock */
32059   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32060            && nNumberOfBytesToUnlockLow == 1){
32061     if (pFile->local.bPending){
32062       pFile->local.bPending = FALSE;
32063       pFile->shared->bPending = FALSE;
32064       bReturn = TRUE;
32065     }
32066   }
32067   /* Releasing a reserved lock */
32068   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32069            && nNumberOfBytesToUnlockLow == 1){
32070     if (pFile->local.bReserved) {
32071       pFile->local.bReserved = FALSE;
32072       pFile->shared->bReserved = FALSE;
32073       bReturn = TRUE;
32074     }
32075   }
32076 
32077   winceMutexRelease(pFile->hMutex);
32078   return bReturn;
32079 }
32080 /*
32081 ** End of the special code for wince
32082 *****************************************************************************/
32083 #endif /* SQLITE_OS_WINCE */
32084 
32085 /*
32086 ** Lock a file region.
32087 */
32088 static BOOL winLockFile(
32089   LPHANDLE phFile,
32090   DWORD flags,
32091   DWORD offsetLow,
32092   DWORD offsetHigh,
32093   DWORD numBytesLow,
32094   DWORD numBytesHigh
32095 ){
32096 #if SQLITE_OS_WINCE
32097   /*
32098   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32099   **       API LockFile.
32100   */
32101   return winceLockFile(phFile, offsetLow, offsetHigh,
32102                        numBytesLow, numBytesHigh);
32103 #else
32104   if( isNT() ){
32105     OVERLAPPED ovlp;
32106     memset(&ovlp, 0, sizeof(OVERLAPPED));
32107     ovlp.Offset = offsetLow;
32108     ovlp.OffsetHigh = offsetHigh;
32109     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
32110   }else{
32111     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32112                       numBytesHigh);
32113   }
32114 #endif
32115 }
32116 
32117 /*
32118 ** Unlock a file region.
32119  */
32120 static BOOL winUnlockFile(
32121   LPHANDLE phFile,
32122   DWORD offsetLow,
32123   DWORD offsetHigh,
32124   DWORD numBytesLow,
32125   DWORD numBytesHigh
32126 ){
32127 #if SQLITE_OS_WINCE
32128   /*
32129   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32130   **       API UnlockFile.
32131   */
32132   return winceUnlockFile(phFile, offsetLow, offsetHigh,
32133                          numBytesLow, numBytesHigh);
32134 #else
32135   if( isNT() ){
32136     OVERLAPPED ovlp;
32137     memset(&ovlp, 0, sizeof(OVERLAPPED));
32138     ovlp.Offset = offsetLow;
32139     ovlp.OffsetHigh = offsetHigh;
32140     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
32141   }else{
32142     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32143                         numBytesHigh);
32144   }
32145 #endif
32146 }
32147 
32148 /*****************************************************************************
32149 ** The next group of routines implement the I/O methods specified
32150 ** by the sqlite3_io_methods object.
32151 ******************************************************************************/
32152 
32153 /*
32154 ** Some Microsoft compilers lack this definition.
32155 */
32156 #ifndef INVALID_SET_FILE_POINTER
32157 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32158 #endif
32159 
32160 /*
32161 ** Move the current position of the file handle passed as the first
32162 ** argument to offset iOffset within the file. If successful, return 0.
32163 ** Otherwise, set pFile->lastErrno and return non-zero.
32164 */
32165 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32166 #if !SQLITE_OS_WINRT
32167   LONG upperBits;                 /* Most sig. 32 bits of new offset */
32168   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32169   DWORD dwRet;                    /* Value returned by SetFilePointer() */
32170   DWORD lastErrno;                /* Value returned by GetLastError() */
32171 
32172   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32173   lowerBits = (LONG)(iOffset & 0xffffffff);
32174 
32175   /* API oddity: If successful, SetFilePointer() returns a dword
32176   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32177   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
32178   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
32179   ** whether an error has actually occurred, it is also necessary to call
32180   ** GetLastError().
32181   */
32182   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32183 
32184   if( (dwRet==INVALID_SET_FILE_POINTER
32185       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
32186     pFile->lastErrno = lastErrno;
32187     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32188              "seekWinFile", pFile->zPath);
32189     return 1;
32190   }
32191 
32192   return 0;
32193 #else
32194   /*
32195   ** Same as above, except that this implementation works for WinRT.
32196   */
32197 
32198   LARGE_INTEGER x;                /* The new offset */
32199   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
32200 
32201   x.QuadPart = iOffset;
32202   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
32203 
32204   if(!bRet){
32205     pFile->lastErrno = osGetLastError();
32206     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32207              "seekWinFile", pFile->zPath);
32208     return 1;
32209   }
32210 
32211   return 0;
32212 #endif
32213 }
32214 
32215 /*
32216 ** Close a file.
32217 **
32218 ** It is reported that an attempt to close a handle might sometimes
32219 ** fail.  This is a very unreasonable result, but Windows is notorious
32220 ** for being unreasonable so I do not doubt that it might happen.  If
32221 ** the close fails, we pause for 100 milliseconds and try again.  As
32222 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32223 ** giving up and returning an error.
32224 */
32225 #define MX_CLOSE_ATTEMPT 3
32226 static int winClose(sqlite3_file *id){
32227   int rc, cnt = 0;
32228   winFile *pFile = (winFile*)id;
32229 
32230   assert( id!=0 );
32231 #ifndef SQLITE_OMIT_WAL
32232   assert( pFile->pShm==0 );
32233 #endif
32234   OSTRACE(("CLOSE %d\n", pFile->h));
32235   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
32236   do{
32237     rc = osCloseHandle(pFile->h);
32238     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32239   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
32240 #if SQLITE_OS_WINCE
32241 #define WINCE_DELETION_ATTEMPTS 3
32242   winceDestroyLock(pFile);
32243   if( pFile->zDeleteOnClose ){
32244     int cnt = 0;
32245     while(
32246            osDeleteFileW(pFile->zDeleteOnClose)==0
32247         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
32248         && cnt++ < WINCE_DELETION_ATTEMPTS
32249     ){
32250        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
32251     }
32252     sqlite3_free(pFile->zDeleteOnClose);
32253   }
32254 #endif
32255   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
32256   if( rc ){
32257     pFile->h = NULL;
32258   }
32259   OpenCounter(-1);
32260   return rc ? SQLITE_OK
32261             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
32262                           "winClose", pFile->zPath);
32263 }
32264 
32265 /*
32266 ** Read data from a file into a buffer.  Return SQLITE_OK if all
32267 ** bytes were read successfully and SQLITE_IOERR if anything goes
32268 ** wrong.
32269 */
32270 static int winRead(
32271   sqlite3_file *id,          /* File to read from */
32272   void *pBuf,                /* Write content into this buffer */
32273   int amt,                   /* Number of bytes to read */
32274   sqlite3_int64 offset       /* Begin reading at this offset */
32275 ){
32276 #if !SQLITE_OS_WINCE
32277   OVERLAPPED overlapped;          /* The offset for ReadFile. */
32278 #endif
32279   winFile *pFile = (winFile*)id;  /* file handle */
32280   DWORD nRead;                    /* Number of bytes actually read from file */
32281   int nRetry = 0;                 /* Number of retrys */
32282 
32283   assert( id!=0 );
32284   SimulateIOError(return SQLITE_IOERR_READ);
32285   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
32286 
32287 #if SQLITE_OS_WINCE
32288   if( seekWinFile(pFile, offset) ){
32289     return SQLITE_FULL;
32290   }
32291   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32292 #else
32293   memset(&overlapped, 0, sizeof(OVERLAPPED));
32294   overlapped.Offset = (LONG)(offset & 0xffffffff);
32295   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32296   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
32297          osGetLastError()!=ERROR_HANDLE_EOF ){
32298 #endif
32299     DWORD lastErrno;
32300     if( retryIoerr(&nRetry, &lastErrno) ) continue;
32301     pFile->lastErrno = lastErrno;
32302     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
32303              "winRead", pFile->zPath);
32304   }
32305   logIoerr(nRetry);
32306   if( nRead<(DWORD)amt ){
32307     /* Unread parts of the buffer must be zero-filled */
32308     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32309     return SQLITE_IOERR_SHORT_READ;
32310   }
32311 
32312   return SQLITE_OK;
32313 }
32314 
32315 /*
32316 ** Write data from a buffer into a file.  Return SQLITE_OK on success
32317 ** or some other error code on failure.
32318 */
32319 static int winWrite(
32320   sqlite3_file *id,               /* File to write into */
32321   const void *pBuf,               /* The bytes to be written */
32322   int amt,                        /* Number of bytes to write */
32323   sqlite3_int64 offset            /* Offset into the file to begin writing at */
32324 ){
32325   int rc = 0;                     /* True if error has occurred, else false */
32326   winFile *pFile = (winFile*)id;  /* File handle */
32327   int nRetry = 0;                 /* Number of retries */
32328 
32329   assert( amt>0 );
32330   assert( pFile );
32331   SimulateIOError(return SQLITE_IOERR_WRITE);
32332   SimulateDiskfullError(return SQLITE_FULL);
32333 
32334   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
32335 
32336 #if SQLITE_OS_WINCE
32337   rc = seekWinFile(pFile, offset);
32338   if( rc==0 ){
32339 #else
32340   {
32341 #endif
32342 #if !SQLITE_OS_WINCE
32343     OVERLAPPED overlapped;        /* The offset for WriteFile. */
32344 #endif
32345     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32346     int nRem = amt;               /* Number of bytes yet to be written */
32347     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32348     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
32349 
32350 #if !SQLITE_OS_WINCE
32351     memset(&overlapped, 0, sizeof(OVERLAPPED));
32352     overlapped.Offset = (LONG)(offset & 0xffffffff);
32353     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32354 #endif
32355 
32356     while( nRem>0 ){
32357 #if SQLITE_OS_WINCE
32358       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32359 #else
32360       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
32361 #endif
32362         if( retryIoerr(&nRetry, &lastErrno) ) continue;
32363         break;
32364       }
32365       assert( nWrite==0 || nWrite<=(DWORD)nRem );
32366       if( nWrite==0 || nWrite>(DWORD)nRem ){
32367         lastErrno = osGetLastError();
32368         break;
32369       }
32370 #if !SQLITE_OS_WINCE
32371       offset += nWrite;
32372       overlapped.Offset = (LONG)(offset & 0xffffffff);
32373       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32374 #endif
32375       aRem += nWrite;
32376       nRem -= nWrite;
32377     }
32378     if( nRem>0 ){
32379       pFile->lastErrno = lastErrno;
32380       rc = 1;
32381     }
32382   }
32383 
32384   if( rc ){
32385     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32386        || ( pFile->lastErrno==ERROR_DISK_FULL )){
32387       return SQLITE_FULL;
32388     }
32389     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
32390              "winWrite", pFile->zPath);
32391   }else{
32392     logIoerr(nRetry);
32393   }
32394   return SQLITE_OK;
32395 }
32396 
32397 /*
32398 ** Truncate an open file to a specified size
32399 */
32400 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32401   winFile *pFile = (winFile*)id;  /* File handle object */
32402   int rc = SQLITE_OK;             /* Return code for this function */
32403 
32404   assert( pFile );
32405 
32406   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32407   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32408 
32409   /* If the user has configured a chunk-size for this file, truncate the
32410   ** file so that it consists of an integer number of chunks (i.e. the
32411   ** actual file size after the operation may be larger than the requested
32412   ** size).
32413   */
32414   if( pFile->szChunk>0 ){
32415     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32416   }
32417 
32418   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32419   if( seekWinFile(pFile, nByte) ){
32420     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32421              "winTruncate1", pFile->zPath);
32422   }else if( 0==osSetEndOfFile(pFile->h) ){
32423     pFile->lastErrno = osGetLastError();
32424     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
32425              "winTruncate2", pFile->zPath);
32426   }
32427 
32428   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32429   return rc;
32430 }
32431 
32432 #ifdef SQLITE_TEST
32433 /*
32434 ** Count the number of fullsyncs and normal syncs.  This is used to test
32435 ** that syncs and fullsyncs are occuring at the right times.
32436 */
32437 SQLITE_API int sqlite3_sync_count = 0;
32438 SQLITE_API int sqlite3_fullsync_count = 0;
32439 #endif
32440 
32441 /*
32442 ** Make sure all writes to a particular file are committed to disk.
32443 */
32444 static int winSync(sqlite3_file *id, int flags){
32445 #ifndef SQLITE_NO_SYNC
32446   /*
32447   ** Used only when SQLITE_NO_SYNC is not defined.
32448    */
32449   BOOL rc;
32450 #endif
32451 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
32452     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
32453   /*
32454   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
32455   ** OSTRACE() macros.
32456    */
32457   winFile *pFile = (winFile*)id;
32458 #else
32459   UNUSED_PARAMETER(id);
32460 #endif
32461 
32462   assert( pFile );
32463   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32464   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32465       || (flags&0x0F)==SQLITE_SYNC_FULL
32466   );
32467 
32468   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32469 
32470   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32471   ** line is to test that doing so does not cause any problems.
32472   */
32473   SimulateDiskfullError( return SQLITE_FULL );
32474 
32475 #ifndef SQLITE_TEST
32476   UNUSED_PARAMETER(flags);
32477 #else
32478   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32479     sqlite3_fullsync_count++;
32480   }
32481   sqlite3_sync_count++;
32482 #endif
32483 
32484   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32485   ** no-op
32486   */
32487 #ifdef SQLITE_NO_SYNC
32488   return SQLITE_OK;
32489 #else
32490   rc = osFlushFileBuffers(pFile->h);
32491   SimulateIOError( rc=FALSE );
32492   if( rc ){
32493     return SQLITE_OK;
32494   }else{
32495     pFile->lastErrno = osGetLastError();
32496     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
32497              "winSync", pFile->zPath);
32498   }
32499 #endif
32500 }
32501 
32502 /*
32503 ** Determine the current size of a file in bytes
32504 */
32505 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32506   winFile *pFile = (winFile*)id;
32507   int rc = SQLITE_OK;
32508 
32509   assert( id!=0 );
32510   SimulateIOError(return SQLITE_IOERR_FSTAT);
32511 #if SQLITE_OS_WINRT
32512   {
32513     FILE_STANDARD_INFO info;
32514     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
32515                                      &info, sizeof(info)) ){
32516       *pSize = info.EndOfFile.QuadPart;
32517     }else{
32518       pFile->lastErrno = osGetLastError();
32519       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32520                        "winFileSize", pFile->zPath);
32521     }
32522   }
32523 #else
32524   {
32525     DWORD upperBits;
32526     DWORD lowerBits;
32527     DWORD lastErrno;
32528 
32529     lowerBits = osGetFileSize(pFile->h, &upperBits);
32530     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32531     if(   (lowerBits == INVALID_FILE_SIZE)
32532        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
32533       pFile->lastErrno = lastErrno;
32534       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
32535              "winFileSize", pFile->zPath);
32536     }
32537   }
32538 #endif
32539   return rc;
32540 }
32541 
32542 /*
32543 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32544 */
32545 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32546 # define LOCKFILE_FAIL_IMMEDIATELY 1
32547 #endif
32548 
32549 #ifndef LOCKFILE_EXCLUSIVE_LOCK
32550 # define LOCKFILE_EXCLUSIVE_LOCK 2
32551 #endif
32552 
32553 /*
32554 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
32555 ** When the LockFile function was used, it was always expected to fail
32556 ** immediately if the lock could not be obtained.  Also, it always expected to
32557 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
32558 ** and reflect those expectations; therefore, they should not be changed.
32559 */
32560 #ifndef SQLITE_LOCKFILE_FLAGS
32561 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
32562                                   LOCKFILE_EXCLUSIVE_LOCK)
32563 #endif
32564 
32565 /*
32566 ** Currently, SQLite never calls the LockFileEx function without wanting the
32567 ** call to fail immediately if the lock cannot be obtained.
32568 */
32569 #ifndef SQLITE_LOCKFILEEX_FLAGS
32570 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
32571 #endif
32572 
32573 /*
32574 ** Acquire a reader lock.
32575 ** Different API routines are called depending on whether or not this
32576 ** is Win9x or WinNT.
32577 */
32578 static int getReadLock(winFile *pFile){
32579   int res;
32580   if( isNT() ){
32581 #if SQLITE_OS_WINCE
32582     /*
32583     ** NOTE: Windows CE is handled differently here due its lack of the Win32
32584     **       API LockFileEx.
32585     */
32586     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
32587 #else
32588     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
32589                       SHARED_SIZE, 0);
32590 #endif
32591   }
32592 #ifdef SQLITE_WIN32_HAS_ANSI
32593   else{
32594     int lk;
32595     sqlite3_randomness(sizeof(lk), &lk);
32596     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32597     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32598                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32599   }
32600 #endif
32601   if( res == 0 ){
32602     pFile->lastErrno = osGetLastError();
32603     /* No need to log a failure to lock */
32604   }
32605   return res;
32606 }
32607 
32608 /*
32609 ** Undo a readlock
32610 */
32611 static int unlockReadLock(winFile *pFile){
32612   int res;
32613   DWORD lastErrno;
32614   if( isNT() ){
32615     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32616   }
32617 #ifdef SQLITE_WIN32_HAS_ANSI
32618   else{
32619     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32620   }
32621 #endif
32622   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
32623     pFile->lastErrno = lastErrno;
32624     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
32625              "unlockReadLock", pFile->zPath);
32626   }
32627   return res;
32628 }
32629 
32630 /*
32631 ** Lock the file with the lock specified by parameter locktype - one
32632 ** of the following:
32633 **
32634 **     (1) SHARED_LOCK
32635 **     (2) RESERVED_LOCK
32636 **     (3) PENDING_LOCK
32637 **     (4) EXCLUSIVE_LOCK
32638 **
32639 ** Sometimes when requesting one lock state, additional lock states
32640 ** are inserted in between.  The locking might fail on one of the later
32641 ** transitions leaving the lock state different from what it started but
32642 ** still short of its goal.  The following chart shows the allowed
32643 ** transitions and the inserted intermediate states:
32644 **
32645 **    UNLOCKED -> SHARED
32646 **    SHARED -> RESERVED
32647 **    SHARED -> (PENDING) -> EXCLUSIVE
32648 **    RESERVED -> (PENDING) -> EXCLUSIVE
32649 **    PENDING -> EXCLUSIVE
32650 **
32651 ** This routine will only increase a lock.  The winUnlock() routine
32652 ** erases all locks at once and returns us immediately to locking level 0.
32653 ** It is not possible to lower the locking level one step at a time.  You
32654 ** must go straight to locking level 0.
32655 */
32656 static int winLock(sqlite3_file *id, int locktype){
32657   int rc = SQLITE_OK;    /* Return code from subroutines */
32658   int res = 1;           /* Result of a Windows lock call */
32659   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32660   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32661   winFile *pFile = (winFile*)id;
32662   DWORD lastErrno = NO_ERROR;
32663 
32664   assert( id!=0 );
32665   OSTRACE(("LOCK %d %d was %d(%d)\n",
32666            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32667 
32668   /* If there is already a lock of this type or more restrictive on the
32669   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32670   ** sqlite3OsEnterMutex() hasn't been called yet.
32671   */
32672   if( pFile->locktype>=locktype ){
32673     return SQLITE_OK;
32674   }
32675 
32676   /* Make sure the locking sequence is correct
32677   */
32678   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32679   assert( locktype!=PENDING_LOCK );
32680   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32681 
32682   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32683   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32684   ** the PENDING_LOCK byte is temporary.
32685   */
32686   newLocktype = pFile->locktype;
32687   if(   (pFile->locktype==NO_LOCK)
32688      || (   (locktype==EXCLUSIVE_LOCK)
32689          && (pFile->locktype==RESERVED_LOCK))
32690   ){
32691     int cnt = 3;
32692     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
32693                                          PENDING_BYTE, 0, 1, 0))==0 ){
32694       /* Try 3 times to get the pending lock.  This is needed to work
32695       ** around problems caused by indexing and/or anti-virus software on
32696       ** Windows systems.
32697       ** If you are using this code as a model for alternative VFSes, do not
32698       ** copy this retry logic.  It is a hack intended for Windows only.
32699       */
32700       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32701       if( cnt ) sqlite3_win32_sleep(1);
32702     }
32703     gotPendingLock = res;
32704     if( !res ){
32705       lastErrno = osGetLastError();
32706     }
32707   }
32708 
32709   /* Acquire a shared lock
32710   */
32711   if( locktype==SHARED_LOCK && res ){
32712     assert( pFile->locktype==NO_LOCK );
32713     res = getReadLock(pFile);
32714     if( res ){
32715       newLocktype = SHARED_LOCK;
32716     }else{
32717       lastErrno = osGetLastError();
32718     }
32719   }
32720 
32721   /* Acquire a RESERVED lock
32722   */
32723   if( locktype==RESERVED_LOCK && res ){
32724     assert( pFile->locktype==SHARED_LOCK );
32725     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
32726     if( res ){
32727       newLocktype = RESERVED_LOCK;
32728     }else{
32729       lastErrno = osGetLastError();
32730     }
32731   }
32732 
32733   /* Acquire a PENDING lock
32734   */
32735   if( locktype==EXCLUSIVE_LOCK && res ){
32736     newLocktype = PENDING_LOCK;
32737     gotPendingLock = 0;
32738   }
32739 
32740   /* Acquire an EXCLUSIVE lock
32741   */
32742   if( locktype==EXCLUSIVE_LOCK && res ){
32743     assert( pFile->locktype>=SHARED_LOCK );
32744     res = unlockReadLock(pFile);
32745     OSTRACE(("unreadlock = %d\n", res));
32746     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
32747                       SHARED_SIZE, 0);
32748     if( res ){
32749       newLocktype = EXCLUSIVE_LOCK;
32750     }else{
32751       lastErrno = osGetLastError();
32752       OSTRACE(("error-code = %d\n", lastErrno));
32753       getReadLock(pFile);
32754     }
32755   }
32756 
32757   /* If we are holding a PENDING lock that ought to be released, then
32758   ** release it now.
32759   */
32760   if( gotPendingLock && locktype==SHARED_LOCK ){
32761     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32762   }
32763 
32764   /* Update the state of the lock has held in the file descriptor then
32765   ** return the appropriate result code.
32766   */
32767   if( res ){
32768     rc = SQLITE_OK;
32769   }else{
32770     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32771            locktype, newLocktype));
32772     pFile->lastErrno = lastErrno;
32773     rc = SQLITE_BUSY;
32774   }
32775   pFile->locktype = (u8)newLocktype;
32776   return rc;
32777 }
32778 
32779 /*
32780 ** This routine checks if there is a RESERVED lock held on the specified
32781 ** file by this or any other process. If such a lock is held, return
32782 ** non-zero, otherwise zero.
32783 */
32784 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32785   int rc;
32786   winFile *pFile = (winFile*)id;
32787 
32788   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32789 
32790   assert( id!=0 );
32791   if( pFile->locktype>=RESERVED_LOCK ){
32792     rc = 1;
32793     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32794   }else{
32795     rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
32796     if( rc ){
32797       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32798     }
32799     rc = !rc;
32800     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32801   }
32802   *pResOut = rc;
32803   return SQLITE_OK;
32804 }
32805 
32806 /*
32807 ** Lower the locking level on file descriptor id to locktype.  locktype
32808 ** must be either NO_LOCK or SHARED_LOCK.
32809 **
32810 ** If the locking level of the file descriptor is already at or below
32811 ** the requested locking level, this routine is a no-op.
32812 **
32813 ** It is not possible for this routine to fail if the second argument
32814 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32815 ** might return SQLITE_IOERR;
32816 */
32817 static int winUnlock(sqlite3_file *id, int locktype){
32818   int type;
32819   winFile *pFile = (winFile*)id;
32820   int rc = SQLITE_OK;
32821   assert( pFile!=0 );
32822   assert( locktype<=SHARED_LOCK );
32823   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32824           pFile->locktype, pFile->sharedLockByte));
32825   type = pFile->locktype;
32826   if( type>=EXCLUSIVE_LOCK ){
32827     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32828     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32829       /* This should never happen.  We should always be able to
32830       ** reacquire the read lock */
32831       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
32832                "winUnlock", pFile->zPath);
32833     }
32834   }
32835   if( type>=RESERVED_LOCK ){
32836     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
32837   }
32838   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32839     unlockReadLock(pFile);
32840   }
32841   if( type>=PENDING_LOCK ){
32842     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
32843   }
32844   pFile->locktype = (u8)locktype;
32845   return rc;
32846 }
32847 
32848 /*
32849 ** If *pArg is inititially negative then this is a query.  Set *pArg to
32850 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
32851 **
32852 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
32853 */
32854 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
32855   if( *pArg<0 ){
32856     *pArg = (pFile->ctrlFlags & mask)!=0;
32857   }else if( (*pArg)==0 ){
32858     pFile->ctrlFlags &= ~mask;
32859   }else{
32860     pFile->ctrlFlags |= mask;
32861   }
32862 }
32863 
32864 /* Forward declaration */
32865 static int getTempname(int nBuf, char *zBuf);
32866 
32867 /*
32868 ** Control and query of the open file handle.
32869 */
32870 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32871   winFile *pFile = (winFile*)id;
32872   switch( op ){
32873     case SQLITE_FCNTL_LOCKSTATE: {
32874       *(int*)pArg = pFile->locktype;
32875       return SQLITE_OK;
32876     }
32877     case SQLITE_LAST_ERRNO: {
32878       *(int*)pArg = (int)pFile->lastErrno;
32879       return SQLITE_OK;
32880     }
32881     case SQLITE_FCNTL_CHUNK_SIZE: {
32882       pFile->szChunk = *(int *)pArg;
32883       return SQLITE_OK;
32884     }
32885     case SQLITE_FCNTL_SIZE_HINT: {
32886       if( pFile->szChunk>0 ){
32887         sqlite3_int64 oldSz;
32888         int rc = winFileSize(id, &oldSz);
32889         if( rc==SQLITE_OK ){
32890           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
32891           if( newSz>oldSz ){
32892             SimulateIOErrorBenign(1);
32893             rc = winTruncate(id, newSz);
32894             SimulateIOErrorBenign(0);
32895           }
32896         }
32897         return rc;
32898       }
32899       return SQLITE_OK;
32900     }
32901     case SQLITE_FCNTL_PERSIST_WAL: {
32902       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
32903       return SQLITE_OK;
32904     }
32905     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
32906       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
32907       return SQLITE_OK;
32908     }
32909     case SQLITE_FCNTL_VFSNAME: {
32910       *(char**)pArg = sqlite3_mprintf("win32");
32911       return SQLITE_OK;
32912     }
32913     case SQLITE_FCNTL_WIN32_AV_RETRY: {
32914       int *a = (int*)pArg;
32915       if( a[0]>0 ){
32916         win32IoerrRetry = a[0];
32917       }else{
32918         a[0] = win32IoerrRetry;
32919       }
32920       if( a[1]>0 ){
32921         win32IoerrRetryDelay = a[1];
32922       }else{
32923         a[1] = win32IoerrRetryDelay;
32924       }
32925       return SQLITE_OK;
32926     }
32927     case SQLITE_FCNTL_TEMPFILENAME: {
32928       char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
32929       if( zTFile ){
32930         getTempname(pFile->pVfs->mxPathname, zTFile);
32931         *(char**)pArg = zTFile;
32932       }
32933       return SQLITE_OK;
32934     }
32935   }
32936   return SQLITE_NOTFOUND;
32937 }
32938 
32939 /*
32940 ** Return the sector size in bytes of the underlying block device for
32941 ** the specified file. This is almost always 512 bytes, but may be
32942 ** larger for some devices.
32943 **
32944 ** SQLite code assumes this function cannot fail. It also assumes that
32945 ** if two files are created in the same file-system directory (i.e.
32946 ** a database and its journal file) that the sector size will be the
32947 ** same for both.
32948 */
32949 static int winSectorSize(sqlite3_file *id){
32950   (void)id;
32951   return SQLITE_DEFAULT_SECTOR_SIZE;
32952 }
32953 
32954 /*
32955 ** Return a vector of device characteristics.
32956 */
32957 static int winDeviceCharacteristics(sqlite3_file *id){
32958   winFile *p = (winFile*)id;
32959   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
32960          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
32961 }
32962 
32963 #ifndef SQLITE_OMIT_WAL
32964 
32965 /*
32966 ** Windows will only let you create file view mappings
32967 ** on allocation size granularity boundaries.
32968 ** During sqlite3_os_init() we do a GetSystemInfo()
32969 ** to get the granularity size.
32970 */
32971 SYSTEM_INFO winSysInfo;
32972 
32973 /*
32974 ** Helper functions to obtain and relinquish the global mutex. The
32975 ** global mutex is used to protect the winLockInfo objects used by
32976 ** this file, all of which may be shared by multiple threads.
32977 **
32978 ** Function winShmMutexHeld() is used to assert() that the global mutex
32979 ** is held when required. This function is only used as part of assert()
32980 ** statements. e.g.
32981 **
32982 **   winShmEnterMutex()
32983 **     assert( winShmMutexHeld() );
32984 **   winShmLeaveMutex()
32985 */
32986 static void winShmEnterMutex(void){
32987   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32988 }
32989 static void winShmLeaveMutex(void){
32990   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32991 }
32992 #ifdef SQLITE_DEBUG
32993 static int winShmMutexHeld(void) {
32994   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32995 }
32996 #endif
32997 
32998 /*
32999 ** Object used to represent a single file opened and mmapped to provide
33000 ** shared memory.  When multiple threads all reference the same
33001 ** log-summary, each thread has its own winFile object, but they all
33002 ** point to a single instance of this object.  In other words, each
33003 ** log-summary is opened only once per process.
33004 **
33005 ** winShmMutexHeld() must be true when creating or destroying
33006 ** this object or while reading or writing the following fields:
33007 **
33008 **      nRef
33009 **      pNext
33010 **
33011 ** The following fields are read-only after the object is created:
33012 **
33013 **      fid
33014 **      zFilename
33015 **
33016 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33017 ** winShmMutexHeld() is true when reading or writing any other field
33018 ** in this structure.
33019 **
33020 */
33021 struct winShmNode {
33022   sqlite3_mutex *mutex;      /* Mutex to access this object */
33023   char *zFilename;           /* Name of the file */
33024   winFile hFile;             /* File handle from winOpen */
33025 
33026   int szRegion;              /* Size of shared-memory regions */
33027   int nRegion;               /* Size of array apRegion */
33028   struct ShmRegion {
33029     HANDLE hMap;             /* File handle from CreateFileMapping */
33030     void *pMap;
33031   } *aRegion;
33032   DWORD lastErrno;           /* The Windows errno from the last I/O error */
33033 
33034   int nRef;                  /* Number of winShm objects pointing to this */
33035   winShm *pFirst;            /* All winShm objects pointing to this */
33036   winShmNode *pNext;         /* Next in list of all winShmNode objects */
33037 #ifdef SQLITE_DEBUG
33038   u8 nextShmId;              /* Next available winShm.id value */
33039 #endif
33040 };
33041 
33042 /*
33043 ** A global array of all winShmNode objects.
33044 **
33045 ** The winShmMutexHeld() must be true while reading or writing this list.
33046 */
33047 static winShmNode *winShmNodeList = 0;
33048 
33049 /*
33050 ** Structure used internally by this VFS to record the state of an
33051 ** open shared memory connection.
33052 **
33053 ** The following fields are initialized when this object is created and
33054 ** are read-only thereafter:
33055 **
33056 **    winShm.pShmNode
33057 **    winShm.id
33058 **
33059 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
33060 ** while accessing any read/write fields.
33061 */
33062 struct winShm {
33063   winShmNode *pShmNode;      /* The underlying winShmNode object */
33064   winShm *pNext;             /* Next winShm with the same winShmNode */
33065   u8 hasMutex;               /* True if holding the winShmNode mutex */
33066   u16 sharedMask;            /* Mask of shared locks held */
33067   u16 exclMask;              /* Mask of exclusive locks held */
33068 #ifdef SQLITE_DEBUG
33069   u8 id;                     /* Id of this connection with its winShmNode */
33070 #endif
33071 };
33072 
33073 /*
33074 ** Constants used for locking
33075 */
33076 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
33077 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33078 
33079 /*
33080 ** Apply advisory locks for all n bytes beginning at ofst.
33081 */
33082 #define _SHM_UNLCK  1
33083 #define _SHM_RDLCK  2
33084 #define _SHM_WRLCK  3
33085 static int winShmSystemLock(
33086   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
33087   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33088   int ofst,             /* Offset to first byte to be locked/unlocked */
33089   int nByte             /* Number of bytes to lock or unlock */
33090 ){
33091   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
33092 
33093   /* Access to the winShmNode object is serialized by the caller */
33094   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33095 
33096   /* Release/Acquire the system-level lock */
33097   if( lockType==_SHM_UNLCK ){
33098     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
33099   }else{
33100     /* Initialize the locking parameters */
33101     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33102     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33103     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
33104   }
33105 
33106   if( rc!= 0 ){
33107     rc = SQLITE_OK;
33108   }else{
33109     pFile->lastErrno =  osGetLastError();
33110     rc = SQLITE_BUSY;
33111   }
33112 
33113   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
33114            pFile->hFile.h,
33115            rc==SQLITE_OK ? "ok" : "failed",
33116            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
33117            pFile->lastErrno));
33118 
33119   return rc;
33120 }
33121 
33122 /* Forward references to VFS methods */
33123 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33124 static int winDelete(sqlite3_vfs *,const char*,int);
33125 
33126 /*
33127 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33128 **
33129 ** This is not a VFS shared-memory method; it is a utility function called
33130 ** by VFS shared-memory methods.
33131 */
33132 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33133   winShmNode **pp;
33134   winShmNode *p;
33135   BOOL bRc;
33136   assert( winShmMutexHeld() );
33137   pp = &winShmNodeList;
33138   while( (p = *pp)!=0 ){
33139     if( p->nRef==0 ){
33140       int i;
33141       if( p->mutex ) sqlite3_mutex_free(p->mutex);
33142       for(i=0; i<p->nRegion; i++){
33143         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
33144         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
33145                  (int)osGetCurrentProcessId(), i,
33146                  bRc ? "ok" : "failed"));
33147         bRc = osCloseHandle(p->aRegion[i].hMap);
33148         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
33149                  (int)osGetCurrentProcessId(), i,
33150                  bRc ? "ok" : "failed"));
33151       }
33152       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
33153         SimulateIOErrorBenign(1);
33154         winClose((sqlite3_file *)&p->hFile);
33155         SimulateIOErrorBenign(0);
33156       }
33157       if( deleteFlag ){
33158         SimulateIOErrorBenign(1);
33159         sqlite3BeginBenignMalloc();
33160         winDelete(pVfs, p->zFilename, 0);
33161         sqlite3EndBenignMalloc();
33162         SimulateIOErrorBenign(0);
33163       }
33164       *pp = p->pNext;
33165       sqlite3_free(p->aRegion);
33166       sqlite3_free(p);
33167     }else{
33168       pp = &p->pNext;
33169     }
33170   }
33171 }
33172 
33173 /*
33174 ** Open the shared-memory area associated with database file pDbFd.
33175 **
33176 ** When opening a new shared-memory file, if no other instances of that
33177 ** file are currently open, in this process or in other processes, then
33178 ** the file must be truncated to zero length or have its header cleared.
33179 */
33180 static int winOpenSharedMemory(winFile *pDbFd){
33181   struct winShm *p;                  /* The connection to be opened */
33182   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
33183   int rc;                            /* Result code */
33184   struct winShmNode *pNew;           /* Newly allocated winShmNode */
33185   int nName;                         /* Size of zName in bytes */
33186 
33187   assert( pDbFd->pShm==0 );    /* Not previously opened */
33188 
33189   /* Allocate space for the new sqlite3_shm object.  Also speculatively
33190   ** allocate space for a new winShmNode and filename.
33191   */
33192   p = sqlite3MallocZero( sizeof(*p) );
33193   if( p==0 ) return SQLITE_IOERR_NOMEM;
33194   nName = sqlite3Strlen30(pDbFd->zPath);
33195   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
33196   if( pNew==0 ){
33197     sqlite3_free(p);
33198     return SQLITE_IOERR_NOMEM;
33199   }
33200   pNew->zFilename = (char*)&pNew[1];
33201   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33202   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
33203 
33204   /* Look to see if there is an existing winShmNode that can be used.
33205   ** If no matching winShmNode currently exists, create a new one.
33206   */
33207   winShmEnterMutex();
33208   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33209     /* TBD need to come up with better match here.  Perhaps
33210     ** use FILE_ID_BOTH_DIR_INFO Structure.
33211     */
33212     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33213   }
33214   if( pShmNode ){
33215     sqlite3_free(pNew);
33216   }else{
33217     pShmNode = pNew;
33218     pNew = 0;
33219     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33220     pShmNode->pNext = winShmNodeList;
33221     winShmNodeList = pShmNode;
33222 
33223     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33224     if( pShmNode->mutex==0 ){
33225       rc = SQLITE_IOERR_NOMEM;
33226       goto shm_open_err;
33227     }
33228 
33229     rc = winOpen(pDbFd->pVfs,
33230                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
33231                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33232                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
33233                  0);
33234     if( SQLITE_OK!=rc ){
33235       goto shm_open_err;
33236     }
33237 
33238     /* Check to see if another process is holding the dead-man switch.
33239     ** If not, truncate the file to zero length.
33240     */
33241     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33242       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33243       if( rc!=SQLITE_OK ){
33244         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
33245                  "winOpenShm", pDbFd->zPath);
33246       }
33247     }
33248     if( rc==SQLITE_OK ){
33249       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33250       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33251     }
33252     if( rc ) goto shm_open_err;
33253   }
33254 
33255   /* Make the new connection a child of the winShmNode */
33256   p->pShmNode = pShmNode;
33257 #ifdef SQLITE_DEBUG
33258   p->id = pShmNode->nextShmId++;
33259 #endif
33260   pShmNode->nRef++;
33261   pDbFd->pShm = p;
33262   winShmLeaveMutex();
33263 
33264   /* The reference count on pShmNode has already been incremented under
33265   ** the cover of the winShmEnterMutex() mutex and the pointer from the
33266   ** new (struct winShm) object to the pShmNode has been set. All that is
33267   ** left to do is to link the new object into the linked list starting
33268   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33269   ** mutex.
33270   */
33271   sqlite3_mutex_enter(pShmNode->mutex);
33272   p->pNext = pShmNode->pFirst;
33273   pShmNode->pFirst = p;
33274   sqlite3_mutex_leave(pShmNode->mutex);
33275   return SQLITE_OK;
33276 
33277   /* Jump here on any error */
33278 shm_open_err:
33279   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33280   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33281   sqlite3_free(p);
33282   sqlite3_free(pNew);
33283   winShmLeaveMutex();
33284   return rc;
33285 }
33286 
33287 /*
33288 ** Close a connection to shared-memory.  Delete the underlying
33289 ** storage if deleteFlag is true.
33290 */
33291 static int winShmUnmap(
33292   sqlite3_file *fd,          /* Database holding shared memory */
33293   int deleteFlag             /* Delete after closing if true */
33294 ){
33295   winFile *pDbFd;       /* Database holding shared-memory */
33296   winShm *p;            /* The connection to be closed */
33297   winShmNode *pShmNode; /* The underlying shared-memory file */
33298   winShm **pp;          /* For looping over sibling connections */
33299 
33300   pDbFd = (winFile*)fd;
33301   p = pDbFd->pShm;
33302   if( p==0 ) return SQLITE_OK;
33303   pShmNode = p->pShmNode;
33304 
33305   /* Remove connection p from the set of connections associated
33306   ** with pShmNode */
33307   sqlite3_mutex_enter(pShmNode->mutex);
33308   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33309   *pp = p->pNext;
33310 
33311   /* Free the connection p */
33312   sqlite3_free(p);
33313   pDbFd->pShm = 0;
33314   sqlite3_mutex_leave(pShmNode->mutex);
33315 
33316   /* If pShmNode->nRef has reached 0, then close the underlying
33317   ** shared-memory file, too */
33318   winShmEnterMutex();
33319   assert( pShmNode->nRef>0 );
33320   pShmNode->nRef--;
33321   if( pShmNode->nRef==0 ){
33322     winShmPurge(pDbFd->pVfs, deleteFlag);
33323   }
33324   winShmLeaveMutex();
33325 
33326   return SQLITE_OK;
33327 }
33328 
33329 /*
33330 ** Change the lock state for a shared-memory segment.
33331 */
33332 static int winShmLock(
33333   sqlite3_file *fd,          /* Database file holding the shared memory */
33334   int ofst,                  /* First lock to acquire or release */
33335   int n,                     /* Number of locks to acquire or release */
33336   int flags                  /* What to do with the lock */
33337 ){
33338   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
33339   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
33340   winShm *pX;                           /* For looping over all siblings */
33341   winShmNode *pShmNode = p->pShmNode;
33342   int rc = SQLITE_OK;                   /* Result code */
33343   u16 mask;                             /* Mask of locks to take or release */
33344 
33345   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33346   assert( n>=1 );
33347   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33348        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33349        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33350        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33351   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33352 
33353   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
33354   assert( n>1 || mask==(1<<ofst) );
33355   sqlite3_mutex_enter(pShmNode->mutex);
33356   if( flags & SQLITE_SHM_UNLOCK ){
33357     u16 allMask = 0; /* Mask of locks held by siblings */
33358 
33359     /* See if any siblings hold this same lock */
33360     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33361       if( pX==p ) continue;
33362       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33363       allMask |= pX->sharedMask;
33364     }
33365 
33366     /* Unlock the system-level locks */
33367     if( (mask & allMask)==0 ){
33368       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
33369     }else{
33370       rc = SQLITE_OK;
33371     }
33372 
33373     /* Undo the local locks */
33374     if( rc==SQLITE_OK ){
33375       p->exclMask &= ~mask;
33376       p->sharedMask &= ~mask;
33377     }
33378   }else if( flags & SQLITE_SHM_SHARED ){
33379     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33380 
33381     /* Find out which shared locks are already held by sibling connections.
33382     ** If any sibling already holds an exclusive lock, go ahead and return
33383     ** SQLITE_BUSY.
33384     */
33385     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33386       if( (pX->exclMask & mask)!=0 ){
33387         rc = SQLITE_BUSY;
33388         break;
33389       }
33390       allShared |= pX->sharedMask;
33391     }
33392 
33393     /* Get shared locks at the system level, if necessary */
33394     if( rc==SQLITE_OK ){
33395       if( (allShared & mask)==0 ){
33396         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33397       }else{
33398         rc = SQLITE_OK;
33399       }
33400     }
33401 
33402     /* Get the local shared locks */
33403     if( rc==SQLITE_OK ){
33404       p->sharedMask |= mask;
33405     }
33406   }else{
33407     /* Make sure no sibling connections hold locks that will block this
33408     ** lock.  If any do, return SQLITE_BUSY right away.
33409     */
33410     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33411       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33412         rc = SQLITE_BUSY;
33413         break;
33414       }
33415     }
33416 
33417     /* Get the exclusive locks at the system level.  Then if successful
33418     ** also mark the local connection as being locked.
33419     */
33420     if( rc==SQLITE_OK ){
33421       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33422       if( rc==SQLITE_OK ){
33423         assert( (p->sharedMask & mask)==0 );
33424         p->exclMask |= mask;
33425       }
33426     }
33427   }
33428   sqlite3_mutex_leave(pShmNode->mutex);
33429   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33430            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
33431            rc ? "failed" : "ok"));
33432   return rc;
33433 }
33434 
33435 /*
33436 ** Implement a memory barrier or memory fence on shared memory.
33437 **
33438 ** All loads and stores begun before the barrier must complete before
33439 ** any load or store begun after the barrier.
33440 */
33441 static void winShmBarrier(
33442   sqlite3_file *fd          /* Database holding the shared memory */
33443 ){
33444   UNUSED_PARAMETER(fd);
33445   /* MemoryBarrier(); // does not work -- do not know why not */
33446   winShmEnterMutex();
33447   winShmLeaveMutex();
33448 }
33449 
33450 /*
33451 ** This function is called to obtain a pointer to region iRegion of the
33452 ** shared-memory associated with the database file fd. Shared-memory regions
33453 ** are numbered starting from zero. Each shared-memory region is szRegion
33454 ** bytes in size.
33455 **
33456 ** If an error occurs, an error code is returned and *pp is set to NULL.
33457 **
33458 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33459 ** region has not been allocated (by any client, including one running in a
33460 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33461 ** isWrite is non-zero and the requested shared-memory region has not yet
33462 ** been allocated, it is allocated by this function.
33463 **
33464 ** If the shared-memory region has already been allocated or is allocated by
33465 ** this call as described above, then it is mapped into this processes
33466 ** address space (if it is not already), *pp is set to point to the mapped
33467 ** memory and SQLITE_OK returned.
33468 */
33469 static int winShmMap(
33470   sqlite3_file *fd,               /* Handle open on database file */
33471   int iRegion,                    /* Region to retrieve */
33472   int szRegion,                   /* Size of regions */
33473   int isWrite,                    /* True to extend file if necessary */
33474   void volatile **pp              /* OUT: Mapped memory */
33475 ){
33476   winFile *pDbFd = (winFile*)fd;
33477   winShm *p = pDbFd->pShm;
33478   winShmNode *pShmNode;
33479   int rc = SQLITE_OK;
33480 
33481   if( !p ){
33482     rc = winOpenSharedMemory(pDbFd);
33483     if( rc!=SQLITE_OK ) return rc;
33484     p = pDbFd->pShm;
33485   }
33486   pShmNode = p->pShmNode;
33487 
33488   sqlite3_mutex_enter(pShmNode->mutex);
33489   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33490 
33491   if( pShmNode->nRegion<=iRegion ){
33492     struct ShmRegion *apNew;           /* New aRegion[] array */
33493     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
33494     sqlite3_int64 sz;                  /* Current size of wal-index file */
33495 
33496     pShmNode->szRegion = szRegion;
33497 
33498     /* The requested region is not mapped into this processes address space.
33499     ** Check to see if it has been allocated (i.e. if the wal-index file is
33500     ** large enough to contain the requested region).
33501     */
33502     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33503     if( rc!=SQLITE_OK ){
33504       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33505                "winShmMap1", pDbFd->zPath);
33506       goto shmpage_out;
33507     }
33508 
33509     if( sz<nByte ){
33510       /* The requested memory region does not exist. If isWrite is set to
33511       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33512       **
33513       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33514       ** the requested memory region.
33515       */
33516       if( !isWrite ) goto shmpage_out;
33517       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33518       if( rc!=SQLITE_OK ){
33519         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
33520                  "winShmMap2", pDbFd->zPath);
33521         goto shmpage_out;
33522       }
33523     }
33524 
33525     /* Map the requested memory region into this processes address space. */
33526     apNew = (struct ShmRegion *)sqlite3_realloc(
33527         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33528     );
33529     if( !apNew ){
33530       rc = SQLITE_IOERR_NOMEM;
33531       goto shmpage_out;
33532     }
33533     pShmNode->aRegion = apNew;
33534 
33535     while( pShmNode->nRegion<=iRegion ){
33536       HANDLE hMap = NULL;         /* file-mapping handle */
33537       void *pMap = 0;             /* Mapped memory region */
33538 
33539 #if SQLITE_OS_WINRT
33540       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
33541           NULL, PAGE_READWRITE, nByte, NULL
33542       );
33543 #elif defined(SQLITE_WIN32_HAS_WIDE)
33544       hMap = osCreateFileMappingW(pShmNode->hFile.h,
33545           NULL, PAGE_READWRITE, 0, nByte, NULL
33546       );
33547 #elif defined(SQLITE_WIN32_HAS_ANSI)
33548       hMap = osCreateFileMappingA(pShmNode->hFile.h,
33549           NULL, PAGE_READWRITE, 0, nByte, NULL
33550       );
33551 #endif
33552       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33553                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
33554                hMap ? "ok" : "failed"));
33555       if( hMap ){
33556         int iOffset = pShmNode->nRegion*szRegion;
33557         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33558 #if SQLITE_OS_WINRT
33559         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33560             iOffset - iOffsetShift, szRegion + iOffsetShift
33561         );
33562 #else
33563         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33564             0, iOffset - iOffsetShift, szRegion + iOffsetShift
33565         );
33566 #endif
33567         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33568                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
33569                  szRegion, pMap ? "ok" : "failed"));
33570       }
33571       if( !pMap ){
33572         pShmNode->lastErrno = osGetLastError();
33573         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
33574                  "winShmMap3", pDbFd->zPath);
33575         if( hMap ) osCloseHandle(hMap);
33576         goto shmpage_out;
33577       }
33578 
33579       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33580       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33581       pShmNode->nRegion++;
33582     }
33583   }
33584 
33585 shmpage_out:
33586   if( pShmNode->nRegion>iRegion ){
33587     int iOffset = iRegion*szRegion;
33588     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33589     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33590     *pp = (void *)&p[iOffsetShift];
33591   }else{
33592     *pp = 0;
33593   }
33594   sqlite3_mutex_leave(pShmNode->mutex);
33595   return rc;
33596 }
33597 
33598 #else
33599 # define winShmMap     0
33600 # define winShmLock    0
33601 # define winShmBarrier 0
33602 # define winShmUnmap   0
33603 #endif /* #ifndef SQLITE_OMIT_WAL */
33604 
33605 /*
33606 ** Here ends the implementation of all sqlite3_file methods.
33607 **
33608 ********************** End sqlite3_file Methods *******************************
33609 ******************************************************************************/
33610 
33611 /*
33612 ** This vector defines all the methods that can operate on an
33613 ** sqlite3_file for win32.
33614 */
33615 static const sqlite3_io_methods winIoMethod = {
33616   2,                              /* iVersion */
33617   winClose,                       /* xClose */
33618   winRead,                        /* xRead */
33619   winWrite,                       /* xWrite */
33620   winTruncate,                    /* xTruncate */
33621   winSync,                        /* xSync */
33622   winFileSize,                    /* xFileSize */
33623   winLock,                        /* xLock */
33624   winUnlock,                      /* xUnlock */
33625   winCheckReservedLock,           /* xCheckReservedLock */
33626   winFileControl,                 /* xFileControl */
33627   winSectorSize,                  /* xSectorSize */
33628   winDeviceCharacteristics,       /* xDeviceCharacteristics */
33629   winShmMap,                      /* xShmMap */
33630   winShmLock,                     /* xShmLock */
33631   winShmBarrier,                  /* xShmBarrier */
33632   winShmUnmap                     /* xShmUnmap */
33633 };
33634 
33635 /****************************************************************************
33636 **************************** sqlite3_vfs methods ****************************
33637 **
33638 ** This division contains the implementation of methods on the
33639 ** sqlite3_vfs object.
33640 */
33641 
33642 /*
33643 ** Convert a UTF-8 filename into whatever form the underlying
33644 ** operating system wants filenames in.  Space to hold the result
33645 ** is obtained from malloc and must be freed by the calling
33646 ** function.
33647 */
33648 static void *convertUtf8Filename(const char *zFilename){
33649   void *zConverted = 0;
33650   if( isNT() ){
33651     zConverted = utf8ToUnicode(zFilename);
33652   }
33653 #ifdef SQLITE_WIN32_HAS_ANSI
33654   else{
33655     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33656   }
33657 #endif
33658   /* caller will handle out of memory */
33659   return zConverted;
33660 }
33661 
33662 /*
33663 ** Create a temporary file name in zBuf.  zBuf must be big enough to
33664 ** hold at pVfs->mxPathname characters.
33665 */
33666 static int getTempname(int nBuf, char *zBuf){
33667   static char zChars[] =
33668     "abcdefghijklmnopqrstuvwxyz"
33669     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33670     "0123456789";
33671   size_t i, j;
33672   int nTempPath;
33673   char zTempPath[MAX_PATH+2];
33674 
33675   /* It's odd to simulate an io-error here, but really this is just
33676   ** using the io-error infrastructure to test that SQLite handles this
33677   ** function failing.
33678   */
33679   SimulateIOError( return SQLITE_IOERR );
33680 
33681   memset(zTempPath, 0, MAX_PATH+2);
33682 
33683   if( sqlite3_temp_directory ){
33684     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33685   }
33686 #if !SQLITE_OS_WINRT
33687   else if( isNT() ){
33688     char *zMulti;
33689     WCHAR zWidePath[MAX_PATH];
33690     osGetTempPathW(MAX_PATH-30, zWidePath);
33691     zMulti = unicodeToUtf8(zWidePath);
33692     if( zMulti ){
33693       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33694       sqlite3_free(zMulti);
33695     }else{
33696       return SQLITE_IOERR_NOMEM;
33697     }
33698   }
33699 #ifdef SQLITE_WIN32_HAS_ANSI
33700   else{
33701     char *zUtf8;
33702     char zMbcsPath[MAX_PATH];
33703     osGetTempPathA(MAX_PATH-30, zMbcsPath);
33704     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33705     if( zUtf8 ){
33706       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33707       sqlite3_free(zUtf8);
33708     }else{
33709       return SQLITE_IOERR_NOMEM;
33710     }
33711   }
33712 #endif
33713 #endif
33714 
33715   /* Check that the output buffer is large enough for the temporary file
33716   ** name. If it is not, return SQLITE_ERROR.
33717   */
33718   nTempPath = sqlite3Strlen30(zTempPath);
33719 
33720   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
33721     return SQLITE_ERROR;
33722   }
33723 
33724   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
33725   zTempPath[i] = 0;
33726 
33727   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
33728                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
33729                    zTempPath);
33730   j = sqlite3Strlen30(zBuf);
33731   sqlite3_randomness(15, &zBuf[j]);
33732   for(i=0; i<15; i++, j++){
33733     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33734   }
33735   zBuf[j] = 0;
33736   zBuf[j+1] = 0;
33737 
33738   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33739   return SQLITE_OK;
33740 }
33741 
33742 /*
33743 ** Return TRUE if the named file is really a directory.  Return false if
33744 ** it is something other than a directory, or if there is any kind of memory
33745 ** allocation failure.
33746 */
33747 static int winIsDir(const void *zConverted){
33748   DWORD attr;
33749   int rc = 0;
33750   DWORD lastErrno;
33751 
33752   if( isNT() ){
33753     int cnt = 0;
33754     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33755     memset(&sAttrData, 0, sizeof(sAttrData));
33756     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
33757                              GetFileExInfoStandard,
33758                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
33759     if( !rc ){
33760       return 0; /* Invalid name? */
33761     }
33762     attr = sAttrData.dwFileAttributes;
33763 #if SQLITE_OS_WINCE==0
33764   }else{
33765     attr = osGetFileAttributesA((char*)zConverted);
33766 #endif
33767   }
33768   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
33769 }
33770 
33771 /*
33772 ** Open a file.
33773 */
33774 static int winOpen(
33775   sqlite3_vfs *pVfs,        /* Not used */
33776   const char *zName,        /* Name of the file (UTF-8) */
33777   sqlite3_file *id,         /* Write the SQLite file handle here */
33778   int flags,                /* Open mode flags */
33779   int *pOutFlags            /* Status return flags */
33780 ){
33781   HANDLE h;
33782   DWORD lastErrno;
33783   DWORD dwDesiredAccess;
33784   DWORD dwShareMode;
33785   DWORD dwCreationDisposition;
33786   DWORD dwFlagsAndAttributes = 0;
33787 #if SQLITE_OS_WINCE
33788   int isTemp = 0;
33789 #endif
33790   winFile *pFile = (winFile*)id;
33791   void *zConverted;              /* Filename in OS encoding */
33792   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33793   int cnt = 0;
33794 
33795   /* If argument zPath is a NULL pointer, this function is required to open
33796   ** a temporary file. Use this buffer to store the file name in.
33797   */
33798   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
33799 
33800   int rc = SQLITE_OK;            /* Function Return Code */
33801 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33802   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33803 #endif
33804 
33805   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33806   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33807   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33808 #ifndef NDEBUG
33809   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33810 #endif
33811   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33812 
33813 #ifndef NDEBUG
33814   int isOpenJournal = (isCreate && (
33815         eType==SQLITE_OPEN_MASTER_JOURNAL
33816      || eType==SQLITE_OPEN_MAIN_JOURNAL
33817      || eType==SQLITE_OPEN_WAL
33818   ));
33819 #endif
33820 
33821   /* Check the following statements are true:
33822   **
33823   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
33824   **   (b) if CREATE is set, then READWRITE must also be set, and
33825   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33826   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33827   */
33828   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33829   assert(isCreate==0 || isReadWrite);
33830   assert(isExclusive==0 || isCreate);
33831   assert(isDelete==0 || isCreate);
33832 
33833   /* The main DB, main journal, WAL file and master journal are never
33834   ** automatically deleted. Nor are they ever temporary files.  */
33835   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33836   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33837   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33838   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33839 
33840   /* Assert that the upper layer has set one of the "file-type" flags. */
33841   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
33842        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
33843        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
33844        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33845   );
33846 
33847   assert( pFile!=0 );
33848   memset(pFile, 0, sizeof(winFile));
33849   pFile->h = INVALID_HANDLE_VALUE;
33850 
33851 #if SQLITE_OS_WINRT
33852   if( !sqlite3_temp_directory ){
33853     sqlite3_log(SQLITE_ERROR,
33854         "sqlite3_temp_directory variable should be set for WinRT");
33855   }
33856 #endif
33857 
33858   /* If the second argument to this function is NULL, generate a
33859   ** temporary file name to use
33860   */
33861   if( !zUtf8Name ){
33862     assert(isDelete && !isOpenJournal);
33863     memset(zTmpname, 0, MAX_PATH+2);
33864     rc = getTempname(MAX_PATH+2, zTmpname);
33865     if( rc!=SQLITE_OK ){
33866       return rc;
33867     }
33868     zUtf8Name = zTmpname;
33869   }
33870 
33871   /* Database filenames are double-zero terminated if they are not
33872   ** URIs with parameters.  Hence, they can always be passed into
33873   ** sqlite3_uri_parameter().
33874   */
33875   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
33876         zUtf8Name[strlen(zUtf8Name)+1]==0 );
33877 
33878   /* Convert the filename to the system encoding. */
33879   zConverted = convertUtf8Filename(zUtf8Name);
33880   if( zConverted==0 ){
33881     return SQLITE_IOERR_NOMEM;
33882   }
33883 
33884   if( winIsDir(zConverted) ){
33885     sqlite3_free(zConverted);
33886     return SQLITE_CANTOPEN_ISDIR;
33887   }
33888 
33889   if( isReadWrite ){
33890     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33891   }else{
33892     dwDesiredAccess = GENERIC_READ;
33893   }
33894 
33895   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
33896   ** created. SQLite doesn't use it to indicate "exclusive access"
33897   ** as it is usually understood.
33898   */
33899   if( isExclusive ){
33900     /* Creates a new file, only if it does not already exist. */
33901     /* If the file exists, it fails. */
33902     dwCreationDisposition = CREATE_NEW;
33903   }else if( isCreate ){
33904     /* Open existing file, or create if it doesn't exist */
33905     dwCreationDisposition = OPEN_ALWAYS;
33906   }else{
33907     /* Opens a file, only if it exists. */
33908     dwCreationDisposition = OPEN_EXISTING;
33909   }
33910 
33911   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33912 
33913   if( isDelete ){
33914 #if SQLITE_OS_WINCE
33915     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33916     isTemp = 1;
33917 #else
33918     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33919                                | FILE_ATTRIBUTE_HIDDEN
33920                                | FILE_FLAG_DELETE_ON_CLOSE;
33921 #endif
33922   }else{
33923     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33924   }
33925   /* Reports from the internet are that performance is always
33926   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33927 #if SQLITE_OS_WINCE
33928   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33929 #endif
33930 
33931   if( isNT() ){
33932 #if SQLITE_OS_WINRT
33933     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
33934     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
33935     extendedParameters.dwFileAttributes =
33936             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
33937     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
33938     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
33939     extendedParameters.lpSecurityAttributes = NULL;
33940     extendedParameters.hTemplateFile = NULL;
33941     while( (h = osCreateFile2((LPCWSTR)zConverted,
33942                               dwDesiredAccess,
33943                               dwShareMode,
33944                               dwCreationDisposition,
33945                               &extendedParameters))==INVALID_HANDLE_VALUE &&
33946                               retryIoerr(&cnt, &lastErrno) ){
33947                /* Noop */
33948     }
33949 #else
33950     while( (h = osCreateFileW((LPCWSTR)zConverted,
33951                               dwDesiredAccess,
33952                               dwShareMode, NULL,
33953                               dwCreationDisposition,
33954                               dwFlagsAndAttributes,
33955                               NULL))==INVALID_HANDLE_VALUE &&
33956                               retryIoerr(&cnt, &lastErrno) ){
33957                /* Noop */
33958     }
33959 #endif
33960   }
33961 #ifdef SQLITE_WIN32_HAS_ANSI
33962   else{
33963     while( (h = osCreateFileA((LPCSTR)zConverted,
33964                               dwDesiredAccess,
33965                               dwShareMode, NULL,
33966                               dwCreationDisposition,
33967                               dwFlagsAndAttributes,
33968                               NULL))==INVALID_HANDLE_VALUE &&
33969                               retryIoerr(&cnt, &lastErrno) ){
33970                /* Noop */
33971     }
33972   }
33973 #endif
33974   logIoerr(cnt);
33975 
33976   OSTRACE(("OPEN %d %s 0x%lx %s\n",
33977            h, zName, dwDesiredAccess,
33978            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33979 
33980   if( h==INVALID_HANDLE_VALUE ){
33981     pFile->lastErrno = lastErrno;
33982     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
33983     sqlite3_free(zConverted);
33984     if( isReadWrite && !isExclusive ){
33985       return winOpen(pVfs, zName, id,
33986          ((flags|SQLITE_OPEN_READONLY) &
33987                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
33988          pOutFlags);
33989     }else{
33990       return SQLITE_CANTOPEN_BKPT;
33991     }
33992   }
33993 
33994   if( pOutFlags ){
33995     if( isReadWrite ){
33996       *pOutFlags = SQLITE_OPEN_READWRITE;
33997     }else{
33998       *pOutFlags = SQLITE_OPEN_READONLY;
33999     }
34000   }
34001 
34002 #if SQLITE_OS_WINCE
34003   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34004        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
34005   ){
34006     osCloseHandle(h);
34007     sqlite3_free(zConverted);
34008     return rc;
34009   }
34010   if( isTemp ){
34011     pFile->zDeleteOnClose = zConverted;
34012   }else
34013 #endif
34014   {
34015     sqlite3_free(zConverted);
34016   }
34017 
34018   pFile->pMethod = &winIoMethod;
34019   pFile->pVfs = pVfs;
34020   pFile->h = h;
34021   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34022     pFile->ctrlFlags |= WINFILE_PSOW;
34023   }
34024   pFile->lastErrno = NO_ERROR;
34025   pFile->zPath = zName;
34026 
34027   OpenCounter(+1);
34028   return rc;
34029 }
34030 
34031 /*
34032 ** Delete the named file.
34033 **
34034 ** Note that Windows does not allow a file to be deleted if some other
34035 ** process has it open.  Sometimes a virus scanner or indexing program
34036 ** will open a journal file shortly after it is created in order to do
34037 ** whatever it does.  While this other process is holding the
34038 ** file open, we will be unable to delete it.  To work around this
34039 ** problem, we delay 100 milliseconds and try to delete again.  Up
34040 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34041 ** up and returning an error.
34042 */
34043 static int winDelete(
34044   sqlite3_vfs *pVfs,          /* Not used on win32 */
34045   const char *zFilename,      /* Name of file to delete */
34046   int syncDir                 /* Not used on win32 */
34047 ){
34048   int cnt = 0;
34049   int rc;
34050   DWORD attr;
34051   DWORD lastErrno;
34052   void *zConverted;
34053   UNUSED_PARAMETER(pVfs);
34054   UNUSED_PARAMETER(syncDir);
34055 
34056   SimulateIOError(return SQLITE_IOERR_DELETE);
34057   zConverted = convertUtf8Filename(zFilename);
34058   if( zConverted==0 ){
34059     return SQLITE_IOERR_NOMEM;
34060   }
34061   if( isNT() ){
34062     do {
34063 #if SQLITE_OS_WINRT
34064       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34065       memset(&sAttrData, 0, sizeof(sAttrData));
34066       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
34067                                   &sAttrData) ){
34068         attr = sAttrData.dwFileAttributes;
34069       }else{
34070         lastErrno = osGetLastError();
34071         if( lastErrno==ERROR_FILE_NOT_FOUND
34072          || lastErrno==ERROR_PATH_NOT_FOUND ){
34073           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34074         }else{
34075           rc = SQLITE_ERROR;
34076         }
34077         break;
34078       }
34079 #else
34080       attr = osGetFileAttributesW(zConverted);
34081 #endif
34082       if ( attr==INVALID_FILE_ATTRIBUTES ){
34083         lastErrno = osGetLastError();
34084         if( lastErrno==ERROR_FILE_NOT_FOUND
34085          || lastErrno==ERROR_PATH_NOT_FOUND ){
34086           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34087         }else{
34088           rc = SQLITE_ERROR;
34089         }
34090         break;
34091       }
34092       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
34093         rc = SQLITE_ERROR; /* Files only. */
34094         break;
34095       }
34096       if ( osDeleteFileW(zConverted) ){
34097         rc = SQLITE_OK; /* Deleted OK. */
34098         break;
34099       }
34100       if ( !retryIoerr(&cnt, &lastErrno) ){
34101         rc = SQLITE_ERROR; /* No more retries. */
34102         break;
34103       }
34104     } while(1);
34105   }
34106 #ifdef SQLITE_WIN32_HAS_ANSI
34107   else{
34108     do {
34109       attr = osGetFileAttributesA(zConverted);
34110       if ( attr==INVALID_FILE_ATTRIBUTES ){
34111         lastErrno = osGetLastError();
34112         if( lastErrno==ERROR_FILE_NOT_FOUND
34113          || lastErrno==ERROR_PATH_NOT_FOUND ){
34114           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
34115         }else{
34116           rc = SQLITE_ERROR;
34117         }
34118         break;
34119       }
34120       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
34121         rc = SQLITE_ERROR; /* Files only. */
34122         break;
34123       }
34124       if ( osDeleteFileA(zConverted) ){
34125         rc = SQLITE_OK; /* Deleted OK. */
34126         break;
34127       }
34128       if ( !retryIoerr(&cnt, &lastErrno) ){
34129         rc = SQLITE_ERROR; /* No more retries. */
34130         break;
34131       }
34132     } while(1);
34133   }
34134 #endif
34135   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
34136     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
34137              "winDelete", zFilename);
34138   }else{
34139     logIoerr(cnt);
34140   }
34141   sqlite3_free(zConverted);
34142   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
34143   return rc;
34144 }
34145 
34146 /*
34147 ** Check the existence and status of a file.
34148 */
34149 static int winAccess(
34150   sqlite3_vfs *pVfs,         /* Not used on win32 */
34151   const char *zFilename,     /* Name of file to check */
34152   int flags,                 /* Type of test to make on this file */
34153   int *pResOut               /* OUT: Result */
34154 ){
34155   DWORD attr;
34156   int rc = 0;
34157   DWORD lastErrno;
34158   void *zConverted;
34159   UNUSED_PARAMETER(pVfs);
34160 
34161   SimulateIOError( return SQLITE_IOERR_ACCESS; );
34162   zConverted = convertUtf8Filename(zFilename);
34163   if( zConverted==0 ){
34164     return SQLITE_IOERR_NOMEM;
34165   }
34166   if( isNT() ){
34167     int cnt = 0;
34168     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34169     memset(&sAttrData, 0, sizeof(sAttrData));
34170     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
34171                              GetFileExInfoStandard,
34172                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
34173     if( rc ){
34174       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
34175       ** as if it does not exist.
34176       */
34177       if(    flags==SQLITE_ACCESS_EXISTS
34178           && sAttrData.nFileSizeHigh==0
34179           && sAttrData.nFileSizeLow==0 ){
34180         attr = INVALID_FILE_ATTRIBUTES;
34181       }else{
34182         attr = sAttrData.dwFileAttributes;
34183       }
34184     }else{
34185       logIoerr(cnt);
34186       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
34187         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
34188         sqlite3_free(zConverted);
34189         return SQLITE_IOERR_ACCESS;
34190       }else{
34191         attr = INVALID_FILE_ATTRIBUTES;
34192       }
34193     }
34194   }
34195 #ifdef SQLITE_WIN32_HAS_ANSI
34196   else{
34197     attr = osGetFileAttributesA((char*)zConverted);
34198   }
34199 #endif
34200   sqlite3_free(zConverted);
34201   switch( flags ){
34202     case SQLITE_ACCESS_READ:
34203     case SQLITE_ACCESS_EXISTS:
34204       rc = attr!=INVALID_FILE_ATTRIBUTES;
34205       break;
34206     case SQLITE_ACCESS_READWRITE:
34207       rc = attr!=INVALID_FILE_ATTRIBUTES &&
34208              (attr & FILE_ATTRIBUTE_READONLY)==0;
34209       break;
34210     default:
34211       assert(!"Invalid flags argument");
34212   }
34213   *pResOut = rc;
34214   return SQLITE_OK;
34215 }
34216 
34217 
34218 /*
34219 ** Returns non-zero if the specified path name should be used verbatim.  If
34220 ** non-zero is returned from this function, the calling function must simply
34221 ** use the provided path name verbatim -OR- resolve it into a full path name
34222 ** using the GetFullPathName Win32 API function (if available).
34223 */
34224 static BOOL winIsVerbatimPathname(
34225   const char *zPathname
34226 ){
34227   /*
34228   ** If the path name starts with a forward slash or a backslash, it is either
34229   ** a legal UNC name, a volume relative path, or an absolute path name in the
34230   ** "Unix" format on Windows.  There is no easy way to differentiate between
34231   ** the final two cases; therefore, we return the safer return value of TRUE
34232   ** so that callers of this function will simply use it verbatim.
34233   */
34234   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
34235     return TRUE;
34236   }
34237 
34238   /*
34239   ** If the path name starts with a letter and a colon it is either a volume
34240   ** relative path or an absolute path.  Callers of this function must not
34241   ** attempt to treat it as a relative path name (i.e. they should simply use
34242   ** it verbatim).
34243   */
34244   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
34245     return TRUE;
34246   }
34247 
34248   /*
34249   ** If we get to this point, the path name should almost certainly be a purely
34250   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
34251   */
34252   return FALSE;
34253 }
34254 
34255 /*
34256 ** Turn a relative pathname into a full pathname.  Write the full
34257 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
34258 ** bytes in size.
34259 */
34260 static int winFullPathname(
34261   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
34262   const char *zRelative,        /* Possibly relative input path */
34263   int nFull,                    /* Size of output buffer in bytes */
34264   char *zFull                   /* Output buffer */
34265 ){
34266 
34267 #if defined(__CYGWIN__)
34268   SimulateIOError( return SQLITE_ERROR );
34269   UNUSED_PARAMETER(nFull);
34270   assert( pVfs->mxPathname>=MAX_PATH );
34271   assert( nFull>=pVfs->mxPathname );
34272   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34273     /*
34274     ** NOTE: We are dealing with a relative path name and the data
34275     **       directory has been set.  Therefore, use it as the basis
34276     **       for converting the relative path name to an absolute
34277     **       one by prepending the data directory and a slash.
34278     */
34279     char zOut[MAX_PATH+1];
34280     memset(zOut, 0, MAX_PATH+1);
34281     cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
34282                      MAX_PATH+1);
34283     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34284                      sqlite3_data_directory, zOut);
34285   }else{
34286     cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
34287   }
34288   return SQLITE_OK;
34289 #endif
34290 
34291 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
34292   SimulateIOError( return SQLITE_ERROR );
34293   /* WinCE has no concept of a relative pathname, or so I am told. */
34294   /* WinRT has no way to convert a relative path to an absolute one. */
34295   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34296     /*
34297     ** NOTE: We are dealing with a relative path name and the data
34298     **       directory has been set.  Therefore, use it as the basis
34299     **       for converting the relative path name to an absolute
34300     **       one by prepending the data directory and a backslash.
34301     */
34302     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34303                      sqlite3_data_directory, zRelative);
34304   }else{
34305     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
34306   }
34307   return SQLITE_OK;
34308 #endif
34309 
34310 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
34311   DWORD nByte;
34312   void *zConverted;
34313   char *zOut;
34314 
34315   /* If this path name begins with "/X:", where "X" is any alphabetic
34316   ** character, discard the initial "/" from the pathname.
34317   */
34318   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
34319     zRelative++;
34320   }
34321 
34322   /* It's odd to simulate an io-error here, but really this is just
34323   ** using the io-error infrastructure to test that SQLite handles this
34324   ** function failing. This function could fail if, for example, the
34325   ** current working directory has been unlinked.
34326   */
34327   SimulateIOError( return SQLITE_ERROR );
34328   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
34329     /*
34330     ** NOTE: We are dealing with a relative path name and the data
34331     **       directory has been set.  Therefore, use it as the basis
34332     **       for converting the relative path name to an absolute
34333     **       one by prepending the data directory and a backslash.
34334     */
34335     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
34336                      sqlite3_data_directory, zRelative);
34337     return SQLITE_OK;
34338   }
34339   zConverted = convertUtf8Filename(zRelative);
34340   if( zConverted==0 ){
34341     return SQLITE_IOERR_NOMEM;
34342   }
34343   if( isNT() ){
34344     LPWSTR zTemp;
34345     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
34346     if( nByte==0 ){
34347       winLogError(SQLITE_ERROR, osGetLastError(),
34348                   "GetFullPathNameW1", zConverted);
34349       sqlite3_free(zConverted);
34350       return SQLITE_CANTOPEN_FULLPATH;
34351     }
34352     nByte += 3;
34353     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
34354     if( zTemp==0 ){
34355       sqlite3_free(zConverted);
34356       return SQLITE_IOERR_NOMEM;
34357     }
34358     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
34359     if( nByte==0 ){
34360       winLogError(SQLITE_ERROR, osGetLastError(),
34361                   "GetFullPathNameW2", zConverted);
34362       sqlite3_free(zConverted);
34363       sqlite3_free(zTemp);
34364       return SQLITE_CANTOPEN_FULLPATH;
34365     }
34366     sqlite3_free(zConverted);
34367     zOut = unicodeToUtf8(zTemp);
34368     sqlite3_free(zTemp);
34369   }
34370 #ifdef SQLITE_WIN32_HAS_ANSI
34371   else{
34372     char *zTemp;
34373     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
34374     if( nByte==0 ){
34375       winLogError(SQLITE_ERROR, osGetLastError(),
34376                   "GetFullPathNameA1", zConverted);
34377       sqlite3_free(zConverted);
34378       return SQLITE_CANTOPEN_FULLPATH;
34379     }
34380     nByte += 3;
34381     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
34382     if( zTemp==0 ){
34383       sqlite3_free(zConverted);
34384       return SQLITE_IOERR_NOMEM;
34385     }
34386     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
34387     if( nByte==0 ){
34388       winLogError(SQLITE_ERROR, osGetLastError(),
34389                   "GetFullPathNameA2", zConverted);
34390       sqlite3_free(zConverted);
34391       sqlite3_free(zTemp);
34392       return SQLITE_CANTOPEN_FULLPATH;
34393     }
34394     sqlite3_free(zConverted);
34395     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34396     sqlite3_free(zTemp);
34397   }
34398 #endif
34399   if( zOut ){
34400     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
34401     sqlite3_free(zOut);
34402     return SQLITE_OK;
34403   }else{
34404     return SQLITE_IOERR_NOMEM;
34405   }
34406 #endif
34407 }
34408 
34409 #ifndef SQLITE_OMIT_LOAD_EXTENSION
34410 /*
34411 ** Interfaces for opening a shared library, finding entry points
34412 ** within the shared library, and closing the shared library.
34413 */
34414 /*
34415 ** Interfaces for opening a shared library, finding entry points
34416 ** within the shared library, and closing the shared library.
34417 */
34418 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
34419   HANDLE h;
34420   void *zConverted = convertUtf8Filename(zFilename);
34421   UNUSED_PARAMETER(pVfs);
34422   if( zConverted==0 ){
34423     return 0;
34424   }
34425   if( isNT() ){
34426 #if SQLITE_OS_WINRT
34427     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
34428 #else
34429     h = osLoadLibraryW((LPCWSTR)zConverted);
34430 #endif
34431   }
34432 #ifdef SQLITE_WIN32_HAS_ANSI
34433   else{
34434     h = osLoadLibraryA((char*)zConverted);
34435   }
34436 #endif
34437   sqlite3_free(zConverted);
34438   return (void*)h;
34439 }
34440 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34441   UNUSED_PARAMETER(pVfs);
34442   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
34443 }
34444 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
34445   UNUSED_PARAMETER(pVfs);
34446   return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
34447 }
34448 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34449   UNUSED_PARAMETER(pVfs);
34450   osFreeLibrary((HANDLE)pHandle);
34451 }
34452 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34453   #define winDlOpen  0
34454   #define winDlError 0
34455   #define winDlSym   0
34456   #define winDlClose 0
34457 #endif
34458 
34459 
34460 /*
34461 ** Write up to nBuf bytes of randomness into zBuf.
34462 */
34463 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34464   int n = 0;
34465   UNUSED_PARAMETER(pVfs);
34466 #if defined(SQLITE_TEST)
34467   n = nBuf;
34468   memset(zBuf, 0, nBuf);
34469 #else
34470   if( sizeof(SYSTEMTIME)<=nBuf-n ){
34471     SYSTEMTIME x;
34472     osGetSystemTime(&x);
34473     memcpy(&zBuf[n], &x, sizeof(x));
34474     n += sizeof(x);
34475   }
34476   if( sizeof(DWORD)<=nBuf-n ){
34477     DWORD pid = osGetCurrentProcessId();
34478     memcpy(&zBuf[n], &pid, sizeof(pid));
34479     n += sizeof(pid);
34480   }
34481 #if SQLITE_OS_WINRT
34482   if( sizeof(ULONGLONG)<=nBuf-n ){
34483     ULONGLONG cnt = osGetTickCount64();
34484     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34485     n += sizeof(cnt);
34486   }
34487 #else
34488   if( sizeof(DWORD)<=nBuf-n ){
34489     DWORD cnt = osGetTickCount();
34490     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34491     n += sizeof(cnt);
34492   }
34493 #endif
34494   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34495     LARGE_INTEGER i;
34496     osQueryPerformanceCounter(&i);
34497     memcpy(&zBuf[n], &i, sizeof(i));
34498     n += sizeof(i);
34499   }
34500 #endif
34501   return n;
34502 }
34503 
34504 
34505 /*
34506 ** Sleep for a little while.  Return the amount of time slept.
34507 */
34508 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34509   sqlite3_win32_sleep((microsec+999)/1000);
34510   UNUSED_PARAMETER(pVfs);
34511   return ((microsec+999)/1000)*1000;
34512 }
34513 
34514 /*
34515 ** The following variable, if set to a non-zero value, is interpreted as
34516 ** the number of seconds since 1970 and is used to set the result of
34517 ** sqlite3OsCurrentTime() during testing.
34518 */
34519 #ifdef SQLITE_TEST
34520 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
34521 #endif
34522 
34523 /*
34524 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
34525 ** the current time and date as a Julian Day number times 86_400_000.  In
34526 ** other words, write into *piNow the number of milliseconds since the Julian
34527 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34528 ** proleptic Gregorian calendar.
34529 **
34530 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
34531 ** cannot be found.
34532 */
34533 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34534   /* FILETIME structure is a 64-bit value representing the number of
34535      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
34536   */
34537   FILETIME ft;
34538   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34539 #ifdef SQLITE_TEST
34540   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34541 #endif
34542   /* 2^32 - to avoid use of LL and warnings in gcc */
34543   static const sqlite3_int64 max32BitValue =
34544       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
34545       (sqlite3_int64)294967296;
34546 
34547 #if SQLITE_OS_WINCE
34548   SYSTEMTIME time;
34549   osGetSystemTime(&time);
34550   /* if SystemTimeToFileTime() fails, it returns zero. */
34551   if (!osSystemTimeToFileTime(&time,&ft)){
34552     return SQLITE_ERROR;
34553   }
34554 #else
34555   osGetSystemTimeAsFileTime( &ft );
34556 #endif
34557 
34558   *piNow = winFiletimeEpoch +
34559             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
34560                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34561 
34562 #ifdef SQLITE_TEST
34563   if( sqlite3_current_time ){
34564     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34565   }
34566 #endif
34567   UNUSED_PARAMETER(pVfs);
34568   return SQLITE_OK;
34569 }
34570 
34571 /*
34572 ** Find the current time (in Universal Coordinated Time).  Write the
34573 ** current time and date as a Julian Day number into *prNow and
34574 ** return 0.  Return 1 if the time and date cannot be found.
34575 */
34576 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34577   int rc;
34578   sqlite3_int64 i;
34579   rc = winCurrentTimeInt64(pVfs, &i);
34580   if( !rc ){
34581     *prNow = i/86400000.0;
34582   }
34583   return rc;
34584 }
34585 
34586 /*
34587 ** The idea is that this function works like a combination of
34588 ** GetLastError() and FormatMessage() on Windows (or errno and
34589 ** strerror_r() on Unix). After an error is returned by an OS
34590 ** function, SQLite calls this function with zBuf pointing to
34591 ** a buffer of nBuf bytes. The OS layer should populate the
34592 ** buffer with a nul-terminated UTF-8 encoded error message
34593 ** describing the last IO error to have occurred within the calling
34594 ** thread.
34595 **
34596 ** If the error message is too large for the supplied buffer,
34597 ** it should be truncated. The return value of xGetLastError
34598 ** is zero if the error message fits in the buffer, or non-zero
34599 ** otherwise (if the message was truncated). If non-zero is returned,
34600 ** then it is not necessary to include the nul-terminator character
34601 ** in the output buffer.
34602 **
34603 ** Not supplying an error message will have no adverse effect
34604 ** on SQLite. It is fine to have an implementation that never
34605 ** returns an error message:
34606 **
34607 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34608 **     assert(zBuf[0]=='\0');
34609 **     return 0;
34610 **   }
34611 **
34612 ** However if an error message is supplied, it will be incorporated
34613 ** by sqlite into the error message available to the user using
34614 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34615 */
34616 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34617   UNUSED_PARAMETER(pVfs);
34618   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
34619 }
34620 
34621 /*
34622 ** Initialize and deinitialize the operating system interface.
34623 */
34624 SQLITE_API int sqlite3_os_init(void){
34625   static sqlite3_vfs winVfs = {
34626     3,                   /* iVersion */
34627     sizeof(winFile),     /* szOsFile */
34628     MAX_PATH,            /* mxPathname */
34629     0,                   /* pNext */
34630     "win32",             /* zName */
34631     0,                   /* pAppData */
34632     winOpen,             /* xOpen */
34633     winDelete,           /* xDelete */
34634     winAccess,           /* xAccess */
34635     winFullPathname,     /* xFullPathname */
34636     winDlOpen,           /* xDlOpen */
34637     winDlError,          /* xDlError */
34638     winDlSym,            /* xDlSym */
34639     winDlClose,          /* xDlClose */
34640     winRandomness,       /* xRandomness */
34641     winSleep,            /* xSleep */
34642     winCurrentTime,      /* xCurrentTime */
34643     winGetLastError,     /* xGetLastError */
34644     winCurrentTimeInt64, /* xCurrentTimeInt64 */
34645     winSetSystemCall,    /* xSetSystemCall */
34646     winGetSystemCall,    /* xGetSystemCall */
34647     winNextSystemCall,   /* xNextSystemCall */
34648   };
34649 
34650   /* Double-check that the aSyscall[] array has been constructed
34651   ** correctly.  See ticket [bb3a86e890c8e96ab] */
34652   assert( ArraySize(aSyscall)==74 );
34653 
34654 #ifndef SQLITE_OMIT_WAL
34655   /* get memory map allocation granularity */
34656   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34657 #if SQLITE_OS_WINRT
34658   osGetNativeSystemInfo(&winSysInfo);
34659 #else
34660   osGetSystemInfo(&winSysInfo);
34661 #endif
34662   assert(winSysInfo.dwAllocationGranularity > 0);
34663 #endif
34664 
34665   sqlite3_vfs_register(&winVfs, 1);
34666   return SQLITE_OK;
34667 }
34668 
34669 SQLITE_API int sqlite3_os_end(void){
34670 #if SQLITE_OS_WINRT
34671   if( sleepObj!=NULL ){
34672     osCloseHandle(sleepObj);
34673     sleepObj = NULL;
34674   }
34675 #endif
34676   return SQLITE_OK;
34677 }
34678 
34679 #endif /* SQLITE_OS_WIN */
34680 
34681 /************** End of os_win.c **********************************************/
34682 /************** Begin file bitvec.c ******************************************/
34683 /*
34684 ** 2008 February 16
34685 **
34686 ** The author disclaims copyright to this source code.  In place of
34687 ** a legal notice, here is a blessing:
34688 **
34689 **    May you do good and not evil.
34690 **    May you find forgiveness for yourself and forgive others.
34691 **    May you share freely, never taking more than you give.
34692 **
34693 *************************************************************************
34694 ** This file implements an object that represents a fixed-length
34695 ** bitmap.  Bits are numbered starting with 1.
34696 **
34697 ** A bitmap is used to record which pages of a database file have been
34698 ** journalled during a transaction, or which pages have the "dont-write"
34699 ** property.  Usually only a few pages are meet either condition.
34700 ** So the bitmap is usually sparse and has low cardinality.
34701 ** But sometimes (for example when during a DROP of a large table) most
34702 ** or all of the pages in a database can get journalled.  In those cases,
34703 ** the bitmap becomes dense with high cardinality.  The algorithm needs
34704 ** to handle both cases well.
34705 **
34706 ** The size of the bitmap is fixed when the object is created.
34707 **
34708 ** All bits are clear when the bitmap is created.  Individual bits
34709 ** may be set or cleared one at a time.
34710 **
34711 ** Test operations are about 100 times more common that set operations.
34712 ** Clear operations are exceedingly rare.  There are usually between
34713 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34714 ** sometimes grow into tens of thousands or larger.  The size of the
34715 ** Bitvec object is the number of pages in the database file at the
34716 ** start of a transaction, and is thus usually less than a few thousand,
34717 ** but can be as large as 2 billion for a really big database.
34718 */
34719 
34720 /* Size of the Bitvec structure in bytes. */
34721 #define BITVEC_SZ        512
34722 
34723 /* Round the union size down to the nearest pointer boundary, since that's how
34724 ** it will be aligned within the Bitvec struct. */
34725 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34726 
34727 /* Type of the array "element" for the bitmap representation.
34728 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
34729 ** Setting this to the "natural word" size of your CPU may improve
34730 ** performance. */
34731 #define BITVEC_TELEM     u8
34732 /* Size, in bits, of the bitmap element. */
34733 #define BITVEC_SZELEM    8
34734 /* Number of elements in a bitmap array. */
34735 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34736 /* Number of bits in the bitmap array. */
34737 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
34738 
34739 /* Number of u32 values in hash table. */
34740 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
34741 /* Maximum number of entries in hash table before
34742 ** sub-dividing and re-hashing. */
34743 #define BITVEC_MXHASH    (BITVEC_NINT/2)
34744 /* Hashing function for the aHash representation.
34745 ** Empirical testing showed that the *37 multiplier
34746 ** (an arbitrary prime)in the hash function provided
34747 ** no fewer collisions than the no-op *1. */
34748 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
34749 
34750 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
34751 
34752 
34753 /*
34754 ** A bitmap is an instance of the following structure.
34755 **
34756 ** This bitmap records the existence of zero or more bits
34757 ** with values between 1 and iSize, inclusive.
34758 **
34759 ** There are three possible representations of the bitmap.
34760 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34761 ** bitmap.  The least significant bit is bit 1.
34762 **
34763 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34764 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34765 **
34766 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34767 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34768 ** handles up to iDivisor separate values of i.  apSub[0] holds
34769 ** values between 1 and iDivisor.  apSub[1] holds values between
34770 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34771 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34772 ** to hold deal with values between 1 and iDivisor.
34773 */
34774 struct Bitvec {
34775   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34776   u32 nSet;       /* Number of bits that are set - only valid for aHash
34777                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34778                   ** this would be 125. */
34779   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34780                   /* Should >=0 for apSub element. */
34781                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34782                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34783   union {
34784     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34785     u32 aHash[BITVEC_NINT];      /* Hash table representation */
34786     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34787   } u;
34788 };
34789 
34790 /*
34791 ** Create a new bitmap object able to handle bits between 0 and iSize,
34792 ** inclusive.  Return a pointer to the new object.  Return NULL if
34793 ** malloc fails.
34794 */
34795 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34796   Bitvec *p;
34797   assert( sizeof(*p)==BITVEC_SZ );
34798   p = sqlite3MallocZero( sizeof(*p) );
34799   if( p ){
34800     p->iSize = iSize;
34801   }
34802   return p;
34803 }
34804 
34805 /*
34806 ** Check to see if the i-th bit is set.  Return true or false.
34807 ** If p is NULL (if the bitmap has not been created) or if
34808 ** i is out of range, then return false.
34809 */
34810 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34811   if( p==0 ) return 0;
34812   if( i>p->iSize || i==0 ) return 0;
34813   i--;
34814   while( p->iDivisor ){
34815     u32 bin = i/p->iDivisor;
34816     i = i%p->iDivisor;
34817     p = p->u.apSub[bin];
34818     if (!p) {
34819       return 0;
34820     }
34821   }
34822   if( p->iSize<=BITVEC_NBIT ){
34823     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34824   } else{
34825     u32 h = BITVEC_HASH(i++);
34826     while( p->u.aHash[h] ){
34827       if( p->u.aHash[h]==i ) return 1;
34828       h = (h+1) % BITVEC_NINT;
34829     }
34830     return 0;
34831   }
34832 }
34833 
34834 /*
34835 ** Set the i-th bit.  Return 0 on success and an error code if
34836 ** anything goes wrong.
34837 **
34838 ** This routine might cause sub-bitmaps to be allocated.  Failing
34839 ** to get the memory needed to hold the sub-bitmap is the only
34840 ** that can go wrong with an insert, assuming p and i are valid.
34841 **
34842 ** The calling function must ensure that p is a valid Bitvec object
34843 ** and that the value for "i" is within range of the Bitvec object.
34844 ** Otherwise the behavior is undefined.
34845 */
34846 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34847   u32 h;
34848   if( p==0 ) return SQLITE_OK;
34849   assert( i>0 );
34850   assert( i<=p->iSize );
34851   i--;
34852   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34853     u32 bin = i/p->iDivisor;
34854     i = i%p->iDivisor;
34855     if( p->u.apSub[bin]==0 ){
34856       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34857       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34858     }
34859     p = p->u.apSub[bin];
34860   }
34861   if( p->iSize<=BITVEC_NBIT ){
34862     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34863     return SQLITE_OK;
34864   }
34865   h = BITVEC_HASH(i++);
34866   /* if there wasn't a hash collision, and this doesn't */
34867   /* completely fill the hash, then just add it without */
34868   /* worring about sub-dividing and re-hashing. */
34869   if( !p->u.aHash[h] ){
34870     if (p->nSet<(BITVEC_NINT-1)) {
34871       goto bitvec_set_end;
34872     } else {
34873       goto bitvec_set_rehash;
34874     }
34875   }
34876   /* there was a collision, check to see if it's already */
34877   /* in hash, if not, try to find a spot for it */
34878   do {
34879     if( p->u.aHash[h]==i ) return SQLITE_OK;
34880     h++;
34881     if( h>=BITVEC_NINT ) h = 0;
34882   } while( p->u.aHash[h] );
34883   /* we didn't find it in the hash.  h points to the first */
34884   /* available free spot. check to see if this is going to */
34885   /* make our hash too "full".  */
34886 bitvec_set_rehash:
34887   if( p->nSet>=BITVEC_MXHASH ){
34888     unsigned int j;
34889     int rc;
34890     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34891     if( aiValues==0 ){
34892       return SQLITE_NOMEM;
34893     }else{
34894       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34895       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34896       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34897       rc = sqlite3BitvecSet(p, i);
34898       for(j=0; j<BITVEC_NINT; j++){
34899         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34900       }
34901       sqlite3StackFree(0, aiValues);
34902       return rc;
34903     }
34904   }
34905 bitvec_set_end:
34906   p->nSet++;
34907   p->u.aHash[h] = i;
34908   return SQLITE_OK;
34909 }
34910 
34911 /*
34912 ** Clear the i-th bit.
34913 **
34914 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34915 ** that BitvecClear can use to rebuilt its hash table.
34916 */
34917 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34918   if( p==0 ) return;
34919   assert( i>0 );
34920   i--;
34921   while( p->iDivisor ){
34922     u32 bin = i/p->iDivisor;
34923     i = i%p->iDivisor;
34924     p = p->u.apSub[bin];
34925     if (!p) {
34926       return;
34927     }
34928   }
34929   if( p->iSize<=BITVEC_NBIT ){
34930     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34931   }else{
34932     unsigned int j;
34933     u32 *aiValues = pBuf;
34934     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34935     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34936     p->nSet = 0;
34937     for(j=0; j<BITVEC_NINT; j++){
34938       if( aiValues[j] && aiValues[j]!=(i+1) ){
34939         u32 h = BITVEC_HASH(aiValues[j]-1);
34940         p->nSet++;
34941         while( p->u.aHash[h] ){
34942           h++;
34943           if( h>=BITVEC_NINT ) h = 0;
34944         }
34945         p->u.aHash[h] = aiValues[j];
34946       }
34947     }
34948   }
34949 }
34950 
34951 /*
34952 ** Destroy a bitmap object.  Reclaim all memory used.
34953 */
34954 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34955   if( p==0 ) return;
34956   if( p->iDivisor ){
34957     unsigned int i;
34958     for(i=0; i<BITVEC_NPTR; i++){
34959       sqlite3BitvecDestroy(p->u.apSub[i]);
34960     }
34961   }
34962   sqlite3_free(p);
34963 }
34964 
34965 /*
34966 ** Return the value of the iSize parameter specified when Bitvec *p
34967 ** was created.
34968 */
34969 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34970   return p->iSize;
34971 }
34972 
34973 #ifndef SQLITE_OMIT_BUILTIN_TEST
34974 /*
34975 ** Let V[] be an array of unsigned characters sufficient to hold
34976 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34977 ** Then the following macros can be used to set, clear, or test
34978 ** individual bits within V.
34979 */
34980 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34981 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34982 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34983 
34984 /*
34985 ** This routine runs an extensive test of the Bitvec code.
34986 **
34987 ** The input is an array of integers that acts as a program
34988 ** to test the Bitvec.  The integers are opcodes followed
34989 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34990 ** opcode follows immediately after the last operand.
34991 **
34992 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34993 ** "halt" opcode and causes the test to end.
34994 **
34995 **    0          Halt and return the number of errors
34996 **    1 N S X    Set N bits beginning with S and incrementing by X
34997 **    2 N S X    Clear N bits beginning with S and incrementing by X
34998 **    3 N        Set N randomly chosen bits
34999 **    4 N        Clear N randomly chosen bits
35000 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
35001 **
35002 ** The opcodes 1 through 4 perform set and clear operations are performed
35003 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
35004 ** Opcode 5 works on the linear array only, not on the Bitvec.
35005 ** Opcode 5 is used to deliberately induce a fault in order to
35006 ** confirm that error detection works.
35007 **
35008 ** At the conclusion of the test the linear array is compared
35009 ** against the Bitvec object.  If there are any differences,
35010 ** an error is returned.  If they are the same, zero is returned.
35011 **
35012 ** If a memory allocation error occurs, return -1.
35013 */
35014 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35015   Bitvec *pBitvec = 0;
35016   unsigned char *pV = 0;
35017   int rc = -1;
35018   int i, nx, pc, op;
35019   void *pTmpSpace;
35020 
35021   /* Allocate the Bitvec to be tested and a linear array of
35022   ** bits to act as the reference */
35023   pBitvec = sqlite3BitvecCreate( sz );
35024   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
35025   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35026   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
35027 
35028   /* NULL pBitvec tests */
35029   sqlite3BitvecSet(0, 1);
35030   sqlite3BitvecClear(0, 1, pTmpSpace);
35031 
35032   /* Run the program */
35033   pc = 0;
35034   while( (op = aOp[pc])!=0 ){
35035     switch( op ){
35036       case 1:
35037       case 2:
35038       case 5: {
35039         nx = 4;
35040         i = aOp[pc+2] - 1;
35041         aOp[pc+2] += aOp[pc+3];
35042         break;
35043       }
35044       case 3:
35045       case 4:
35046       default: {
35047         nx = 2;
35048         sqlite3_randomness(sizeof(i), &i);
35049         break;
35050       }
35051     }
35052     if( (--aOp[pc+1]) > 0 ) nx = 0;
35053     pc += nx;
35054     i = (i & 0x7fffffff)%sz;
35055     if( (op & 1)!=0 ){
35056       SETBIT(pV, (i+1));
35057       if( op!=5 ){
35058         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
35059       }
35060     }else{
35061       CLEARBIT(pV, (i+1));
35062       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
35063     }
35064   }
35065 
35066   /* Test to make sure the linear array exactly matches the
35067   ** Bitvec object.  Start with the assumption that they do
35068   ** match (rc==0).  Change rc to non-zero if a discrepancy
35069   ** is found.
35070   */
35071   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
35072           + sqlite3BitvecTest(pBitvec, 0)
35073           + (sqlite3BitvecSize(pBitvec) - sz);
35074   for(i=1; i<=sz; i++){
35075     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
35076       rc = i;
35077       break;
35078     }
35079   }
35080 
35081   /* Free allocated structure */
35082 bitvec_end:
35083   sqlite3_free(pTmpSpace);
35084   sqlite3_free(pV);
35085   sqlite3BitvecDestroy(pBitvec);
35086   return rc;
35087 }
35088 #endif /* SQLITE_OMIT_BUILTIN_TEST */
35089 
35090 /************** End of bitvec.c **********************************************/
35091 /************** Begin file pcache.c ******************************************/
35092 /*
35093 ** 2008 August 05
35094 **
35095 ** The author disclaims copyright to this source code.  In place of
35096 ** a legal notice, here is a blessing:
35097 **
35098 **    May you do good and not evil.
35099 **    May you find forgiveness for yourself and forgive others.
35100 **    May you share freely, never taking more than you give.
35101 **
35102 *************************************************************************
35103 ** This file implements that page cache.
35104 */
35105 
35106 /*
35107 ** A complete page cache is an instance of this structure.
35108 */
35109 struct PCache {
35110   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
35111   PgHdr *pSynced;                     /* Last synced page in dirty page list */
35112   int nRef;                           /* Number of referenced pages */
35113   int szCache;                        /* Configured cache size */
35114   int szPage;                         /* Size of every page in this cache */
35115   int szExtra;                        /* Size of extra space for each page */
35116   int bPurgeable;                     /* True if pages are on backing store */
35117   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
35118   void *pStress;                      /* Argument to xStress */
35119   sqlite3_pcache *pCache;             /* Pluggable cache module */
35120   PgHdr *pPage1;                      /* Reference to page 1 */
35121 };
35122 
35123 /*
35124 ** Some of the assert() macros in this code are too expensive to run
35125 ** even during normal debugging.  Use them only rarely on long-running
35126 ** tests.  Enable the expensive asserts using the
35127 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
35128 */
35129 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
35130 # define expensive_assert(X)  assert(X)
35131 #else
35132 # define expensive_assert(X)
35133 #endif
35134 
35135 /********************************** Linked List Management ********************/
35136 
35137 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
35138 /*
35139 ** Check that the pCache->pSynced variable is set correctly. If it
35140 ** is not, either fail an assert or return zero. Otherwise, return
35141 ** non-zero. This is only used in debugging builds, as follows:
35142 **
35143 **   expensive_assert( pcacheCheckSynced(pCache) );
35144 */
35145 static int pcacheCheckSynced(PCache *pCache){
35146   PgHdr *p;
35147   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
35148     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
35149   }
35150   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
35151 }
35152 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
35153 
35154 /*
35155 ** Remove page pPage from the list of dirty pages.
35156 */
35157 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
35158   PCache *p = pPage->pCache;
35159 
35160   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
35161   assert( pPage->pDirtyPrev || pPage==p->pDirty );
35162 
35163   /* Update the PCache1.pSynced variable if necessary. */
35164   if( p->pSynced==pPage ){
35165     PgHdr *pSynced = pPage->pDirtyPrev;
35166     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
35167       pSynced = pSynced->pDirtyPrev;
35168     }
35169     p->pSynced = pSynced;
35170   }
35171 
35172   if( pPage->pDirtyNext ){
35173     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
35174   }else{
35175     assert( pPage==p->pDirtyTail );
35176     p->pDirtyTail = pPage->pDirtyPrev;
35177   }
35178   if( pPage->pDirtyPrev ){
35179     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
35180   }else{
35181     assert( pPage==p->pDirty );
35182     p->pDirty = pPage->pDirtyNext;
35183   }
35184   pPage->pDirtyNext = 0;
35185   pPage->pDirtyPrev = 0;
35186 
35187   expensive_assert( pcacheCheckSynced(p) );
35188 }
35189 
35190 /*
35191 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
35192 ** pPage).
35193 */
35194 static void pcacheAddToDirtyList(PgHdr *pPage){
35195   PCache *p = pPage->pCache;
35196 
35197   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
35198 
35199   pPage->pDirtyNext = p->pDirty;
35200   if( pPage->pDirtyNext ){
35201     assert( pPage->pDirtyNext->pDirtyPrev==0 );
35202     pPage->pDirtyNext->pDirtyPrev = pPage;
35203   }
35204   p->pDirty = pPage;
35205   if( !p->pDirtyTail ){
35206     p->pDirtyTail = pPage;
35207   }
35208   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
35209     p->pSynced = pPage;
35210   }
35211   expensive_assert( pcacheCheckSynced(p) );
35212 }
35213 
35214 /*
35215 ** Wrapper around the pluggable caches xUnpin method. If the cache is
35216 ** being used for an in-memory database, this function is a no-op.
35217 */
35218 static void pcacheUnpin(PgHdr *p){
35219   PCache *pCache = p->pCache;
35220   if( pCache->bPurgeable ){
35221     if( p->pgno==1 ){
35222       pCache->pPage1 = 0;
35223     }
35224     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
35225   }
35226 }
35227 
35228 /*************************************************** General Interfaces ******
35229 **
35230 ** Initialize and shutdown the page cache subsystem. Neither of these
35231 ** functions are threadsafe.
35232 */
35233 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
35234   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
35235     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
35236     ** built-in default page cache is used instead of the application defined
35237     ** page cache. */
35238     sqlite3PCacheSetDefault();
35239   }
35240   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
35241 }
35242 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
35243   if( sqlite3GlobalConfig.pcache2.xShutdown ){
35244     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
35245     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
35246   }
35247 }
35248 
35249 /*
35250 ** Return the size in bytes of a PCache object.
35251 */
35252 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
35253 
35254 /*
35255 ** Create a new PCache object. Storage space to hold the object
35256 ** has already been allocated and is passed in as the p pointer.
35257 ** The caller discovers how much space needs to be allocated by
35258 ** calling sqlite3PcacheSize().
35259 */
35260 SQLITE_PRIVATE void sqlite3PcacheOpen(
35261   int szPage,                  /* Size of every page */
35262   int szExtra,                 /* Extra space associated with each page */
35263   int bPurgeable,              /* True if pages are on backing store */
35264   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
35265   void *pStress,               /* Argument to xStress */
35266   PCache *p                    /* Preallocated space for the PCache */
35267 ){
35268   memset(p, 0, sizeof(PCache));
35269   p->szPage = szPage;
35270   p->szExtra = szExtra;
35271   p->bPurgeable = bPurgeable;
35272   p->xStress = xStress;
35273   p->pStress = pStress;
35274   p->szCache = 100;
35275 }
35276 
35277 /*
35278 ** Change the page size for PCache object. The caller must ensure that there
35279 ** are no outstanding page references when this function is called.
35280 */
35281 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
35282   assert( pCache->nRef==0 && pCache->pDirty==0 );
35283   if( pCache->pCache ){
35284     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35285     pCache->pCache = 0;
35286     pCache->pPage1 = 0;
35287   }
35288   pCache->szPage = szPage;
35289 }
35290 
35291 /*
35292 ** Compute the number of pages of cache requested.
35293 */
35294 static int numberOfCachePages(PCache *p){
35295   if( p->szCache>=0 ){
35296     return p->szCache;
35297   }else{
35298     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
35299   }
35300 }
35301 
35302 /*
35303 ** Try to obtain a page from the cache.
35304 */
35305 SQLITE_PRIVATE int sqlite3PcacheFetch(
35306   PCache *pCache,       /* Obtain the page from this cache */
35307   Pgno pgno,            /* Page number to obtain */
35308   int createFlag,       /* If true, create page if it does not exist already */
35309   PgHdr **ppPage        /* Write the page here */
35310 ){
35311   sqlite3_pcache_page *pPage = 0;
35312   PgHdr *pPgHdr = 0;
35313   int eCreate;
35314 
35315   assert( pCache!=0 );
35316   assert( createFlag==1 || createFlag==0 );
35317   assert( pgno>0 );
35318 
35319   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
35320   ** allocate it now.
35321   */
35322   if( !pCache->pCache && createFlag ){
35323     sqlite3_pcache *p;
35324     p = sqlite3GlobalConfig.pcache2.xCreate(
35325         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
35326     );
35327     if( !p ){
35328       return SQLITE_NOMEM;
35329     }
35330     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
35331     pCache->pCache = p;
35332   }
35333 
35334   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
35335   if( pCache->pCache ){
35336     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
35337   }
35338 
35339   if( !pPage && eCreate==1 ){
35340     PgHdr *pPg;
35341 
35342     /* Find a dirty page to write-out and recycle. First try to find a
35343     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
35344     ** cleared), but if that is not possible settle for any other
35345     ** unreferenced dirty page.
35346     */
35347     expensive_assert( pcacheCheckSynced(pCache) );
35348     for(pPg=pCache->pSynced;
35349         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
35350         pPg=pPg->pDirtyPrev
35351     );
35352     pCache->pSynced = pPg;
35353     if( !pPg ){
35354       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
35355     }
35356     if( pPg ){
35357       int rc;
35358 #ifdef SQLITE_LOG_CACHE_SPILL
35359       sqlite3_log(SQLITE_FULL,
35360                   "spill page %d making room for %d - cache used: %d/%d",
35361                   pPg->pgno, pgno,
35362                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
35363                   numberOfCachePages(pCache));
35364 #endif
35365       rc = pCache->xStress(pCache->pStress, pPg);
35366       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
35367         return rc;
35368       }
35369     }
35370 
35371     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
35372   }
35373 
35374   if( pPage ){
35375     pPgHdr = (PgHdr *)pPage->pExtra;
35376 
35377     if( !pPgHdr->pPage ){
35378       memset(pPgHdr, 0, sizeof(PgHdr));
35379       pPgHdr->pPage = pPage;
35380       pPgHdr->pData = pPage->pBuf;
35381       pPgHdr->pExtra = (void *)&pPgHdr[1];
35382       memset(pPgHdr->pExtra, 0, pCache->szExtra);
35383       pPgHdr->pCache = pCache;
35384       pPgHdr->pgno = pgno;
35385     }
35386     assert( pPgHdr->pCache==pCache );
35387     assert( pPgHdr->pgno==pgno );
35388     assert( pPgHdr->pData==pPage->pBuf );
35389     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
35390 
35391     if( 0==pPgHdr->nRef ){
35392       pCache->nRef++;
35393     }
35394     pPgHdr->nRef++;
35395     if( pgno==1 ){
35396       pCache->pPage1 = pPgHdr;
35397     }
35398   }
35399   *ppPage = pPgHdr;
35400   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
35401 }
35402 
35403 /*
35404 ** Decrement the reference count on a page. If the page is clean and the
35405 ** reference count drops to 0, then it is made elible for recycling.
35406 */
35407 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
35408   assert( p->nRef>0 );
35409   p->nRef--;
35410   if( p->nRef==0 ){
35411     PCache *pCache = p->pCache;
35412     pCache->nRef--;
35413     if( (p->flags&PGHDR_DIRTY)==0 ){
35414       pcacheUnpin(p);
35415     }else{
35416       /* Move the page to the head of the dirty list. */
35417       pcacheRemoveFromDirtyList(p);
35418       pcacheAddToDirtyList(p);
35419     }
35420   }
35421 }
35422 
35423 /*
35424 ** Increase the reference count of a supplied page by 1.
35425 */
35426 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
35427   assert(p->nRef>0);
35428   p->nRef++;
35429 }
35430 
35431 /*
35432 ** Drop a page from the cache. There must be exactly one reference to the
35433 ** page. This function deletes that reference, so after it returns the
35434 ** page pointed to by p is invalid.
35435 */
35436 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35437   PCache *pCache;
35438   assert( p->nRef==1 );
35439   if( p->flags&PGHDR_DIRTY ){
35440     pcacheRemoveFromDirtyList(p);
35441   }
35442   pCache = p->pCache;
35443   pCache->nRef--;
35444   if( p->pgno==1 ){
35445     pCache->pPage1 = 0;
35446   }
35447   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
35448 }
35449 
35450 /*
35451 ** Make sure the page is marked as dirty. If it isn't dirty already,
35452 ** make it so.
35453 */
35454 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35455   p->flags &= ~PGHDR_DONT_WRITE;
35456   assert( p->nRef>0 );
35457   if( 0==(p->flags & PGHDR_DIRTY) ){
35458     p->flags |= PGHDR_DIRTY;
35459     pcacheAddToDirtyList( p);
35460   }
35461 }
35462 
35463 /*
35464 ** Make sure the page is marked as clean. If it isn't clean already,
35465 ** make it so.
35466 */
35467 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35468   if( (p->flags & PGHDR_DIRTY) ){
35469     pcacheRemoveFromDirtyList(p);
35470     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35471     if( p->nRef==0 ){
35472       pcacheUnpin(p);
35473     }
35474   }
35475 }
35476 
35477 /*
35478 ** Make every page in the cache clean.
35479 */
35480 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35481   PgHdr *p;
35482   while( (p = pCache->pDirty)!=0 ){
35483     sqlite3PcacheMakeClean(p);
35484   }
35485 }
35486 
35487 /*
35488 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35489 */
35490 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35491   PgHdr *p;
35492   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35493     p->flags &= ~PGHDR_NEED_SYNC;
35494   }
35495   pCache->pSynced = pCache->pDirtyTail;
35496 }
35497 
35498 /*
35499 ** Change the page number of page p to newPgno.
35500 */
35501 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35502   PCache *pCache = p->pCache;
35503   assert( p->nRef>0 );
35504   assert( newPgno>0 );
35505   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
35506   p->pgno = newPgno;
35507   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35508     pcacheRemoveFromDirtyList(p);
35509     pcacheAddToDirtyList(p);
35510   }
35511 }
35512 
35513 /*
35514 ** Drop every cache entry whose page number is greater than "pgno". The
35515 ** caller must ensure that there are no outstanding references to any pages
35516 ** other than page 1 with a page number greater than pgno.
35517 **
35518 ** If there is a reference to page 1 and the pgno parameter passed to this
35519 ** function is 0, then the data area associated with page 1 is zeroed, but
35520 ** the page object is not dropped.
35521 */
35522 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35523   if( pCache->pCache ){
35524     PgHdr *p;
35525     PgHdr *pNext;
35526     for(p=pCache->pDirty; p; p=pNext){
35527       pNext = p->pDirtyNext;
35528       /* This routine never gets call with a positive pgno except right
35529       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
35530       ** it must be that pgno==0.
35531       */
35532       assert( p->pgno>0 );
35533       if( ALWAYS(p->pgno>pgno) ){
35534         assert( p->flags&PGHDR_DIRTY );
35535         sqlite3PcacheMakeClean(p);
35536       }
35537     }
35538     if( pgno==0 && pCache->pPage1 ){
35539       memset(pCache->pPage1->pData, 0, pCache->szPage);
35540       pgno = 1;
35541     }
35542     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
35543   }
35544 }
35545 
35546 /*
35547 ** Close a cache.
35548 */
35549 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35550   if( pCache->pCache ){
35551     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
35552   }
35553 }
35554 
35555 /*
35556 ** Discard the contents of the cache.
35557 */
35558 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35559   sqlite3PcacheTruncate(pCache, 0);
35560 }
35561 
35562 /*
35563 ** Merge two lists of pages connected by pDirty and in pgno order.
35564 ** Do not both fixing the pDirtyPrev pointers.
35565 */
35566 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35567   PgHdr result, *pTail;
35568   pTail = &result;
35569   while( pA && pB ){
35570     if( pA->pgno<pB->pgno ){
35571       pTail->pDirty = pA;
35572       pTail = pA;
35573       pA = pA->pDirty;
35574     }else{
35575       pTail->pDirty = pB;
35576       pTail = pB;
35577       pB = pB->pDirty;
35578     }
35579   }
35580   if( pA ){
35581     pTail->pDirty = pA;
35582   }else if( pB ){
35583     pTail->pDirty = pB;
35584   }else{
35585     pTail->pDirty = 0;
35586   }
35587   return result.pDirty;
35588 }
35589 
35590 /*
35591 ** Sort the list of pages in accending order by pgno.  Pages are
35592 ** connected by pDirty pointers.  The pDirtyPrev pointers are
35593 ** corrupted by this sort.
35594 **
35595 ** Since there cannot be more than 2^31 distinct pages in a database,
35596 ** there cannot be more than 31 buckets required by the merge sorter.
35597 ** One extra bucket is added to catch overflow in case something
35598 ** ever changes to make the previous sentence incorrect.
35599 */
35600 #define N_SORT_BUCKET  32
35601 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35602   PgHdr *a[N_SORT_BUCKET], *p;
35603   int i;
35604   memset(a, 0, sizeof(a));
35605   while( pIn ){
35606     p = pIn;
35607     pIn = p->pDirty;
35608     p->pDirty = 0;
35609     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35610       if( a[i]==0 ){
35611         a[i] = p;
35612         break;
35613       }else{
35614         p = pcacheMergeDirtyList(a[i], p);
35615         a[i] = 0;
35616       }
35617     }
35618     if( NEVER(i==N_SORT_BUCKET-1) ){
35619       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35620       ** the input list.  But that is impossible.
35621       */
35622       a[i] = pcacheMergeDirtyList(a[i], p);
35623     }
35624   }
35625   p = a[0];
35626   for(i=1; i<N_SORT_BUCKET; i++){
35627     p = pcacheMergeDirtyList(p, a[i]);
35628   }
35629   return p;
35630 }
35631 
35632 /*
35633 ** Return a list of all dirty pages in the cache, sorted by page number.
35634 */
35635 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35636   PgHdr *p;
35637   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35638     p->pDirty = p->pDirtyNext;
35639   }
35640   return pcacheSortDirtyList(pCache->pDirty);
35641 }
35642 
35643 /*
35644 ** Return the total number of referenced pages held by the cache.
35645 */
35646 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35647   return pCache->nRef;
35648 }
35649 
35650 /*
35651 ** Return the number of references to the page supplied as an argument.
35652 */
35653 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35654   return p->nRef;
35655 }
35656 
35657 /*
35658 ** Return the total number of pages in the cache.
35659 */
35660 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35661   int nPage = 0;
35662   if( pCache->pCache ){
35663     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
35664   }
35665   return nPage;
35666 }
35667 
35668 #ifdef SQLITE_TEST
35669 /*
35670 ** Get the suggested cache-size value.
35671 */
35672 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35673   return numberOfCachePages(pCache);
35674 }
35675 #endif
35676 
35677 /*
35678 ** Set the suggested cache-size value.
35679 */
35680 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35681   pCache->szCache = mxPage;
35682   if( pCache->pCache ){
35683     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
35684                                            numberOfCachePages(pCache));
35685   }
35686 }
35687 
35688 /*
35689 ** Free up as much memory as possible from the page cache.
35690 */
35691 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
35692   if( pCache->pCache ){
35693     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
35694   }
35695 }
35696 
35697 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35698 /*
35699 ** For all dirty pages currently in the cache, invoke the specified
35700 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35701 ** defined.
35702 */
35703 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35704   PgHdr *pDirty;
35705   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35706     xIter(pDirty);
35707   }
35708 }
35709 #endif
35710 
35711 /************** End of pcache.c **********************************************/
35712 /************** Begin file pcache1.c *****************************************/
35713 /*
35714 ** 2008 November 05
35715 **
35716 ** The author disclaims copyright to this source code.  In place of
35717 ** a legal notice, here is a blessing:
35718 **
35719 **    May you do good and not evil.
35720 **    May you find forgiveness for yourself and forgive others.
35721 **    May you share freely, never taking more than you give.
35722 **
35723 *************************************************************************
35724 **
35725 ** This file implements the default page cache implementation (the
35726 ** sqlite3_pcache interface). It also contains part of the implementation
35727 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35728 ** If the default page cache implementation is overriden, then neither of
35729 ** these two features are available.
35730 */
35731 
35732 
35733 typedef struct PCache1 PCache1;
35734 typedef struct PgHdr1 PgHdr1;
35735 typedef struct PgFreeslot PgFreeslot;
35736 typedef struct PGroup PGroup;
35737 
35738 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
35739 ** of one or more PCaches that are able to recycle each others unpinned
35740 ** pages when they are under memory pressure.  A PGroup is an instance of
35741 ** the following object.
35742 **
35743 ** This page cache implementation works in one of two modes:
35744 **
35745 **   (1)  Every PCache is the sole member of its own PGroup.  There is
35746 **        one PGroup per PCache.
35747 **
35748 **   (2)  There is a single global PGroup that all PCaches are a member
35749 **        of.
35750 **
35751 ** Mode 1 uses more memory (since PCache instances are not able to rob
35752 ** unused pages from other PCaches) but it also operates without a mutex,
35753 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
35754 ** threadsafe, but recycles pages more efficiently.
35755 **
35756 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
35757 ** PGroup which is the pcache1.grp global variable and its mutex is
35758 ** SQLITE_MUTEX_STATIC_LRU.
35759 */
35760 struct PGroup {
35761   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
35762   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
35763   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
35764   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
35765   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
35766   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
35767 };
35768 
35769 /* Each page cache is an instance of the following object.  Every
35770 ** open database file (including each in-memory database and each
35771 ** temporary or transient database) has a single page cache which
35772 ** is an instance of this object.
35773 **
35774 ** Pointers to structures of this type are cast and returned as
35775 ** opaque sqlite3_pcache* handles.
35776 */
35777 struct PCache1 {
35778   /* Cache configuration parameters. Page size (szPage) and the purgeable
35779   ** flag (bPurgeable) are set when the cache is created. nMax may be
35780   ** modified at any time by a call to the pcache1Cachesize() method.
35781   ** The PGroup mutex must be held when accessing nMax.
35782   */
35783   PGroup *pGroup;                     /* PGroup this cache belongs to */
35784   int szPage;                         /* Size of allocated pages in bytes */
35785   int szExtra;                        /* Size of extra space in bytes */
35786   int bPurgeable;                     /* True if cache is purgeable */
35787   unsigned int nMin;                  /* Minimum number of pages reserved */
35788   unsigned int nMax;                  /* Configured "cache_size" value */
35789   unsigned int n90pct;                /* nMax*9/10 */
35790   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35791 
35792   /* Hash table of all pages. The following variables may only be accessed
35793   ** when the accessor is holding the PGroup mutex.
35794   */
35795   unsigned int nRecyclable;           /* Number of pages in the LRU list */
35796   unsigned int nPage;                 /* Total number of pages in apHash */
35797   unsigned int nHash;                 /* Number of slots in apHash[] */
35798   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35799 };
35800 
35801 /*
35802 ** Each cache entry is represented by an instance of the following
35803 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
35804 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
35805 ** in memory.
35806 */
35807 struct PgHdr1 {
35808   sqlite3_pcache_page page;
35809   unsigned int iKey;             /* Key value (page number) */
35810   PgHdr1 *pNext;                 /* Next in hash table chain */
35811   PCache1 *pCache;               /* Cache that currently owns this page */
35812   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35813   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35814 };
35815 
35816 /*
35817 ** Free slots in the allocator used to divide up the buffer provided using
35818 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35819 */
35820 struct PgFreeslot {
35821   PgFreeslot *pNext;  /* Next free slot */
35822 };
35823 
35824 /*
35825 ** Global data used by this cache.
35826 */
35827 static SQLITE_WSD struct PCacheGlobal {
35828   PGroup grp;                    /* The global PGroup for mode (2) */
35829 
35830   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35831   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35832   ** fixed at sqlite3_initialize() time and do not require mutex protection.
35833   ** The nFreeSlot and pFree values do require mutex protection.
35834   */
35835   int isInit;                    /* True if initialized */
35836   int szSlot;                    /* Size of each free slot */
35837   int nSlot;                     /* The number of pcache slots */
35838   int nReserve;                  /* Try to keep nFreeSlot above this */
35839   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35840   /* Above requires no mutex.  Use mutex below for variable that follow. */
35841   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35842   PgFreeslot *pFree;             /* Free page blocks */
35843   int nFreeSlot;                 /* Number of unused pcache slots */
35844   /* The following value requires a mutex to change.  We skip the mutex on
35845   ** reading because (1) most platforms read a 32-bit integer atomically and
35846   ** (2) even if an incorrect value is read, no great harm is done since this
35847   ** is really just an optimization. */
35848   int bUnderPressure;            /* True if low on PAGECACHE memory */
35849 } pcache1_g;
35850 
35851 /*
35852 ** All code in this file should access the global structure above via the
35853 ** alias "pcache1". This ensures that the WSD emulation is used when
35854 ** compiling for systems that do not support real WSD.
35855 */
35856 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35857 
35858 /*
35859 ** Macros to enter and leave the PCache LRU mutex.
35860 */
35861 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35862 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35863 
35864 /******************************************************************************/
35865 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35866 
35867 /*
35868 ** This function is called during initialization if a static buffer is
35869 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35870 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35871 ** enough to contain 'n' buffers of 'sz' bytes each.
35872 **
35873 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35874 ** to be serialized already.  There is no need for further mutexing.
35875 */
35876 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35877   if( pcache1.isInit ){
35878     PgFreeslot *p;
35879     sz = ROUNDDOWN8(sz);
35880     pcache1.szSlot = sz;
35881     pcache1.nSlot = pcache1.nFreeSlot = n;
35882     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35883     pcache1.pStart = pBuf;
35884     pcache1.pFree = 0;
35885     pcache1.bUnderPressure = 0;
35886     while( n-- ){
35887       p = (PgFreeslot*)pBuf;
35888       p->pNext = pcache1.pFree;
35889       pcache1.pFree = p;
35890       pBuf = (void*)&((char*)pBuf)[sz];
35891     }
35892     pcache1.pEnd = pBuf;
35893   }
35894 }
35895 
35896 /*
35897 ** Malloc function used within this file to allocate space from the buffer
35898 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
35899 ** such buffer exists or there is no space left in it, this function falls
35900 ** back to sqlite3Malloc().
35901 **
35902 ** Multiple threads can run this routine at the same time.  Global variables
35903 ** in pcache1 need to be protected via mutex.
35904 */
35905 static void *pcache1Alloc(int nByte){
35906   void *p = 0;
35907   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35908   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35909   if( nByte<=pcache1.szSlot ){
35910     sqlite3_mutex_enter(pcache1.mutex);
35911     p = (PgHdr1 *)pcache1.pFree;
35912     if( p ){
35913       pcache1.pFree = pcache1.pFree->pNext;
35914       pcache1.nFreeSlot--;
35915       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35916       assert( pcache1.nFreeSlot>=0 );
35917       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35918     }
35919     sqlite3_mutex_leave(pcache1.mutex);
35920   }
35921   if( p==0 ){
35922     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35923     ** it from sqlite3Malloc instead.
35924     */
35925     p = sqlite3Malloc(nByte);
35926 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35927     if( p ){
35928       int sz = sqlite3MallocSize(p);
35929       sqlite3_mutex_enter(pcache1.mutex);
35930       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35931       sqlite3_mutex_leave(pcache1.mutex);
35932     }
35933 #endif
35934     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35935   }
35936   return p;
35937 }
35938 
35939 /*
35940 ** Free an allocated buffer obtained from pcache1Alloc().
35941 */
35942 static int pcache1Free(void *p){
35943   int nFreed = 0;
35944   if( p==0 ) return 0;
35945   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35946     PgFreeslot *pSlot;
35947     sqlite3_mutex_enter(pcache1.mutex);
35948     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35949     pSlot = (PgFreeslot*)p;
35950     pSlot->pNext = pcache1.pFree;
35951     pcache1.pFree = pSlot;
35952     pcache1.nFreeSlot++;
35953     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35954     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35955     sqlite3_mutex_leave(pcache1.mutex);
35956   }else{
35957     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35958     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35959     nFreed = sqlite3MallocSize(p);
35960 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
35961     sqlite3_mutex_enter(pcache1.mutex);
35962     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
35963     sqlite3_mutex_leave(pcache1.mutex);
35964 #endif
35965     sqlite3_free(p);
35966   }
35967   return nFreed;
35968 }
35969 
35970 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35971 /*
35972 ** Return the size of a pcache allocation
35973 */
35974 static int pcache1MemSize(void *p){
35975   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35976     return pcache1.szSlot;
35977   }else{
35978     int iSize;
35979     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35980     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35981     iSize = sqlite3MallocSize(p);
35982     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35983     return iSize;
35984   }
35985 }
35986 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35987 
35988 /*
35989 ** Allocate a new page object initially associated with cache pCache.
35990 */
35991 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35992   PgHdr1 *p = 0;
35993   void *pPg;
35994 
35995   /* The group mutex must be released before pcache1Alloc() is called. This
35996   ** is because it may call sqlite3_release_memory(), which assumes that
35997   ** this mutex is not held. */
35998   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35999   pcache1LeaveMutex(pCache->pGroup);
36000 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36001   pPg = pcache1Alloc(pCache->szPage);
36002   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
36003   if( !pPg || !p ){
36004     pcache1Free(pPg);
36005     sqlite3_free(p);
36006     pPg = 0;
36007   }
36008 #else
36009   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
36010   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
36011 #endif
36012   pcache1EnterMutex(pCache->pGroup);
36013 
36014   if( pPg ){
36015     p->page.pBuf = pPg;
36016     p->page.pExtra = &p[1];
36017     if( pCache->bPurgeable ){
36018       pCache->pGroup->nCurrentPage++;
36019     }
36020     return p;
36021   }
36022   return 0;
36023 }
36024 
36025 /*
36026 ** Free a page object allocated by pcache1AllocPage().
36027 **
36028 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
36029 ** that the current implementation happens to never call this routine
36030 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
36031 */
36032 static void pcache1FreePage(PgHdr1 *p){
36033   if( ALWAYS(p) ){
36034     PCache1 *pCache = p->pCache;
36035     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36036     pcache1Free(p->page.pBuf);
36037 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36038     sqlite3_free(p);
36039 #endif
36040     if( pCache->bPurgeable ){
36041       pCache->pGroup->nCurrentPage--;
36042     }
36043   }
36044 }
36045 
36046 /*
36047 ** Malloc function used by SQLite to obtain space from the buffer configured
36048 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
36049 ** exists, this function falls back to sqlite3Malloc().
36050 */
36051 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
36052   return pcache1Alloc(sz);
36053 }
36054 
36055 /*
36056 ** Free an allocated buffer obtained from sqlite3PageMalloc().
36057 */
36058 SQLITE_PRIVATE void sqlite3PageFree(void *p){
36059   pcache1Free(p);
36060 }
36061 
36062 
36063 /*
36064 ** Return true if it desirable to avoid allocating a new page cache
36065 ** entry.
36066 **
36067 ** If memory was allocated specifically to the page cache using
36068 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
36069 ** it is desirable to avoid allocating a new page cache entry because
36070 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
36071 ** for all page cache needs and we should not need to spill the
36072 ** allocation onto the heap.
36073 **
36074 ** Or, the heap is used for all page cache memory but the heap is
36075 ** under memory pressure, then again it is desirable to avoid
36076 ** allocating a new page cache entry in order to avoid stressing
36077 ** the heap even further.
36078 */
36079 static int pcache1UnderMemoryPressure(PCache1 *pCache){
36080   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
36081     return pcache1.bUnderPressure;
36082   }else{
36083     return sqlite3HeapNearlyFull();
36084   }
36085 }
36086 
36087 /******************************************************************************/
36088 /******** General Implementation Functions ************************************/
36089 
36090 /*
36091 ** This function is used to resize the hash table used by the cache passed
36092 ** as the first argument.
36093 **
36094 ** The PCache mutex must be held when this function is called.
36095 */
36096 static int pcache1ResizeHash(PCache1 *p){
36097   PgHdr1 **apNew;
36098   unsigned int nNew;
36099   unsigned int i;
36100 
36101   assert( sqlite3_mutex_held(p->pGroup->mutex) );
36102 
36103   nNew = p->nHash*2;
36104   if( nNew<256 ){
36105     nNew = 256;
36106   }
36107 
36108   pcache1LeaveMutex(p->pGroup);
36109   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
36110   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
36111   if( p->nHash ){ sqlite3EndBenignMalloc(); }
36112   pcache1EnterMutex(p->pGroup);
36113   if( apNew ){
36114     for(i=0; i<p->nHash; i++){
36115       PgHdr1 *pPage;
36116       PgHdr1 *pNext = p->apHash[i];
36117       while( (pPage = pNext)!=0 ){
36118         unsigned int h = pPage->iKey % nNew;
36119         pNext = pPage->pNext;
36120         pPage->pNext = apNew[h];
36121         apNew[h] = pPage;
36122       }
36123     }
36124     sqlite3_free(p->apHash);
36125     p->apHash = apNew;
36126     p->nHash = nNew;
36127   }
36128 
36129   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
36130 }
36131 
36132 /*
36133 ** This function is used internally to remove the page pPage from the
36134 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
36135 ** LRU list, then this function is a no-op.
36136 **
36137 ** The PGroup mutex must be held when this function is called.
36138 **
36139 ** If pPage is NULL then this routine is a no-op.
36140 */
36141 static void pcache1PinPage(PgHdr1 *pPage){
36142   PCache1 *pCache;
36143   PGroup *pGroup;
36144 
36145   if( pPage==0 ) return;
36146   pCache = pPage->pCache;
36147   pGroup = pCache->pGroup;
36148   assert( sqlite3_mutex_held(pGroup->mutex) );
36149   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
36150     if( pPage->pLruPrev ){
36151       pPage->pLruPrev->pLruNext = pPage->pLruNext;
36152     }
36153     if( pPage->pLruNext ){
36154       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
36155     }
36156     if( pGroup->pLruHead==pPage ){
36157       pGroup->pLruHead = pPage->pLruNext;
36158     }
36159     if( pGroup->pLruTail==pPage ){
36160       pGroup->pLruTail = pPage->pLruPrev;
36161     }
36162     pPage->pLruNext = 0;
36163     pPage->pLruPrev = 0;
36164     pPage->pCache->nRecyclable--;
36165   }
36166 }
36167 
36168 
36169 /*
36170 ** Remove the page supplied as an argument from the hash table
36171 ** (PCache1.apHash structure) that it is currently stored in.
36172 **
36173 ** The PGroup mutex must be held when this function is called.
36174 */
36175 static void pcache1RemoveFromHash(PgHdr1 *pPage){
36176   unsigned int h;
36177   PCache1 *pCache = pPage->pCache;
36178   PgHdr1 **pp;
36179 
36180   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36181   h = pPage->iKey % pCache->nHash;
36182   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
36183   *pp = (*pp)->pNext;
36184 
36185   pCache->nPage--;
36186 }
36187 
36188 /*
36189 ** If there are currently more than nMaxPage pages allocated, try
36190 ** to recycle pages to reduce the number allocated to nMaxPage.
36191 */
36192 static void pcache1EnforceMaxPage(PGroup *pGroup){
36193   assert( sqlite3_mutex_held(pGroup->mutex) );
36194   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
36195     PgHdr1 *p = pGroup->pLruTail;
36196     assert( p->pCache->pGroup==pGroup );
36197     pcache1PinPage(p);
36198     pcache1RemoveFromHash(p);
36199     pcache1FreePage(p);
36200   }
36201 }
36202 
36203 /*
36204 ** Discard all pages from cache pCache with a page number (key value)
36205 ** greater than or equal to iLimit. Any pinned pages that meet this
36206 ** criteria are unpinned before they are discarded.
36207 **
36208 ** The PCache mutex must be held when this function is called.
36209 */
36210 static void pcache1TruncateUnsafe(
36211   PCache1 *pCache,             /* The cache to truncate */
36212   unsigned int iLimit          /* Drop pages with this pgno or larger */
36213 ){
36214   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
36215   unsigned int h;
36216   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36217   for(h=0; h<pCache->nHash; h++){
36218     PgHdr1 **pp = &pCache->apHash[h];
36219     PgHdr1 *pPage;
36220     while( (pPage = *pp)!=0 ){
36221       if( pPage->iKey>=iLimit ){
36222         pCache->nPage--;
36223         *pp = pPage->pNext;
36224         pcache1PinPage(pPage);
36225         pcache1FreePage(pPage);
36226       }else{
36227         pp = &pPage->pNext;
36228         TESTONLY( nPage++; )
36229       }
36230     }
36231   }
36232   assert( pCache->nPage==nPage );
36233 }
36234 
36235 /******************************************************************************/
36236 /******** sqlite3_pcache Methods **********************************************/
36237 
36238 /*
36239 ** Implementation of the sqlite3_pcache.xInit method.
36240 */
36241 static int pcache1Init(void *NotUsed){
36242   UNUSED_PARAMETER(NotUsed);
36243   assert( pcache1.isInit==0 );
36244   memset(&pcache1, 0, sizeof(pcache1));
36245   if( sqlite3GlobalConfig.bCoreMutex ){
36246     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
36247     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
36248   }
36249   pcache1.grp.mxPinned = 10;
36250   pcache1.isInit = 1;
36251   return SQLITE_OK;
36252 }
36253 
36254 /*
36255 ** Implementation of the sqlite3_pcache.xShutdown method.
36256 ** Note that the static mutex allocated in xInit does
36257 ** not need to be freed.
36258 */
36259 static void pcache1Shutdown(void *NotUsed){
36260   UNUSED_PARAMETER(NotUsed);
36261   assert( pcache1.isInit!=0 );
36262   memset(&pcache1, 0, sizeof(pcache1));
36263 }
36264 
36265 /*
36266 ** Implementation of the sqlite3_pcache.xCreate method.
36267 **
36268 ** Allocate a new cache.
36269 */
36270 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
36271   PCache1 *pCache;      /* The newly created page cache */
36272   PGroup *pGroup;       /* The group the new page cache will belong to */
36273   int sz;               /* Bytes of memory required to allocate the new cache */
36274 
36275   /*
36276   ** The seperateCache variable is true if each PCache has its own private
36277   ** PGroup.  In other words, separateCache is true for mode (1) where no
36278   ** mutexing is required.
36279   **
36280   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
36281   **
36282   **   *  Always use a unified cache in single-threaded applications
36283   **
36284   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
36285   **      use separate caches (mode-1)
36286   */
36287 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
36288   const int separateCache = 0;
36289 #else
36290   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
36291 #endif
36292 
36293   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
36294   assert( szExtra < 300 );
36295 
36296   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
36297   pCache = (PCache1 *)sqlite3MallocZero(sz);
36298   if( pCache ){
36299     if( separateCache ){
36300       pGroup = (PGroup*)&pCache[1];
36301       pGroup->mxPinned = 10;
36302     }else{
36303       pGroup = &pcache1.grp;
36304     }
36305     pCache->pGroup = pGroup;
36306     pCache->szPage = szPage;
36307     pCache->szExtra = szExtra;
36308     pCache->bPurgeable = (bPurgeable ? 1 : 0);
36309     if( bPurgeable ){
36310       pCache->nMin = 10;
36311       pcache1EnterMutex(pGroup);
36312       pGroup->nMinPage += pCache->nMin;
36313       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36314       pcache1LeaveMutex(pGroup);
36315     }
36316   }
36317   return (sqlite3_pcache *)pCache;
36318 }
36319 
36320 /*
36321 ** Implementation of the sqlite3_pcache.xCachesize method.
36322 **
36323 ** Configure the cache_size limit for a cache.
36324 */
36325 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
36326   PCache1 *pCache = (PCache1 *)p;
36327   if( pCache->bPurgeable ){
36328     PGroup *pGroup = pCache->pGroup;
36329     pcache1EnterMutex(pGroup);
36330     pGroup->nMaxPage += (nMax - pCache->nMax);
36331     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36332     pCache->nMax = nMax;
36333     pCache->n90pct = pCache->nMax*9/10;
36334     pcache1EnforceMaxPage(pGroup);
36335     pcache1LeaveMutex(pGroup);
36336   }
36337 }
36338 
36339 /*
36340 ** Implementation of the sqlite3_pcache.xShrink method.
36341 **
36342 ** Free up as much memory as possible.
36343 */
36344 static void pcache1Shrink(sqlite3_pcache *p){
36345   PCache1 *pCache = (PCache1*)p;
36346   if( pCache->bPurgeable ){
36347     PGroup *pGroup = pCache->pGroup;
36348     int savedMaxPage;
36349     pcache1EnterMutex(pGroup);
36350     savedMaxPage = pGroup->nMaxPage;
36351     pGroup->nMaxPage = 0;
36352     pcache1EnforceMaxPage(pGroup);
36353     pGroup->nMaxPage = savedMaxPage;
36354     pcache1LeaveMutex(pGroup);
36355   }
36356 }
36357 
36358 /*
36359 ** Implementation of the sqlite3_pcache.xPagecount method.
36360 */
36361 static int pcache1Pagecount(sqlite3_pcache *p){
36362   int n;
36363   PCache1 *pCache = (PCache1*)p;
36364   pcache1EnterMutex(pCache->pGroup);
36365   n = pCache->nPage;
36366   pcache1LeaveMutex(pCache->pGroup);
36367   return n;
36368 }
36369 
36370 /*
36371 ** Implementation of the sqlite3_pcache.xFetch method.
36372 **
36373 ** Fetch a page by key value.
36374 **
36375 ** Whether or not a new page may be allocated by this function depends on
36376 ** the value of the createFlag argument.  0 means do not allocate a new
36377 ** page.  1 means allocate a new page if space is easily available.  2
36378 ** means to try really hard to allocate a new page.
36379 **
36380 ** For a non-purgeable cache (a cache used as the storage for an in-memory
36381 ** database) there is really no difference between createFlag 1 and 2.  So
36382 ** the calling function (pcache.c) will never have a createFlag of 1 on
36383 ** a non-purgeable cache.
36384 **
36385 ** There are three different approaches to obtaining space for a page,
36386 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
36387 **
36388 **   1. Regardless of the value of createFlag, the cache is searched for a
36389 **      copy of the requested page. If one is found, it is returned.
36390 **
36391 **   2. If createFlag==0 and the page is not already in the cache, NULL is
36392 **      returned.
36393 **
36394 **   3. If createFlag is 1, and the page is not already in the cache, then
36395 **      return NULL (do not allocate a new page) if any of the following
36396 **      conditions are true:
36397 **
36398 **       (a) the number of pages pinned by the cache is greater than
36399 **           PCache1.nMax, or
36400 **
36401 **       (b) the number of pages pinned by the cache is greater than
36402 **           the sum of nMax for all purgeable caches, less the sum of
36403 **           nMin for all other purgeable caches, or
36404 **
36405 **   4. If none of the first three conditions apply and the cache is marked
36406 **      as purgeable, and if one of the following is true:
36407 **
36408 **       (a) The number of pages allocated for the cache is already
36409 **           PCache1.nMax, or
36410 **
36411 **       (b) The number of pages allocated for all purgeable caches is
36412 **           already equal to or greater than the sum of nMax for all
36413 **           purgeable caches,
36414 **
36415 **       (c) The system is under memory pressure and wants to avoid
36416 **           unnecessary pages cache entry allocations
36417 **
36418 **      then attempt to recycle a page from the LRU list. If it is the right
36419 **      size, return the recycled buffer. Otherwise, free the buffer and
36420 **      proceed to step 5.
36421 **
36422 **   5. Otherwise, allocate and return a new page buffer.
36423 */
36424 static sqlite3_pcache_page *pcache1Fetch(
36425   sqlite3_pcache *p,
36426   unsigned int iKey,
36427   int createFlag
36428 ){
36429   unsigned int nPinned;
36430   PCache1 *pCache = (PCache1 *)p;
36431   PGroup *pGroup;
36432   PgHdr1 *pPage = 0;
36433 
36434   assert( pCache->bPurgeable || createFlag!=1 );
36435   assert( pCache->bPurgeable || pCache->nMin==0 );
36436   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
36437   assert( pCache->nMin==0 || pCache->bPurgeable );
36438   pcache1EnterMutex(pGroup = pCache->pGroup);
36439 
36440   /* Step 1: Search the hash table for an existing entry. */
36441   if( pCache->nHash>0 ){
36442     unsigned int h = iKey % pCache->nHash;
36443     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
36444   }
36445 
36446   /* Step 2: Abort if no existing page is found and createFlag is 0 */
36447   if( pPage || createFlag==0 ){
36448     pcache1PinPage(pPage);
36449     goto fetch_out;
36450   }
36451 
36452   /* The pGroup local variable will normally be initialized by the
36453   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
36454   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
36455   ** local variable here.  Delaying the initialization of pGroup is an
36456   ** optimization:  The common case is to exit the module before reaching
36457   ** this point.
36458   */
36459 #ifdef SQLITE_MUTEX_OMIT
36460   pGroup = pCache->pGroup;
36461 #endif
36462 
36463   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
36464   assert( pCache->nPage >= pCache->nRecyclable );
36465   nPinned = pCache->nPage - pCache->nRecyclable;
36466   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
36467   assert( pCache->n90pct == pCache->nMax*9/10 );
36468   if( createFlag==1 && (
36469         nPinned>=pGroup->mxPinned
36470      || nPinned>=pCache->n90pct
36471      || pcache1UnderMemoryPressure(pCache)
36472   )){
36473     goto fetch_out;
36474   }
36475 
36476   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36477     goto fetch_out;
36478   }
36479 
36480   /* Step 4. Try to recycle a page. */
36481   if( pCache->bPurgeable && pGroup->pLruTail && (
36482          (pCache->nPage+1>=pCache->nMax)
36483       || pGroup->nCurrentPage>=pGroup->nMaxPage
36484       || pcache1UnderMemoryPressure(pCache)
36485   )){
36486     PCache1 *pOther;
36487     pPage = pGroup->pLruTail;
36488     pcache1RemoveFromHash(pPage);
36489     pcache1PinPage(pPage);
36490     pOther = pPage->pCache;
36491 
36492     /* We want to verify that szPage and szExtra are the same for pOther
36493     ** and pCache.  Assert that we can verify this by comparing sums. */
36494     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
36495     assert( pCache->szExtra<512 );
36496     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
36497     assert( pOther->szExtra<512 );
36498 
36499     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
36500       pcache1FreePage(pPage);
36501       pPage = 0;
36502     }else{
36503       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
36504     }
36505   }
36506 
36507   /* Step 5. If a usable page buffer has still not been found,
36508   ** attempt to allocate a new one.
36509   */
36510   if( !pPage ){
36511     if( createFlag==1 ) sqlite3BeginBenignMalloc();
36512     pPage = pcache1AllocPage(pCache);
36513     if( createFlag==1 ) sqlite3EndBenignMalloc();
36514   }
36515 
36516   if( pPage ){
36517     unsigned int h = iKey % pCache->nHash;
36518     pCache->nPage++;
36519     pPage->iKey = iKey;
36520     pPage->pNext = pCache->apHash[h];
36521     pPage->pCache = pCache;
36522     pPage->pLruPrev = 0;
36523     pPage->pLruNext = 0;
36524     *(void **)pPage->page.pExtra = 0;
36525     pCache->apHash[h] = pPage;
36526   }
36527 
36528 fetch_out:
36529   if( pPage && iKey>pCache->iMaxKey ){
36530     pCache->iMaxKey = iKey;
36531   }
36532   pcache1LeaveMutex(pGroup);
36533   return &pPage->page;
36534 }
36535 
36536 
36537 /*
36538 ** Implementation of the sqlite3_pcache.xUnpin method.
36539 **
36540 ** Mark a page as unpinned (eligible for asynchronous recycling).
36541 */
36542 static void pcache1Unpin(
36543   sqlite3_pcache *p,
36544   sqlite3_pcache_page *pPg,
36545   int reuseUnlikely
36546 ){
36547   PCache1 *pCache = (PCache1 *)p;
36548   PgHdr1 *pPage = (PgHdr1 *)pPg;
36549   PGroup *pGroup = pCache->pGroup;
36550 
36551   assert( pPage->pCache==pCache );
36552   pcache1EnterMutex(pGroup);
36553 
36554   /* It is an error to call this function if the page is already
36555   ** part of the PGroup LRU list.
36556   */
36557   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36558   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36559 
36560   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36561     pcache1RemoveFromHash(pPage);
36562     pcache1FreePage(pPage);
36563   }else{
36564     /* Add the page to the PGroup LRU list. */
36565     if( pGroup->pLruHead ){
36566       pGroup->pLruHead->pLruPrev = pPage;
36567       pPage->pLruNext = pGroup->pLruHead;
36568       pGroup->pLruHead = pPage;
36569     }else{
36570       pGroup->pLruTail = pPage;
36571       pGroup->pLruHead = pPage;
36572     }
36573     pCache->nRecyclable++;
36574   }
36575 
36576   pcache1LeaveMutex(pCache->pGroup);
36577 }
36578 
36579 /*
36580 ** Implementation of the sqlite3_pcache.xRekey method.
36581 */
36582 static void pcache1Rekey(
36583   sqlite3_pcache *p,
36584   sqlite3_pcache_page *pPg,
36585   unsigned int iOld,
36586   unsigned int iNew
36587 ){
36588   PCache1 *pCache = (PCache1 *)p;
36589   PgHdr1 *pPage = (PgHdr1 *)pPg;
36590   PgHdr1 **pp;
36591   unsigned int h;
36592   assert( pPage->iKey==iOld );
36593   assert( pPage->pCache==pCache );
36594 
36595   pcache1EnterMutex(pCache->pGroup);
36596 
36597   h = iOld%pCache->nHash;
36598   pp = &pCache->apHash[h];
36599   while( (*pp)!=pPage ){
36600     pp = &(*pp)->pNext;
36601   }
36602   *pp = pPage->pNext;
36603 
36604   h = iNew%pCache->nHash;
36605   pPage->iKey = iNew;
36606   pPage->pNext = pCache->apHash[h];
36607   pCache->apHash[h] = pPage;
36608   if( iNew>pCache->iMaxKey ){
36609     pCache->iMaxKey = iNew;
36610   }
36611 
36612   pcache1LeaveMutex(pCache->pGroup);
36613 }
36614 
36615 /*
36616 ** Implementation of the sqlite3_pcache.xTruncate method.
36617 **
36618 ** Discard all unpinned pages in the cache with a page number equal to
36619 ** or greater than parameter iLimit. Any pinned pages with a page number
36620 ** equal to or greater than iLimit are implicitly unpinned.
36621 */
36622 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36623   PCache1 *pCache = (PCache1 *)p;
36624   pcache1EnterMutex(pCache->pGroup);
36625   if( iLimit<=pCache->iMaxKey ){
36626     pcache1TruncateUnsafe(pCache, iLimit);
36627     pCache->iMaxKey = iLimit-1;
36628   }
36629   pcache1LeaveMutex(pCache->pGroup);
36630 }
36631 
36632 /*
36633 ** Implementation of the sqlite3_pcache.xDestroy method.
36634 **
36635 ** Destroy a cache allocated using pcache1Create().
36636 */
36637 static void pcache1Destroy(sqlite3_pcache *p){
36638   PCache1 *pCache = (PCache1 *)p;
36639   PGroup *pGroup = pCache->pGroup;
36640   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36641   pcache1EnterMutex(pGroup);
36642   pcache1TruncateUnsafe(pCache, 0);
36643   assert( pGroup->nMaxPage >= pCache->nMax );
36644   pGroup->nMaxPage -= pCache->nMax;
36645   assert( pGroup->nMinPage >= pCache->nMin );
36646   pGroup->nMinPage -= pCache->nMin;
36647   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36648   pcache1EnforceMaxPage(pGroup);
36649   pcache1LeaveMutex(pGroup);
36650   sqlite3_free(pCache->apHash);
36651   sqlite3_free(pCache);
36652 }
36653 
36654 /*
36655 ** This function is called during initialization (sqlite3_initialize()) to
36656 ** install the default pluggable cache module, assuming the user has not
36657 ** already provided an alternative.
36658 */
36659 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36660   static const sqlite3_pcache_methods2 defaultMethods = {
36661     1,                       /* iVersion */
36662     0,                       /* pArg */
36663     pcache1Init,             /* xInit */
36664     pcache1Shutdown,         /* xShutdown */
36665     pcache1Create,           /* xCreate */
36666     pcache1Cachesize,        /* xCachesize */
36667     pcache1Pagecount,        /* xPagecount */
36668     pcache1Fetch,            /* xFetch */
36669     pcache1Unpin,            /* xUnpin */
36670     pcache1Rekey,            /* xRekey */
36671     pcache1Truncate,         /* xTruncate */
36672     pcache1Destroy,          /* xDestroy */
36673     pcache1Shrink            /* xShrink */
36674   };
36675   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
36676 }
36677 
36678 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36679 /*
36680 ** This function is called to free superfluous dynamically allocated memory
36681 ** held by the pager system. Memory in use by any SQLite pager allocated
36682 ** by the current thread may be sqlite3_free()ed.
36683 **
36684 ** nReq is the number of bytes of memory required. Once this much has
36685 ** been released, the function returns. The return value is the total number
36686 ** of bytes of memory released.
36687 */
36688 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36689   int nFree = 0;
36690   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36691   assert( sqlite3_mutex_notheld(pcache1.mutex) );
36692   if( pcache1.pStart==0 ){
36693     PgHdr1 *p;
36694     pcache1EnterMutex(&pcache1.grp);
36695     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36696       nFree += pcache1MemSize(p->page.pBuf);
36697 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36698       nFree += sqlite3MemSize(p);
36699 #endif
36700       pcache1PinPage(p);
36701       pcache1RemoveFromHash(p);
36702       pcache1FreePage(p);
36703     }
36704     pcache1LeaveMutex(&pcache1.grp);
36705   }
36706   return nFree;
36707 }
36708 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36709 
36710 #ifdef SQLITE_TEST
36711 /*
36712 ** This function is used by test procedures to inspect the internal state
36713 ** of the global cache.
36714 */
36715 SQLITE_PRIVATE void sqlite3PcacheStats(
36716   int *pnCurrent,      /* OUT: Total number of pages cached */
36717   int *pnMax,          /* OUT: Global maximum cache size */
36718   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
36719   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
36720 ){
36721   PgHdr1 *p;
36722   int nRecyclable = 0;
36723   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36724     nRecyclable++;
36725   }
36726   *pnCurrent = pcache1.grp.nCurrentPage;
36727   *pnMax = (int)pcache1.grp.nMaxPage;
36728   *pnMin = (int)pcache1.grp.nMinPage;
36729   *pnRecyclable = nRecyclable;
36730 }
36731 #endif
36732 
36733 /************** End of pcache1.c *********************************************/
36734 /************** Begin file rowset.c ******************************************/
36735 /*
36736 ** 2008 December 3
36737 **
36738 ** The author disclaims copyright to this source code.  In place of
36739 ** a legal notice, here is a blessing:
36740 **
36741 **    May you do good and not evil.
36742 **    May you find forgiveness for yourself and forgive others.
36743 **    May you share freely, never taking more than you give.
36744 **
36745 *************************************************************************
36746 **
36747 ** This module implements an object we call a "RowSet".
36748 **
36749 ** The RowSet object is a collection of rowids.  Rowids
36750 ** are inserted into the RowSet in an arbitrary order.  Inserts
36751 ** can be intermixed with tests to see if a given rowid has been
36752 ** previously inserted into the RowSet.
36753 **
36754 ** After all inserts are finished, it is possible to extract the
36755 ** elements of the RowSet in sorted order.  Once this extraction
36756 ** process has started, no new elements may be inserted.
36757 **
36758 ** Hence, the primitive operations for a RowSet are:
36759 **
36760 **    CREATE
36761 **    INSERT
36762 **    TEST
36763 **    SMALLEST
36764 **    DESTROY
36765 **
36766 ** The CREATE and DESTROY primitives are the constructor and destructor,
36767 ** obviously.  The INSERT primitive adds a new element to the RowSet.
36768 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
36769 ** extracts the least value from the RowSet.
36770 **
36771 ** The INSERT primitive might allocate additional memory.  Memory is
36772 ** allocated in chunks so most INSERTs do no allocation.  There is an
36773 ** upper bound on the size of allocated memory.  No memory is freed
36774 ** until DESTROY.
36775 **
36776 ** The TEST primitive includes a "batch" number.  The TEST primitive
36777 ** will only see elements that were inserted before the last change
36778 ** in the batch number.  In other words, if an INSERT occurs between
36779 ** two TESTs where the TESTs have the same batch nubmer, then the
36780 ** value added by the INSERT will not be visible to the second TEST.
36781 ** The initial batch number is zero, so if the very first TEST contains
36782 ** a non-zero batch number, it will see all prior INSERTs.
36783 **
36784 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
36785 ** that is attempted.
36786 **
36787 ** The cost of an INSERT is roughly constant.  (Sometime new memory
36788 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
36789 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
36790 ** The cost of a TEST using the same batch number is O(logN).  The cost
36791 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
36792 ** primitives are constant time.  The cost of DESTROY is O(N).
36793 **
36794 ** There is an added cost of O(N) when switching between TEST and
36795 ** SMALLEST primitives.
36796 */
36797 
36798 
36799 /*
36800 ** Target size for allocation chunks.
36801 */
36802 #define ROWSET_ALLOCATION_SIZE 1024
36803 
36804 /*
36805 ** The number of rowset entries per allocation chunk.
36806 */
36807 #define ROWSET_ENTRY_PER_CHUNK  \
36808                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
36809 
36810 /*
36811 ** Each entry in a RowSet is an instance of the following object.
36812 **
36813 ** This same object is reused to store a linked list of trees of RowSetEntry
36814 ** objects.  In that alternative use, pRight points to the next entry
36815 ** in the list, pLeft points to the tree, and v is unused.  The
36816 ** RowSet.pForest value points to the head of this forest list.
36817 */
36818 struct RowSetEntry {
36819   i64 v;                        /* ROWID value for this entry */
36820   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
36821   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
36822 };
36823 
36824 /*
36825 ** RowSetEntry objects are allocated in large chunks (instances of the
36826 ** following structure) to reduce memory allocation overhead.  The
36827 ** chunks are kept on a linked list so that they can be deallocated
36828 ** when the RowSet is destroyed.
36829 */
36830 struct RowSetChunk {
36831   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
36832   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
36833 };
36834 
36835 /*
36836 ** A RowSet in an instance of the following structure.
36837 **
36838 ** A typedef of this structure if found in sqliteInt.h.
36839 */
36840 struct RowSet {
36841   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
36842   sqlite3 *db;                   /* The database connection */
36843   struct RowSetEntry *pEntry;    /* List of entries using pRight */
36844   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
36845   struct RowSetEntry *pFresh;    /* Source of new entry objects */
36846   struct RowSetEntry *pForest;   /* List of binary trees of entries */
36847   u16 nFresh;                    /* Number of objects on pFresh */
36848   u8 rsFlags;                    /* Various flags */
36849   u8 iBatch;                     /* Current insert batch */
36850 };
36851 
36852 /*
36853 ** Allowed values for RowSet.rsFlags
36854 */
36855 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
36856 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
36857 
36858 /*
36859 ** Turn bulk memory into a RowSet object.  N bytes of memory
36860 ** are available at pSpace.  The db pointer is used as a memory context
36861 ** for any subsequent allocations that need to occur.
36862 ** Return a pointer to the new RowSet object.
36863 **
36864 ** It must be the case that N is sufficient to make a Rowset.  If not
36865 ** an assertion fault occurs.
36866 **
36867 ** If N is larger than the minimum, use the surplus as an initial
36868 ** allocation of entries available to be filled.
36869 */
36870 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36871   RowSet *p;
36872   assert( N >= ROUND8(sizeof(*p)) );
36873   p = pSpace;
36874   p->pChunk = 0;
36875   p->db = db;
36876   p->pEntry = 0;
36877   p->pLast = 0;
36878   p->pForest = 0;
36879   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36880   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36881   p->rsFlags = ROWSET_SORTED;
36882   p->iBatch = 0;
36883   return p;
36884 }
36885 
36886 /*
36887 ** Deallocate all chunks from a RowSet.  This frees all memory that
36888 ** the RowSet has allocated over its lifetime.  This routine is
36889 ** the destructor for the RowSet.
36890 */
36891 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36892   struct RowSetChunk *pChunk, *pNextChunk;
36893   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36894     pNextChunk = pChunk->pNextChunk;
36895     sqlite3DbFree(p->db, pChunk);
36896   }
36897   p->pChunk = 0;
36898   p->nFresh = 0;
36899   p->pEntry = 0;
36900   p->pLast = 0;
36901   p->pForest = 0;
36902   p->rsFlags = ROWSET_SORTED;
36903 }
36904 
36905 /*
36906 ** Allocate a new RowSetEntry object that is associated with the
36907 ** given RowSet.  Return a pointer to the new and completely uninitialized
36908 ** objected.
36909 **
36910 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
36911 ** routine returns NULL.
36912 */
36913 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
36914   assert( p!=0 );
36915   if( p->nFresh==0 ){
36916     struct RowSetChunk *pNew;
36917     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36918     if( pNew==0 ){
36919       return 0;
36920     }
36921     pNew->pNextChunk = p->pChunk;
36922     p->pChunk = pNew;
36923     p->pFresh = pNew->aEntry;
36924     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36925   }
36926   p->nFresh--;
36927   return p->pFresh++;
36928 }
36929 
36930 /*
36931 ** Insert a new value into a RowSet.
36932 **
36933 ** The mallocFailed flag of the database connection is set if a
36934 ** memory allocation fails.
36935 */
36936 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36937   struct RowSetEntry *pEntry;  /* The new entry */
36938   struct RowSetEntry *pLast;   /* The last prior entry */
36939 
36940   /* This routine is never called after sqlite3RowSetNext() */
36941   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
36942 
36943   pEntry = rowSetEntryAlloc(p);
36944   if( pEntry==0 ) return;
36945   pEntry->v = rowid;
36946   pEntry->pRight = 0;
36947   pLast = p->pLast;
36948   if( pLast ){
36949     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
36950       p->rsFlags &= ~ROWSET_SORTED;
36951     }
36952     pLast->pRight = pEntry;
36953   }else{
36954     p->pEntry = pEntry;
36955   }
36956   p->pLast = pEntry;
36957 }
36958 
36959 /*
36960 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
36961 **
36962 ** The input lists are connected via pRight pointers and are
36963 ** assumed to each already be in sorted order.
36964 */
36965 static struct RowSetEntry *rowSetEntryMerge(
36966   struct RowSetEntry *pA,    /* First sorted list to be merged */
36967   struct RowSetEntry *pB     /* Second sorted list to be merged */
36968 ){
36969   struct RowSetEntry head;
36970   struct RowSetEntry *pTail;
36971 
36972   pTail = &head;
36973   while( pA && pB ){
36974     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36975     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36976     if( pA->v<pB->v ){
36977       pTail->pRight = pA;
36978       pA = pA->pRight;
36979       pTail = pTail->pRight;
36980     }else if( pB->v<pA->v ){
36981       pTail->pRight = pB;
36982       pB = pB->pRight;
36983       pTail = pTail->pRight;
36984     }else{
36985       pA = pA->pRight;
36986     }
36987   }
36988   if( pA ){
36989     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36990     pTail->pRight = pA;
36991   }else{
36992     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36993     pTail->pRight = pB;
36994   }
36995   return head.pRight;
36996 }
36997 
36998 /*
36999 ** Sort all elements on the list of RowSetEntry objects into order of
37000 ** increasing v.
37001 */
37002 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
37003   unsigned int i;
37004   struct RowSetEntry *pNext, *aBucket[40];
37005 
37006   memset(aBucket, 0, sizeof(aBucket));
37007   while( pIn ){
37008     pNext = pIn->pRight;
37009     pIn->pRight = 0;
37010     for(i=0; aBucket[i]; i++){
37011       pIn = rowSetEntryMerge(aBucket[i], pIn);
37012       aBucket[i] = 0;
37013     }
37014     aBucket[i] = pIn;
37015     pIn = pNext;
37016   }
37017   pIn = 0;
37018   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37019     pIn = rowSetEntryMerge(pIn, aBucket[i]);
37020   }
37021   return pIn;
37022 }
37023 
37024 
37025 /*
37026 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37027 ** Convert this tree into a linked list connected by the pRight pointers
37028 ** and return pointers to the first and last elements of the new list.
37029 */
37030 static void rowSetTreeToList(
37031   struct RowSetEntry *pIn,         /* Root of the input tree */
37032   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
37033   struct RowSetEntry **ppLast      /* Write tail of the output list here */
37034 ){
37035   assert( pIn!=0 );
37036   if( pIn->pLeft ){
37037     struct RowSetEntry *p;
37038     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37039     p->pRight = pIn;
37040   }else{
37041     *ppFirst = pIn;
37042   }
37043   if( pIn->pRight ){
37044     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37045   }else{
37046     *ppLast = pIn;
37047   }
37048   assert( (*ppLast)->pRight==0 );
37049 }
37050 
37051 
37052 /*
37053 ** Convert a sorted list of elements (connected by pRight) into a binary
37054 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
37055 ** node taken from the head of *ppList.  A depth of 2 means a tree with
37056 ** three nodes.  And so forth.
37057 **
37058 ** Use as many entries from the input list as required and update the
37059 ** *ppList to point to the unused elements of the list.  If the input
37060 ** list contains too few elements, then construct an incomplete tree
37061 ** and leave *ppList set to NULL.
37062 **
37063 ** Return a pointer to the root of the constructed binary tree.
37064 */
37065 static struct RowSetEntry *rowSetNDeepTree(
37066   struct RowSetEntry **ppList,
37067   int iDepth
37068 ){
37069   struct RowSetEntry *p;         /* Root of the new tree */
37070   struct RowSetEntry *pLeft;     /* Left subtree */
37071   if( *ppList==0 ){
37072     return 0;
37073   }
37074   if( iDepth==1 ){
37075     p = *ppList;
37076     *ppList = p->pRight;
37077     p->pLeft = p->pRight = 0;
37078     return p;
37079   }
37080   pLeft = rowSetNDeepTree(ppList, iDepth-1);
37081   p = *ppList;
37082   if( p==0 ){
37083     return pLeft;
37084   }
37085   p->pLeft = pLeft;
37086   *ppList = p->pRight;
37087   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
37088   return p;
37089 }
37090 
37091 /*
37092 ** Convert a sorted list of elements into a binary tree. Make the tree
37093 ** as deep as it needs to be in order to contain the entire list.
37094 */
37095 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
37096   int iDepth;           /* Depth of the tree so far */
37097   struct RowSetEntry *p;       /* Current tree root */
37098   struct RowSetEntry *pLeft;   /* Left subtree */
37099 
37100   assert( pList!=0 );
37101   p = pList;
37102   pList = p->pRight;
37103   p->pLeft = p->pRight = 0;
37104   for(iDepth=1; pList; iDepth++){
37105     pLeft = p;
37106     p = pList;
37107     pList = p->pRight;
37108     p->pLeft = pLeft;
37109     p->pRight = rowSetNDeepTree(&pList, iDepth);
37110   }
37111   return p;
37112 }
37113 
37114 /*
37115 ** Take all the entries on p->pEntry and on the trees in p->pForest and
37116 ** sort them all together into one big ordered list on p->pEntry.
37117 **
37118 ** This routine should only be called once in the life of a RowSet.
37119 */
37120 static void rowSetToList(RowSet *p){
37121 
37122   /* This routine is called only once */
37123   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
37124 
37125   if( (p->rsFlags & ROWSET_SORTED)==0 ){
37126     p->pEntry = rowSetEntrySort(p->pEntry);
37127   }
37128 
37129   /* While this module could theoretically support it, sqlite3RowSetNext()
37130   ** is never called after sqlite3RowSetText() for the same RowSet.  So
37131   ** there is never a forest to deal with.  Should this change, simply
37132   ** remove the assert() and the #if 0. */
37133   assert( p->pForest==0 );
37134 #if 0
37135   while( p->pForest ){
37136     struct RowSetEntry *pTree = p->pForest->pLeft;
37137     if( pTree ){
37138       struct RowSetEntry *pHead, *pTail;
37139       rowSetTreeToList(pTree, &pHead, &pTail);
37140       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
37141     }
37142     p->pForest = p->pForest->pRight;
37143   }
37144 #endif
37145   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
37146 }
37147 
37148 /*
37149 ** Extract the smallest element from the RowSet.
37150 ** Write the element into *pRowid.  Return 1 on success.  Return
37151 ** 0 if the RowSet is already empty.
37152 **
37153 ** After this routine has been called, the sqlite3RowSetInsert()
37154 ** routine may not be called again.
37155 */
37156 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
37157   assert( p!=0 );
37158 
37159   /* Merge the forest into a single sorted list on first call */
37160   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
37161 
37162   /* Return the next entry on the list */
37163   if( p->pEntry ){
37164     *pRowid = p->pEntry->v;
37165     p->pEntry = p->pEntry->pRight;
37166     if( p->pEntry==0 ){
37167       sqlite3RowSetClear(p);
37168     }
37169     return 1;
37170   }else{
37171     return 0;
37172   }
37173 }
37174 
37175 /*
37176 ** Check to see if element iRowid was inserted into the rowset as
37177 ** part of any insert batch prior to iBatch.  Return 1 or 0.
37178 **
37179 ** If this is the first test of a new batch and if there exist entires
37180 ** on pRowSet->pEntry, then sort those entires into the forest at
37181 ** pRowSet->pForest so that they can be tested.
37182 */
37183 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
37184   struct RowSetEntry *p, *pTree;
37185 
37186   /* This routine is never called after sqlite3RowSetNext() */
37187   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
37188 
37189   /* Sort entries into the forest on the first test of a new batch
37190   */
37191   if( iBatch!=pRowSet->iBatch ){
37192     p = pRowSet->pEntry;
37193     if( p ){
37194       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
37195       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
37196         p = rowSetEntrySort(p);
37197       }
37198       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
37199         ppPrevTree = &pTree->pRight;
37200         if( pTree->pLeft==0 ){
37201           pTree->pLeft = rowSetListToTree(p);
37202           break;
37203         }else{
37204           struct RowSetEntry *pAux, *pTail;
37205           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
37206           pTree->pLeft = 0;
37207           p = rowSetEntryMerge(pAux, p);
37208         }
37209       }
37210       if( pTree==0 ){
37211         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
37212         if( pTree ){
37213           pTree->v = 0;
37214           pTree->pRight = 0;
37215           pTree->pLeft = rowSetListToTree(p);
37216         }
37217       }
37218       pRowSet->pEntry = 0;
37219       pRowSet->pLast = 0;
37220       pRowSet->rsFlags |= ROWSET_SORTED;
37221     }
37222     pRowSet->iBatch = iBatch;
37223   }
37224 
37225   /* Test to see if the iRowid value appears anywhere in the forest.
37226   ** Return 1 if it does and 0 if not.
37227   */
37228   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
37229     p = pTree->pLeft;
37230     while( p ){
37231       if( p->v<iRowid ){
37232         p = p->pRight;
37233       }else if( p->v>iRowid ){
37234         p = p->pLeft;
37235       }else{
37236         return 1;
37237       }
37238     }
37239   }
37240   return 0;
37241 }
37242 
37243 /************** End of rowset.c **********************************************/
37244 /************** Begin file pager.c *******************************************/
37245 /*
37246 ** 2001 September 15
37247 **
37248 ** The author disclaims copyright to this source code.  In place of
37249 ** a legal notice, here is a blessing:
37250 **
37251 **    May you do good and not evil.
37252 **    May you find forgiveness for yourself and forgive others.
37253 **    May you share freely, never taking more than you give.
37254 **
37255 *************************************************************************
37256 ** This is the implementation of the page cache subsystem or "pager".
37257 **
37258 ** The pager is used to access a database disk file.  It implements
37259 ** atomic commit and rollback through the use of a journal file that
37260 ** is separate from the database file.  The pager also implements file
37261 ** locking to prevent two processes from writing the same database
37262 ** file simultaneously, or one process from reading the database while
37263 ** another is writing.
37264 */
37265 #ifndef SQLITE_OMIT_DISKIO
37266 /************** Include wal.h in the middle of pager.c ***********************/
37267 /************** Begin file wal.h *********************************************/
37268 /*
37269 ** 2010 February 1
37270 **
37271 ** The author disclaims copyright to this source code.  In place of
37272 ** a legal notice, here is a blessing:
37273 **
37274 **    May you do good and not evil.
37275 **    May you find forgiveness for yourself and forgive others.
37276 **    May you share freely, never taking more than you give.
37277 **
37278 *************************************************************************
37279 ** This header file defines the interface to the write-ahead logging
37280 ** system. Refer to the comments below and the header comment attached to
37281 ** the implementation of each function in log.c for further details.
37282 */
37283 
37284 #ifndef _WAL_H_
37285 #define _WAL_H_
37286 
37287 
37288 /* Additional values that can be added to the sync_flags argument of
37289 ** sqlite3WalFrames():
37290 */
37291 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
37292 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
37293 
37294 #ifdef SQLITE_OMIT_WAL
37295 # define sqlite3WalOpen(x,y,z)                   0
37296 # define sqlite3WalLimit(x,y)
37297 # define sqlite3WalClose(w,x,y,z)                0
37298 # define sqlite3WalBeginReadTransaction(y,z)     0
37299 # define sqlite3WalEndReadTransaction(z)
37300 # define sqlite3WalRead(v,w,x,y,z)               0
37301 # define sqlite3WalDbsize(y)                     0
37302 # define sqlite3WalBeginWriteTransaction(y)      0
37303 # define sqlite3WalEndWriteTransaction(x)        0
37304 # define sqlite3WalUndo(x,y,z)                   0
37305 # define sqlite3WalSavepoint(y,z)
37306 # define sqlite3WalSavepointUndo(y,z)            0
37307 # define sqlite3WalFrames(u,v,w,x,y,z)           0
37308 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
37309 # define sqlite3WalCallback(z)                   0
37310 # define sqlite3WalExclusiveMode(y,z)            0
37311 # define sqlite3WalHeapMemory(z)                 0
37312 # define sqlite3WalFramesize(z)                  0
37313 #else
37314 
37315 #define WAL_SAVEPOINT_NDATA 4
37316 
37317 /* Connection to a write-ahead log (WAL) file.
37318 ** There is one object of this type for each pager.
37319 */
37320 typedef struct Wal Wal;
37321 
37322 /* Open and close a connection to a write-ahead log. */
37323 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
37324 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
37325 
37326 /* Set the limiting size of a WAL file. */
37327 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
37328 
37329 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
37330 ** snapshot is like a read-transaction.  It is the state of the database
37331 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
37332 ** preserves the current state even if the other threads or processes
37333 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
37334 ** transaction and releases the lock.
37335 */
37336 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
37337 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
37338 
37339 /* Read a page from the write-ahead log, if it is present. */
37340 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
37341 
37342 /* If the WAL is not empty, return the size of the database. */
37343 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
37344 
37345 /* Obtain or release the WRITER lock. */
37346 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
37347 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
37348 
37349 /* Undo any frames written (but not committed) to the log */
37350 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
37351 
37352 /* Return an integer that records the current (uncommitted) write
37353 ** position in the WAL */
37354 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
37355 
37356 /* Move the write position of the WAL back to iFrame.  Called in
37357 ** response to a ROLLBACK TO command. */
37358 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
37359 
37360 /* Write a frame or frames to the log. */
37361 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
37362 
37363 /* Copy pages from the log to the database file */
37364 SQLITE_PRIVATE int sqlite3WalCheckpoint(
37365   Wal *pWal,                      /* Write-ahead log connection */
37366   int eMode,                      /* One of PASSIVE, FULL and RESTART */
37367   int (*xBusy)(void*),            /* Function to call when busy */
37368   void *pBusyArg,                 /* Context argument for xBusyHandler */
37369   int sync_flags,                 /* Flags to sync db file with (or 0) */
37370   int nBuf,                       /* Size of buffer nBuf */
37371   u8 *zBuf,                       /* Temporary buffer to use */
37372   int *pnLog,                     /* OUT: Number of frames in WAL */
37373   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
37374 );
37375 
37376 /* Return the value to pass to a sqlite3_wal_hook callback, the
37377 ** number of frames in the WAL at the point of the last commit since
37378 ** sqlite3WalCallback() was called.  If no commits have occurred since
37379 ** the last call, then return 0.
37380 */
37381 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
37382 
37383 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
37384 ** by the pager layer on the database file.
37385 */
37386 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
37387 
37388 /* Return true if the argument is non-NULL and the WAL module is using
37389 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
37390 ** WAL module is using shared-memory, return false.
37391 */
37392 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
37393 
37394 #ifdef SQLITE_ENABLE_ZIPVFS
37395 /* If the WAL file is not empty, return the number of bytes of content
37396 ** stored in each frame (i.e. the db page-size when the WAL was created).
37397 */
37398 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
37399 #endif
37400 
37401 #endif /* ifndef SQLITE_OMIT_WAL */
37402 #endif /* _WAL_H_ */
37403 
37404 /************** End of wal.h *************************************************/
37405 /************** Continuing where we left off in pager.c **********************/
37406 
37407 
37408 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
37409 **
37410 ** This comment block describes invariants that hold when using a rollback
37411 ** journal.  These invariants do not apply for journal_mode=WAL,
37412 ** journal_mode=MEMORY, or journal_mode=OFF.
37413 **
37414 ** Within this comment block, a page is deemed to have been synced
37415 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
37416 ** Otherwise, the page is not synced until the xSync method of the VFS
37417 ** is called successfully on the file containing the page.
37418 **
37419 ** Definition:  A page of the database file is said to be "overwriteable" if
37420 ** one or more of the following are true about the page:
37421 **
37422 **     (a)  The original content of the page as it was at the beginning of
37423 **          the transaction has been written into the rollback journal and
37424 **          synced.
37425 **
37426 **     (b)  The page was a freelist leaf page at the start of the transaction.
37427 **
37428 **     (c)  The page number is greater than the largest page that existed in
37429 **          the database file at the start of the transaction.
37430 **
37431 ** (1) A page of the database file is never overwritten unless one of the
37432 **     following are true:
37433 **
37434 **     (a) The page and all other pages on the same sector are overwriteable.
37435 **
37436 **     (b) The atomic page write optimization is enabled, and the entire
37437 **         transaction other than the update of the transaction sequence
37438 **         number consists of a single page change.
37439 **
37440 ** (2) The content of a page written into the rollback journal exactly matches
37441 **     both the content in the database when the rollback journal was written
37442 **     and the content in the database at the beginning of the current
37443 **     transaction.
37444 **
37445 ** (3) Writes to the database file are an integer multiple of the page size
37446 **     in length and are aligned on a page boundary.
37447 **
37448 ** (4) Reads from the database file are either aligned on a page boundary and
37449 **     an integer multiple of the page size in length or are taken from the
37450 **     first 100 bytes of the database file.
37451 **
37452 ** (5) All writes to the database file are synced prior to the rollback journal
37453 **     being deleted, truncated, or zeroed.
37454 **
37455 ** (6) If a master journal file is used, then all writes to the database file
37456 **     are synced prior to the master journal being deleted.
37457 **
37458 ** Definition: Two databases (or the same database at two points it time)
37459 ** are said to be "logically equivalent" if they give the same answer to
37460 ** all queries.  Note in particular the content of freelist leaf
37461 ** pages can be changed arbitarily without effecting the logical equivalence
37462 ** of the database.
37463 **
37464 ** (7) At any time, if any subset, including the empty set and the total set,
37465 **     of the unsynced changes to a rollback journal are removed and the
37466 **     journal is rolled back, the resulting database file will be logical
37467 **     equivalent to the database file at the beginning of the transaction.
37468 **
37469 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
37470 **     is called to restore the database file to the same size it was at
37471 **     the beginning of the transaction.  (In some VFSes, the xTruncate
37472 **     method is a no-op, but that does not change the fact the SQLite will
37473 **     invoke it.)
37474 **
37475 ** (9) Whenever the database file is modified, at least one bit in the range
37476 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
37477 **     the EXCLUSIVE lock, thus signaling other connections on the same
37478 **     database to flush their caches.
37479 **
37480 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
37481 **      than one billion transactions.
37482 **
37483 ** (11) A database file is well-formed at the beginning and at the conclusion
37484 **      of every transaction.
37485 **
37486 ** (12) An EXCLUSIVE lock is held on the database file when writing to
37487 **      the database file.
37488 **
37489 ** (13) A SHARED lock is held on the database file while reading any
37490 **      content out of the database file.
37491 **
37492 ******************************************************************************/
37493 
37494 /*
37495 ** Macros for troubleshooting.  Normally turned off
37496 */
37497 #if 0
37498 int sqlite3PagerTrace=1;  /* True to enable tracing */
37499 #define sqlite3DebugPrintf printf
37500 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
37501 #else
37502 #define PAGERTRACE(X)
37503 #endif
37504 
37505 /*
37506 ** The following two macros are used within the PAGERTRACE() macros above
37507 ** to print out file-descriptors.
37508 **
37509 ** PAGERID() takes a pointer to a Pager struct as its argument. The
37510 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
37511 ** struct as its argument.
37512 */
37513 #define PAGERID(p) ((int)(p->fd))
37514 #define FILEHANDLEID(fd) ((int)fd)
37515 
37516 /*
37517 ** The Pager.eState variable stores the current 'state' of a pager. A
37518 ** pager may be in any one of the seven states shown in the following
37519 ** state diagram.
37520 **
37521 **                            OPEN <------+------+
37522 **                              |         |      |
37523 **                              V         |      |
37524 **               +---------> READER-------+      |
37525 **               |              |                |
37526 **               |              V                |
37527 **               |<-------WRITER_LOCKED------> ERROR
37528 **               |              |                ^
37529 **               |              V                |
37530 **               |<------WRITER_CACHEMOD-------->|
37531 **               |              |                |
37532 **               |              V                |
37533 **               |<-------WRITER_DBMOD---------->|
37534 **               |              |                |
37535 **               |              V                |
37536 **               +<------WRITER_FINISHED-------->+
37537 **
37538 **
37539 ** List of state transitions and the C [function] that performs each:
37540 **
37541 **   OPEN              -> READER              [sqlite3PagerSharedLock]
37542 **   READER            -> OPEN                [pager_unlock]
37543 **
37544 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
37545 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
37546 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
37547 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
37548 **   WRITER_***        -> READER              [pager_end_transaction]
37549 **
37550 **   WRITER_***        -> ERROR               [pager_error]
37551 **   ERROR             -> OPEN                [pager_unlock]
37552 **
37553 **
37554 **  OPEN:
37555 **
37556 **    The pager starts up in this state. Nothing is guaranteed in this
37557 **    state - the file may or may not be locked and the database size is
37558 **    unknown. The database may not be read or written.
37559 **
37560 **    * No read or write transaction is active.
37561 **    * Any lock, or no lock at all, may be held on the database file.
37562 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
37563 **
37564 **  READER:
37565 **
37566 **    In this state all the requirements for reading the database in
37567 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
37568 **    was) in exclusive-locking mode, a user-level read transaction is
37569 **    open. The database size is known in this state.
37570 **
37571 **    A connection running with locking_mode=normal enters this state when
37572 **    it opens a read-transaction on the database and returns to state
37573 **    OPEN after the read-transaction is completed. However a connection
37574 **    running in locking_mode=exclusive (including temp databases) remains in
37575 **    this state even after the read-transaction is closed. The only way
37576 **    a locking_mode=exclusive connection can transition from READER to OPEN
37577 **    is via the ERROR state (see below).
37578 **
37579 **    * A read transaction may be active (but a write-transaction cannot).
37580 **    * A SHARED or greater lock is held on the database file.
37581 **    * The dbSize variable may be trusted (even if a user-level read
37582 **      transaction is not active). The dbOrigSize and dbFileSize variables
37583 **      may not be trusted at this point.
37584 **    * If the database is a WAL database, then the WAL connection is open.
37585 **    * Even if a read-transaction is not open, it is guaranteed that
37586 **      there is no hot-journal in the file-system.
37587 **
37588 **  WRITER_LOCKED:
37589 **
37590 **    The pager moves to this state from READER when a write-transaction
37591 **    is first opened on the database. In WRITER_LOCKED state, all locks
37592 **    required to start a write-transaction are held, but no actual
37593 **    modifications to the cache or database have taken place.
37594 **
37595 **    In rollback mode, a RESERVED or (if the transaction was opened with
37596 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37597 **    moving to this state, but the journal file is not written to or opened
37598 **    to in this state. If the transaction is committed or rolled back while
37599 **    in WRITER_LOCKED state, all that is required is to unlock the database
37600 **    file.
37601 **
37602 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37603 **    If the connection is running with locking_mode=exclusive, an attempt
37604 **    is made to obtain an EXCLUSIVE lock on the database file.
37605 **
37606 **    * A write transaction is active.
37607 **    * If the connection is open in rollback-mode, a RESERVED or greater
37608 **      lock is held on the database file.
37609 **    * If the connection is open in WAL-mode, a WAL write transaction
37610 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37611 **      called).
37612 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37613 **    * The contents of the pager cache have not been modified.
37614 **    * The journal file may or may not be open.
37615 **    * Nothing (not even the first header) has been written to the journal.
37616 **
37617 **  WRITER_CACHEMOD:
37618 **
37619 **    A pager moves from WRITER_LOCKED state to this state when a page is
37620 **    first modified by the upper layer. In rollback mode the journal file
37621 **    is opened (if it is not already open) and a header written to the
37622 **    start of it. The database file on disk has not been modified.
37623 **
37624 **    * A write transaction is active.
37625 **    * A RESERVED or greater lock is held on the database file.
37626 **    * The journal file is open and the first header has been written
37627 **      to it, but the header has not been synced to disk.
37628 **    * The contents of the page cache have been modified.
37629 **
37630 **  WRITER_DBMOD:
37631 **
37632 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37633 **    when it modifies the contents of the database file. WAL connections
37634 **    never enter this state (since they do not modify the database file,
37635 **    just the log file).
37636 **
37637 **    * A write transaction is active.
37638 **    * An EXCLUSIVE or greater lock is held on the database file.
37639 **    * The journal file is open and the first header has been written
37640 **      and synced to disk.
37641 **    * The contents of the page cache have been modified (and possibly
37642 **      written to disk).
37643 **
37644 **  WRITER_FINISHED:
37645 **
37646 **    It is not possible for a WAL connection to enter this state.
37647 **
37648 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37649 **    state after the entire transaction has been successfully written into the
37650 **    database file. In this state the transaction may be committed simply
37651 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
37652 **    not possible to modify the database further. At this point, the upper
37653 **    layer must either commit or rollback the transaction.
37654 **
37655 **    * A write transaction is active.
37656 **    * An EXCLUSIVE or greater lock is held on the database file.
37657 **    * All writing and syncing of journal and database data has finished.
37658 **      If no error occurred, all that remains is to finalize the journal to
37659 **      commit the transaction. If an error did occur, the caller will need
37660 **      to rollback the transaction.
37661 **
37662 **  ERROR:
37663 **
37664 **    The ERROR state is entered when an IO or disk-full error (including
37665 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
37666 **    difficult to be sure that the in-memory pager state (cache contents,
37667 **    db size etc.) are consistent with the contents of the file-system.
37668 **
37669 **    Temporary pager files may enter the ERROR state, but in-memory pagers
37670 **    cannot.
37671 **
37672 **    For example, if an IO error occurs while performing a rollback,
37673 **    the contents of the page-cache may be left in an inconsistent state.
37674 **    At this point it would be dangerous to change back to READER state
37675 **    (as usually happens after a rollback). Any subsequent readers might
37676 **    report database corruption (due to the inconsistent cache), and if
37677 **    they upgrade to writers, they may inadvertently corrupt the database
37678 **    file. To avoid this hazard, the pager switches into the ERROR state
37679 **    instead of READER following such an error.
37680 **
37681 **    Once it has entered the ERROR state, any attempt to use the pager
37682 **    to read or write data returns an error. Eventually, once all
37683 **    outstanding transactions have been abandoned, the pager is able to
37684 **    transition back to OPEN state, discarding the contents of the
37685 **    page-cache and any other in-memory state at the same time. Everything
37686 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37687 **    when a read-transaction is next opened on the pager (transitioning
37688 **    the pager into READER state). At that point the system has recovered
37689 **    from the error.
37690 **
37691 **    Specifically, the pager jumps into the ERROR state if:
37692 **
37693 **      1. An error occurs while attempting a rollback. This happens in
37694 **         function sqlite3PagerRollback().
37695 **
37696 **      2. An error occurs while attempting to finalize a journal file
37697 **         following a commit in function sqlite3PagerCommitPhaseTwo().
37698 **
37699 **      3. An error occurs while attempting to write to the journal or
37700 **         database file in function pagerStress() in order to free up
37701 **         memory.
37702 **
37703 **    In other cases, the error is returned to the b-tree layer. The b-tree
37704 **    layer then attempts a rollback operation. If the error condition
37705 **    persists, the pager enters the ERROR state via condition (1) above.
37706 **
37707 **    Condition (3) is necessary because it can be triggered by a read-only
37708 **    statement executed within a transaction. In this case, if the error
37709 **    code were simply returned to the user, the b-tree layer would not
37710 **    automatically attempt a rollback, as it assumes that an error in a
37711 **    read-only statement cannot leave the pager in an internally inconsistent
37712 **    state.
37713 **
37714 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
37715 **    * There are one or more outstanding references to pages (after the
37716 **      last reference is dropped the pager should move back to OPEN state).
37717 **    * The pager is not an in-memory pager.
37718 **
37719 **
37720 ** Notes:
37721 **
37722 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37723 **     connection is open in WAL mode. A WAL connection is always in one
37724 **     of the first four states.
37725 **
37726 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37727 **     state. There are two exceptions: immediately after exclusive-mode has
37728 **     been turned on (and before any read or write transactions are
37729 **     executed), and when the pager is leaving the "error state".
37730 **
37731 **   * See also: assert_pager_state().
37732 */
37733 #define PAGER_OPEN                  0
37734 #define PAGER_READER                1
37735 #define PAGER_WRITER_LOCKED         2
37736 #define PAGER_WRITER_CACHEMOD       3
37737 #define PAGER_WRITER_DBMOD          4
37738 #define PAGER_WRITER_FINISHED       5
37739 #define PAGER_ERROR                 6
37740 
37741 /*
37742 ** The Pager.eLock variable is almost always set to one of the
37743 ** following locking-states, according to the lock currently held on
37744 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37745 ** This variable is kept up to date as locks are taken and released by
37746 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37747 **
37748 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37749 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37750 ** the operation was successful. In these circumstances pagerLockDb() and
37751 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37752 ** when unlocking the file, and only updated when locking the file if the
37753 ** VFS call is successful. This way, the Pager.eLock variable may be set
37754 ** to a less exclusive (lower) value than the lock that is actually held
37755 ** at the system level, but it is never set to a more exclusive value.
37756 **
37757 ** This is usually safe. If an xUnlock fails or appears to fail, there may
37758 ** be a few redundant xLock() calls or a lock may be held for longer than
37759 ** required, but nothing really goes wrong.
37760 **
37761 ** The exception is when the database file is unlocked as the pager moves
37762 ** from ERROR to OPEN state. At this point there may be a hot-journal file
37763 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37764 ** transition, by the same pager or any other). If the call to xUnlock()
37765 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37766 ** can confuse the call to xCheckReservedLock() call made later as part
37767 ** of hot-journal detection.
37768 **
37769 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
37770 ** lock held by this process or any others". So xCheckReservedLock may
37771 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37772 ** doesn't know it because of a previous error in xUnlock). If this happens
37773 ** a hot-journal may be mistaken for a journal being created by an active
37774 ** transaction in another process, causing SQLite to read from the database
37775 ** without rolling it back.
37776 **
37777 ** To work around this, if a call to xUnlock() fails when unlocking the
37778 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37779 ** is only changed back to a real locking state after a successful call
37780 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37781 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
37782 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37783 ** lock on the database file before attempting to roll it back. See function
37784 ** PagerSharedLock() for more detail.
37785 **
37786 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
37787 ** PAGER_OPEN state.
37788 */
37789 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
37790 
37791 /*
37792 ** A macro used for invoking the codec if there is one
37793 */
37794 #ifdef SQLITE_HAS_CODEC
37795 # define CODEC1(P,D,N,X,E) \
37796     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37797 # define CODEC2(P,D,N,X,E,O) \
37798     if( P->xCodec==0 ){ O=(char*)D; }else \
37799     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37800 #else
37801 # define CODEC1(P,D,N,X,E)   /* NO-OP */
37802 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37803 #endif
37804 
37805 /*
37806 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
37807 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37808 ** This could conceivably cause corruption following a power failure on
37809 ** such a system. This is currently an undocumented limit.
37810 */
37811 #define MAX_SECTOR_SIZE 0x10000
37812 
37813 /*
37814 ** An instance of the following structure is allocated for each active
37815 ** savepoint and statement transaction in the system. All such structures
37816 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37817 ** resized using sqlite3Realloc().
37818 **
37819 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37820 ** set to 0. If a journal-header is written into the main journal while
37821 ** the savepoint is active, then iHdrOffset is set to the byte offset
37822 ** immediately following the last journal record written into the main
37823 ** journal before the journal-header. This is required during savepoint
37824 ** rollback (see pagerPlaybackSavepoint()).
37825 */
37826 typedef struct PagerSavepoint PagerSavepoint;
37827 struct PagerSavepoint {
37828   i64 iOffset;                 /* Starting offset in main journal */
37829   i64 iHdrOffset;              /* See above */
37830   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
37831   Pgno nOrig;                  /* Original number of pages in file */
37832   Pgno iSubRec;                /* Index of first record in sub-journal */
37833 #ifndef SQLITE_OMIT_WAL
37834   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
37835 #endif
37836 };
37837 
37838 /*
37839 ** A open page cache is an instance of struct Pager. A description of
37840 ** some of the more important member variables follows:
37841 **
37842 ** eState
37843 **
37844 **   The current 'state' of the pager object. See the comment and state
37845 **   diagram above for a description of the pager state.
37846 **
37847 ** eLock
37848 **
37849 **   For a real on-disk database, the current lock held on the database file -
37850 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37851 **
37852 **   For a temporary or in-memory database (neither of which require any
37853 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
37854 **   databases always have Pager.exclusiveMode==1, this tricks the pager
37855 **   logic into thinking that it already has all the locks it will ever
37856 **   need (and no reason to release them).
37857 **
37858 **   In some (obscure) circumstances, this variable may also be set to
37859 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
37860 **   details.
37861 **
37862 ** changeCountDone
37863 **
37864 **   This boolean variable is used to make sure that the change-counter
37865 **   (the 4-byte header field at byte offset 24 of the database file) is
37866 **   not updated more often than necessary.
37867 **
37868 **   It is set to true when the change-counter field is updated, which
37869 **   can only happen if an exclusive lock is held on the database file.
37870 **   It is cleared (set to false) whenever an exclusive lock is
37871 **   relinquished on the database file. Each time a transaction is committed,
37872 **   The changeCountDone flag is inspected. If it is true, the work of
37873 **   updating the change-counter is omitted for the current transaction.
37874 **
37875 **   This mechanism means that when running in exclusive mode, a connection
37876 **   need only update the change-counter once, for the first transaction
37877 **   committed.
37878 **
37879 ** setMaster
37880 **
37881 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
37882 **   (or may not) specify a master-journal name to be written into the
37883 **   journal file before it is synced to disk.
37884 **
37885 **   Whether or not a journal file contains a master-journal pointer affects
37886 **   the way in which the journal file is finalized after the transaction is
37887 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
37888 **   If a journal file does not contain a master-journal pointer, it is
37889 **   finalized by overwriting the first journal header with zeroes. If
37890 **   it does contain a master-journal pointer the journal file is finalized
37891 **   by truncating it to zero bytes, just as if the connection were
37892 **   running in "journal_mode=truncate" mode.
37893 **
37894 **   Journal files that contain master journal pointers cannot be finalized
37895 **   simply by overwriting the first journal-header with zeroes, as the
37896 **   master journal pointer could interfere with hot-journal rollback of any
37897 **   subsequently interrupted transaction that reuses the journal file.
37898 **
37899 **   The flag is cleared as soon as the journal file is finalized (either
37900 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
37901 **   journal file from being successfully finalized, the setMaster flag
37902 **   is cleared anyway (and the pager will move to ERROR state).
37903 **
37904 ** doNotSpill, doNotSyncSpill
37905 **
37906 **   These two boolean variables control the behavior of cache-spills
37907 **   (calls made by the pcache module to the pagerStress() routine to
37908 **   write cached data to the file-system in order to free up memory).
37909 **
37910 **   When doNotSpill is non-zero, writing to the database from pagerStress()
37911 **   is disabled altogether. This is done in a very obscure case that
37912 **   comes up during savepoint rollback that requires the pcache module
37913 **   to allocate a new page to prevent the journal file from being written
37914 **   while it is being traversed by code in pager_playback().
37915 **
37916 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
37917 **   is permitted, but syncing the journal file is not. This flag is set
37918 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
37919 **   the database page-size in order to prevent a journal sync from happening
37920 **   in between the journalling of two pages on the same sector.
37921 **
37922 ** subjInMemory
37923 **
37924 **   This is a boolean variable. If true, then any required sub-journal
37925 **   is opened as an in-memory journal file. If false, then in-memory
37926 **   sub-journals are only used for in-memory pager files.
37927 **
37928 **   This variable is updated by the upper layer each time a new
37929 **   write-transaction is opened.
37930 **
37931 ** dbSize, dbOrigSize, dbFileSize
37932 **
37933 **   Variable dbSize is set to the number of pages in the database file.
37934 **   It is valid in PAGER_READER and higher states (all states except for
37935 **   OPEN and ERROR).
37936 **
37937 **   dbSize is set based on the size of the database file, which may be
37938 **   larger than the size of the database (the value stored at offset
37939 **   28 of the database header by the btree). If the size of the file
37940 **   is not an integer multiple of the page-size, the value stored in
37941 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37942 **   Except, any file that is greater than 0 bytes in size is considered
37943 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
37944 **   to dbSize==1).
37945 **
37946 **   During a write-transaction, if pages with page-numbers greater than
37947 **   dbSize are modified in the cache, dbSize is updated accordingly.
37948 **   Similarly, if the database is truncated using PagerTruncateImage(),
37949 **   dbSize is updated.
37950 **
37951 **   Variables dbOrigSize and dbFileSize are valid in states
37952 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37953 **   variable at the start of the transaction. It is used during rollback,
37954 **   and to determine whether or not pages need to be journalled before
37955 **   being modified.
37956 **
37957 **   Throughout a write-transaction, dbFileSize contains the size of
37958 **   the file on disk in pages. It is set to a copy of dbSize when the
37959 **   write-transaction is first opened, and updated when VFS calls are made
37960 **   to write or truncate the database file on disk.
37961 **
37962 **   The only reason the dbFileSize variable is required is to suppress
37963 **   unnecessary calls to xTruncate() after committing a transaction. If,
37964 **   when a transaction is committed, the dbFileSize variable indicates
37965 **   that the database file is larger than the database image (Pager.dbSize),
37966 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
37967 **   to measure the database file on disk, and then truncates it if required.
37968 **   dbFileSize is not used when rolling back a transaction. In this case
37969 **   pager_truncate() is called unconditionally (which means there may be
37970 **   a call to xFilesize() that is not strictly required). In either case,
37971 **   pager_truncate() may cause the file to become smaller or larger.
37972 **
37973 ** dbHintSize
37974 **
37975 **   The dbHintSize variable is used to limit the number of calls made to
37976 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
37977 **
37978 **   dbHintSize is set to a copy of the dbSize variable when a
37979 **   write-transaction is opened (at the same time as dbFileSize and
37980 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37981 **   dbHintSize is increased to the number of pages that correspond to the
37982 **   size-hint passed to the method call. See pager_write_pagelist() for
37983 **   details.
37984 **
37985 ** errCode
37986 **
37987 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37988 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
37989 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
37990 **   sub-codes.
37991 */
37992 struct Pager {
37993   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
37994   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
37995   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
37996   u8 useJournal;              /* Use a rollback journal on this file */
37997   u8 noSync;                  /* Do not sync the journal if true */
37998   u8 fullSync;                /* Do extra syncs of the journal for robustness */
37999   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
38000   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
38001   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
38002   u8 tempFile;                /* zFilename is a temporary file */
38003   u8 readOnly;                /* True for a read-only database */
38004   u8 memDb;                   /* True to inhibit all file I/O */
38005 
38006   /**************************************************************************
38007   ** The following block contains those class members that change during
38008   ** routine opertion.  Class members not in this block are either fixed
38009   ** when the pager is first created or else only change when there is a
38010   ** significant mode change (such as changing the page_size, locking_mode,
38011   ** or the journal_mode).  From another view, these class members describe
38012   ** the "state" of the pager, while other class members describe the
38013   ** "configuration" of the pager.
38014   */
38015   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
38016   u8 eLock;                   /* Current lock held on database file */
38017   u8 changeCountDone;         /* Set after incrementing the change-counter */
38018   u8 setMaster;               /* True if a m-j name has been written to jrnl */
38019   u8 doNotSpill;              /* Do not spill the cache when non-zero */
38020   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
38021   u8 subjInMemory;            /* True to use in-memory sub-journals */
38022   Pgno dbSize;                /* Number of pages in the database */
38023   Pgno dbOrigSize;            /* dbSize before the current transaction */
38024   Pgno dbFileSize;            /* Number of pages in the database file */
38025   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
38026   int errCode;                /* One of several kinds of errors */
38027   int nRec;                   /* Pages journalled since last j-header written */
38028   u32 cksumInit;              /* Quasi-random value added to every checksum */
38029   u32 nSubRec;                /* Number of records written to sub-journal */
38030   Bitvec *pInJournal;         /* One bit for each page in the database file */
38031   sqlite3_file *fd;           /* File descriptor for database */
38032   sqlite3_file *jfd;          /* File descriptor for main journal */
38033   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
38034   i64 journalOff;             /* Current write offset in the journal file */
38035   i64 journalHdr;             /* Byte offset to previous journal header */
38036   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
38037   PagerSavepoint *aSavepoint; /* Array of active savepoints */
38038   int nSavepoint;             /* Number of elements in aSavepoint[] */
38039   char dbFileVers[16];        /* Changes whenever database file changes */
38040   /*
38041   ** End of the routinely-changing class members
38042   ***************************************************************************/
38043 
38044   u16 nExtra;                 /* Add this many bytes to each in-memory page */
38045   i16 nReserve;               /* Number of unused bytes at end of each page */
38046   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
38047   u32 sectorSize;             /* Assumed sector size during rollback */
38048   int pageSize;               /* Number of bytes in a page */
38049   Pgno mxPgno;                /* Maximum allowed size of the database */
38050   i64 journalSizeLimit;       /* Size limit for persistent journal files */
38051   char *zFilename;            /* Name of the database file */
38052   char *zJournal;             /* Name of the journal file */
38053   int (*xBusyHandler)(void*); /* Function to call when busy */
38054   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
38055   int aStat[3];               /* Total cache hits, misses and writes */
38056 #ifdef SQLITE_TEST
38057   int nRead;                  /* Database pages read */
38058 #endif
38059   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
38060 #ifdef SQLITE_HAS_CODEC
38061   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
38062   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
38063   void (*xCodecFree)(void*);             /* Destructor for the codec */
38064   void *pCodec;               /* First argument to xCodec... methods */
38065 #endif
38066   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
38067   PCache *pPCache;            /* Pointer to page cache object */
38068 #ifndef SQLITE_OMIT_WAL
38069   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
38070   char *zWal;                 /* File name for write-ahead log */
38071 #endif
38072 };
38073 
38074 /*
38075 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
38076 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
38077 ** or CACHE_WRITE to sqlite3_db_status().
38078 */
38079 #define PAGER_STAT_HIT   0
38080 #define PAGER_STAT_MISS  1
38081 #define PAGER_STAT_WRITE 2
38082 
38083 /*
38084 ** The following global variables hold counters used for
38085 ** testing purposes only.  These variables do not exist in
38086 ** a non-testing build.  These variables are not thread-safe.
38087 */
38088 #ifdef SQLITE_TEST
38089 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
38090 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
38091 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
38092 # define PAGER_INCR(v)  v++
38093 #else
38094 # define PAGER_INCR(v)
38095 #endif
38096 
38097 
38098 
38099 /*
38100 ** Journal files begin with the following magic string.  The data
38101 ** was obtained from /dev/random.  It is used only as a sanity check.
38102 **
38103 ** Since version 2.8.0, the journal format contains additional sanity
38104 ** checking information.  If the power fails while the journal is being
38105 ** written, semi-random garbage data might appear in the journal
38106 ** file after power is restored.  If an attempt is then made
38107 ** to roll the journal back, the database could be corrupted.  The additional
38108 ** sanity checking data is an attempt to discover the garbage in the
38109 ** journal and ignore it.
38110 **
38111 ** The sanity checking information for the new journal format consists
38112 ** of a 32-bit checksum on each page of data.  The checksum covers both
38113 ** the page number and the pPager->pageSize bytes of data for the page.
38114 ** This cksum is initialized to a 32-bit random value that appears in the
38115 ** journal file right after the header.  The random initializer is important,
38116 ** because garbage data that appears at the end of a journal is likely
38117 ** data that was once in other files that have now been deleted.  If the
38118 ** garbage data came from an obsolete journal file, the checksums might
38119 ** be correct.  But by initializing the checksum to random value which
38120 ** is different for every journal, we minimize that risk.
38121 */
38122 static const unsigned char aJournalMagic[] = {
38123   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
38124 };
38125 
38126 /*
38127 ** The size of the of each page record in the journal is given by
38128 ** the following macro.
38129 */
38130 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
38131 
38132 /*
38133 ** The journal header size for this pager. This is usually the same
38134 ** size as a single disk sector. See also setSectorSize().
38135 */
38136 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
38137 
38138 /*
38139 ** The macro MEMDB is true if we are dealing with an in-memory database.
38140 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
38141 ** the value of MEMDB will be a constant and the compiler will optimize
38142 ** out code that would never execute.
38143 */
38144 #ifdef SQLITE_OMIT_MEMORYDB
38145 # define MEMDB 0
38146 #else
38147 # define MEMDB pPager->memDb
38148 #endif
38149 
38150 /*
38151 ** The maximum legal page number is (2^31 - 1).
38152 */
38153 #define PAGER_MAX_PGNO 2147483647
38154 
38155 /*
38156 ** The argument to this macro is a file descriptor (type sqlite3_file*).
38157 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
38158 **
38159 ** This is so that expressions can be written as:
38160 **
38161 **   if( isOpen(pPager->jfd) ){ ...
38162 **
38163 ** instead of
38164 **
38165 **   if( pPager->jfd->pMethods ){ ...
38166 */
38167 #define isOpen(pFd) ((pFd)->pMethods)
38168 
38169 /*
38170 ** Return true if this pager uses a write-ahead log instead of the usual
38171 ** rollback journal. Otherwise false.
38172 */
38173 #ifndef SQLITE_OMIT_WAL
38174 static int pagerUseWal(Pager *pPager){
38175   return (pPager->pWal!=0);
38176 }
38177 #else
38178 # define pagerUseWal(x) 0
38179 # define pagerRollbackWal(x) 0
38180 # define pagerWalFrames(v,w,x,y) 0
38181 # define pagerOpenWalIfPresent(z) SQLITE_OK
38182 # define pagerBeginReadTransaction(z) SQLITE_OK
38183 #endif
38184 
38185 #ifndef NDEBUG
38186 /*
38187 ** Usage:
38188 **
38189 **   assert( assert_pager_state(pPager) );
38190 **
38191 ** This function runs many asserts to try to find inconsistencies in
38192 ** the internal state of the Pager object.
38193 */
38194 static int assert_pager_state(Pager *p){
38195   Pager *pPager = p;
38196 
38197   /* State must be valid. */
38198   assert( p->eState==PAGER_OPEN
38199        || p->eState==PAGER_READER
38200        || p->eState==PAGER_WRITER_LOCKED
38201        || p->eState==PAGER_WRITER_CACHEMOD
38202        || p->eState==PAGER_WRITER_DBMOD
38203        || p->eState==PAGER_WRITER_FINISHED
38204        || p->eState==PAGER_ERROR
38205   );
38206 
38207   /* Regardless of the current state, a temp-file connection always behaves
38208   ** as if it has an exclusive lock on the database file. It never updates
38209   ** the change-counter field, so the changeCountDone flag is always set.
38210   */
38211   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
38212   assert( p->tempFile==0 || pPager->changeCountDone );
38213 
38214   /* If the useJournal flag is clear, the journal-mode must be "OFF".
38215   ** And if the journal-mode is "OFF", the journal file must not be open.
38216   */
38217   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
38218   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
38219 
38220   /* Check that MEMDB implies noSync. And an in-memory journal. Since
38221   ** this means an in-memory pager performs no IO at all, it cannot encounter
38222   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
38223   ** a journal file. (although the in-memory journal implementation may
38224   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
38225   ** is therefore not possible for an in-memory pager to enter the ERROR
38226   ** state.
38227   */
38228   if( MEMDB ){
38229     assert( p->noSync );
38230     assert( p->journalMode==PAGER_JOURNALMODE_OFF
38231          || p->journalMode==PAGER_JOURNALMODE_MEMORY
38232     );
38233     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
38234     assert( pagerUseWal(p)==0 );
38235   }
38236 
38237   /* If changeCountDone is set, a RESERVED lock or greater must be held
38238   ** on the file.
38239   */
38240   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
38241   assert( p->eLock!=PENDING_LOCK );
38242 
38243   switch( p->eState ){
38244     case PAGER_OPEN:
38245       assert( !MEMDB );
38246       assert( pPager->errCode==SQLITE_OK );
38247       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
38248       break;
38249 
38250     case PAGER_READER:
38251       assert( pPager->errCode==SQLITE_OK );
38252       assert( p->eLock!=UNKNOWN_LOCK );
38253       assert( p->eLock>=SHARED_LOCK );
38254       break;
38255 
38256     case PAGER_WRITER_LOCKED:
38257       assert( p->eLock!=UNKNOWN_LOCK );
38258       assert( pPager->errCode==SQLITE_OK );
38259       if( !pagerUseWal(pPager) ){
38260         assert( p->eLock>=RESERVED_LOCK );
38261       }
38262       assert( pPager->dbSize==pPager->dbOrigSize );
38263       assert( pPager->dbOrigSize==pPager->dbFileSize );
38264       assert( pPager->dbOrigSize==pPager->dbHintSize );
38265       assert( pPager->setMaster==0 );
38266       break;
38267 
38268     case PAGER_WRITER_CACHEMOD:
38269       assert( p->eLock!=UNKNOWN_LOCK );
38270       assert( pPager->errCode==SQLITE_OK );
38271       if( !pagerUseWal(pPager) ){
38272         /* It is possible that if journal_mode=wal here that neither the
38273         ** journal file nor the WAL file are open. This happens during
38274         ** a rollback transaction that switches from journal_mode=off
38275         ** to journal_mode=wal.
38276         */
38277         assert( p->eLock>=RESERVED_LOCK );
38278         assert( isOpen(p->jfd)
38279              || p->journalMode==PAGER_JOURNALMODE_OFF
38280              || p->journalMode==PAGER_JOURNALMODE_WAL
38281         );
38282       }
38283       assert( pPager->dbOrigSize==pPager->dbFileSize );
38284       assert( pPager->dbOrigSize==pPager->dbHintSize );
38285       break;
38286 
38287     case PAGER_WRITER_DBMOD:
38288       assert( p->eLock==EXCLUSIVE_LOCK );
38289       assert( pPager->errCode==SQLITE_OK );
38290       assert( !pagerUseWal(pPager) );
38291       assert( p->eLock>=EXCLUSIVE_LOCK );
38292       assert( isOpen(p->jfd)
38293            || p->journalMode==PAGER_JOURNALMODE_OFF
38294            || p->journalMode==PAGER_JOURNALMODE_WAL
38295       );
38296       assert( pPager->dbOrigSize<=pPager->dbHintSize );
38297       break;
38298 
38299     case PAGER_WRITER_FINISHED:
38300       assert( p->eLock==EXCLUSIVE_LOCK );
38301       assert( pPager->errCode==SQLITE_OK );
38302       assert( !pagerUseWal(pPager) );
38303       assert( isOpen(p->jfd)
38304            || p->journalMode==PAGER_JOURNALMODE_OFF
38305            || p->journalMode==PAGER_JOURNALMODE_WAL
38306       );
38307       break;
38308 
38309     case PAGER_ERROR:
38310       /* There must be at least one outstanding reference to the pager if
38311       ** in ERROR state. Otherwise the pager should have already dropped
38312       ** back to OPEN state.
38313       */
38314       assert( pPager->errCode!=SQLITE_OK );
38315       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
38316       break;
38317   }
38318 
38319   return 1;
38320 }
38321 #endif /* ifndef NDEBUG */
38322 
38323 #ifdef SQLITE_DEBUG
38324 /*
38325 ** Return a pointer to a human readable string in a static buffer
38326 ** containing the state of the Pager object passed as an argument. This
38327 ** is intended to be used within debuggers. For example, as an alternative
38328 ** to "print *pPager" in gdb:
38329 **
38330 ** (gdb) printf "%s", print_pager_state(pPager)
38331 */
38332 static char *print_pager_state(Pager *p){
38333   static char zRet[1024];
38334 
38335   sqlite3_snprintf(1024, zRet,
38336       "Filename:      %s\n"
38337       "State:         %s errCode=%d\n"
38338       "Lock:          %s\n"
38339       "Locking mode:  locking_mode=%s\n"
38340       "Journal mode:  journal_mode=%s\n"
38341       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
38342       "Journal:       journalOff=%lld journalHdr=%lld\n"
38343       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
38344       , p->zFilename
38345       , p->eState==PAGER_OPEN            ? "OPEN" :
38346         p->eState==PAGER_READER          ? "READER" :
38347         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
38348         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
38349         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
38350         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
38351         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
38352       , (int)p->errCode
38353       , p->eLock==NO_LOCK         ? "NO_LOCK" :
38354         p->eLock==RESERVED_LOCK   ? "RESERVED" :
38355         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
38356         p->eLock==SHARED_LOCK     ? "SHARED" :
38357         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
38358       , p->exclusiveMode ? "exclusive" : "normal"
38359       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
38360         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
38361         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
38362         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
38363         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
38364         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
38365       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
38366       , p->journalOff, p->journalHdr
38367       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
38368   );
38369 
38370   return zRet;
38371 }
38372 #endif
38373 
38374 /*
38375 ** Return true if it is necessary to write page *pPg into the sub-journal.
38376 ** A page needs to be written into the sub-journal if there exists one
38377 ** or more open savepoints for which:
38378 **
38379 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
38380 **   * The bit corresponding to the page-number is not set in
38381 **     PagerSavepoint.pInSavepoint.
38382 */
38383 static int subjRequiresPage(PgHdr *pPg){
38384   Pgno pgno = pPg->pgno;
38385   Pager *pPager = pPg->pPager;
38386   int i;
38387   for(i=0; i<pPager->nSavepoint; i++){
38388     PagerSavepoint *p = &pPager->aSavepoint[i];
38389     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
38390       return 1;
38391     }
38392   }
38393   return 0;
38394 }
38395 
38396 /*
38397 ** Return true if the page is already in the journal file.
38398 */
38399 static int pageInJournal(PgHdr *pPg){
38400   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
38401 }
38402 
38403 /*
38404 ** Read a 32-bit integer from the given file descriptor.  Store the integer
38405 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
38406 ** error code is something goes wrong.
38407 **
38408 ** All values are stored on disk as big-endian.
38409 */
38410 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
38411   unsigned char ac[4];
38412   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
38413   if( rc==SQLITE_OK ){
38414     *pRes = sqlite3Get4byte(ac);
38415   }
38416   return rc;
38417 }
38418 
38419 /*
38420 ** Write a 32-bit integer into a string buffer in big-endian byte order.
38421 */
38422 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
38423 
38424 
38425 /*
38426 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
38427 ** on success or an error code is something goes wrong.
38428 */
38429 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
38430   char ac[4];
38431   put32bits(ac, val);
38432   return sqlite3OsWrite(fd, ac, 4, offset);
38433 }
38434 
38435 /*
38436 ** Unlock the database file to level eLock, which must be either NO_LOCK
38437 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
38438 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
38439 **
38440 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38441 ** called, do not modify it. See the comment above the #define of
38442 ** UNKNOWN_LOCK for an explanation of this.
38443 */
38444 static int pagerUnlockDb(Pager *pPager, int eLock){
38445   int rc = SQLITE_OK;
38446 
38447   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
38448   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
38449   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
38450   if( isOpen(pPager->fd) ){
38451     assert( pPager->eLock>=eLock );
38452     rc = sqlite3OsUnlock(pPager->fd, eLock);
38453     if( pPager->eLock!=UNKNOWN_LOCK ){
38454       pPager->eLock = (u8)eLock;
38455     }
38456     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
38457   }
38458   return rc;
38459 }
38460 
38461 /*
38462 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
38463 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
38464 ** Pager.eLock variable to the new locking state.
38465 **
38466 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38467 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
38468 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
38469 ** of this.
38470 */
38471 static int pagerLockDb(Pager *pPager, int eLock){
38472   int rc = SQLITE_OK;
38473 
38474   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
38475   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
38476     rc = sqlite3OsLock(pPager->fd, eLock);
38477     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
38478       pPager->eLock = (u8)eLock;
38479       IOTRACE(("LOCK %p %d\n", pPager, eLock))
38480     }
38481   }
38482   return rc;
38483 }
38484 
38485 /*
38486 ** This function determines whether or not the atomic-write optimization
38487 ** can be used with this pager. The optimization can be used if:
38488 **
38489 **  (a) the value returned by OsDeviceCharacteristics() indicates that
38490 **      a database page may be written atomically, and
38491 **  (b) the value returned by OsSectorSize() is less than or equal
38492 **      to the page size.
38493 **
38494 ** The optimization is also always enabled for temporary files. It is
38495 ** an error to call this function if pPager is opened on an in-memory
38496 ** database.
38497 **
38498 ** If the optimization cannot be used, 0 is returned. If it can be used,
38499 ** then the value returned is the size of the journal file when it
38500 ** contains rollback data for exactly one page.
38501 */
38502 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38503 static int jrnlBufferSize(Pager *pPager){
38504   assert( !MEMDB );
38505   if( !pPager->tempFile ){
38506     int dc;                           /* Device characteristics */
38507     int nSector;                      /* Sector size */
38508     int szPage;                       /* Page size */
38509 
38510     assert( isOpen(pPager->fd) );
38511     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
38512     nSector = pPager->sectorSize;
38513     szPage = pPager->pageSize;
38514 
38515     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38516     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38517     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
38518       return 0;
38519     }
38520   }
38521 
38522   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
38523 }
38524 #endif
38525 
38526 /*
38527 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
38528 ** on the cache using a hash function.  This is used for testing
38529 ** and debugging only.
38530 */
38531 #ifdef SQLITE_CHECK_PAGES
38532 /*
38533 ** Return a 32-bit hash of the page data for pPage.
38534 */
38535 static u32 pager_datahash(int nByte, unsigned char *pData){
38536   u32 hash = 0;
38537   int i;
38538   for(i=0; i<nByte; i++){
38539     hash = (hash*1039) + pData[i];
38540   }
38541   return hash;
38542 }
38543 static u32 pager_pagehash(PgHdr *pPage){
38544   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
38545 }
38546 static void pager_set_pagehash(PgHdr *pPage){
38547   pPage->pageHash = pager_pagehash(pPage);
38548 }
38549 
38550 /*
38551 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
38552 ** is defined, and NDEBUG is not defined, an assert() statement checks
38553 ** that the page is either dirty or still matches the calculated page-hash.
38554 */
38555 #define CHECK_PAGE(x) checkPage(x)
38556 static void checkPage(PgHdr *pPg){
38557   Pager *pPager = pPg->pPager;
38558   assert( pPager->eState!=PAGER_ERROR );
38559   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
38560 }
38561 
38562 #else
38563 #define pager_datahash(X,Y)  0
38564 #define pager_pagehash(X)  0
38565 #define pager_set_pagehash(X)
38566 #define CHECK_PAGE(x)
38567 #endif  /* SQLITE_CHECK_PAGES */
38568 
38569 /*
38570 ** When this is called the journal file for pager pPager must be open.
38571 ** This function attempts to read a master journal file name from the
38572 ** end of the file and, if successful, copies it into memory supplied
38573 ** by the caller. See comments above writeMasterJournal() for the format
38574 ** used to store a master journal file name at the end of a journal file.
38575 **
38576 ** zMaster must point to a buffer of at least nMaster bytes allocated by
38577 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
38578 ** enough space to write the master journal name). If the master journal
38579 ** name in the journal is longer than nMaster bytes (including a
38580 ** nul-terminator), then this is handled as if no master journal name
38581 ** were present in the journal.
38582 **
38583 ** If a master journal file name is present at the end of the journal
38584 ** file, then it is copied into the buffer pointed to by zMaster. A
38585 ** nul-terminator byte is appended to the buffer following the master
38586 ** journal file name.
38587 **
38588 ** If it is determined that no master journal file name is present
38589 ** zMaster[0] is set to 0 and SQLITE_OK returned.
38590 **
38591 ** If an error occurs while reading from the journal file, an SQLite
38592 ** error code is returned.
38593 */
38594 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
38595   int rc;                    /* Return code */
38596   u32 len;                   /* Length in bytes of master journal name */
38597   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
38598   u32 cksum;                 /* MJ checksum value read from journal */
38599   u32 u;                     /* Unsigned loop counter */
38600   unsigned char aMagic[8];   /* A buffer to hold the magic header */
38601   zMaster[0] = '\0';
38602 
38603   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38604    || szJ<16
38605    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38606    || len>=nMaster
38607    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38608    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38609    || memcmp(aMagic, aJournalMagic, 8)
38610    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38611   ){
38612     return rc;
38613   }
38614 
38615   /* See if the checksum matches the master journal name */
38616   for(u=0; u<len; u++){
38617     cksum -= zMaster[u];
38618   }
38619   if( cksum ){
38620     /* If the checksum doesn't add up, then one or more of the disk sectors
38621     ** containing the master journal filename is corrupted. This means
38622     ** definitely roll back, so just return SQLITE_OK and report a (nul)
38623     ** master-journal filename.
38624     */
38625     len = 0;
38626   }
38627   zMaster[len] = '\0';
38628 
38629   return SQLITE_OK;
38630 }
38631 
38632 /*
38633 ** Return the offset of the sector boundary at or immediately
38634 ** following the value in pPager->journalOff, assuming a sector
38635 ** size of pPager->sectorSize bytes.
38636 **
38637 ** i.e for a sector size of 512:
38638 **
38639 **   Pager.journalOff          Return value
38640 **   ---------------------------------------
38641 **   0                         0
38642 **   512                       512
38643 **   100                       512
38644 **   2000                      2048
38645 **
38646 */
38647 static i64 journalHdrOffset(Pager *pPager){
38648   i64 offset = 0;
38649   i64 c = pPager->journalOff;
38650   if( c ){
38651     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38652   }
38653   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38654   assert( offset>=c );
38655   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38656   return offset;
38657 }
38658 
38659 /*
38660 ** The journal file must be open when this function is called.
38661 **
38662 ** This function is a no-op if the journal file has not been written to
38663 ** within the current transaction (i.e. if Pager.journalOff==0).
38664 **
38665 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38666 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38667 ** zero the 28-byte header at the start of the journal file. In either case,
38668 ** if the pager is not in no-sync mode, sync the journal file immediately
38669 ** after writing or truncating it.
38670 **
38671 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38672 ** following the truncation or zeroing described above the size of the
38673 ** journal file in bytes is larger than this value, then truncate the
38674 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38675 ** not need to be synced following this operation.
38676 **
38677 ** If an IO error occurs, abandon processing and return the IO error code.
38678 ** Otherwise, return SQLITE_OK.
38679 */
38680 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38681   int rc = SQLITE_OK;                               /* Return code */
38682   assert( isOpen(pPager->jfd) );
38683   if( pPager->journalOff ){
38684     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
38685 
38686     IOTRACE(("JZEROHDR %p\n", pPager))
38687     if( doTruncate || iLimit==0 ){
38688       rc = sqlite3OsTruncate(pPager->jfd, 0);
38689     }else{
38690       static const char zeroHdr[28] = {0};
38691       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38692     }
38693     if( rc==SQLITE_OK && !pPager->noSync ){
38694       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38695     }
38696 
38697     /* At this point the transaction is committed but the write lock
38698     ** is still held on the file. If there is a size limit configured for
38699     ** the persistent journal and the journal file currently consumes more
38700     ** space than that limit allows for, truncate it now. There is no need
38701     ** to sync the file following this operation.
38702     */
38703     if( rc==SQLITE_OK && iLimit>0 ){
38704       i64 sz;
38705       rc = sqlite3OsFileSize(pPager->jfd, &sz);
38706       if( rc==SQLITE_OK && sz>iLimit ){
38707         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38708       }
38709     }
38710   }
38711   return rc;
38712 }
38713 
38714 /*
38715 ** The journal file must be open when this routine is called. A journal
38716 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38717 ** current location.
38718 **
38719 ** The format for the journal header is as follows:
38720 ** - 8 bytes: Magic identifying journal format.
38721 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38722 ** - 4 bytes: Random number used for page hash.
38723 ** - 4 bytes: Initial database page count.
38724 ** - 4 bytes: Sector size used by the process that wrote this journal.
38725 ** - 4 bytes: Database page size.
38726 **
38727 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38728 */
38729 static int writeJournalHdr(Pager *pPager){
38730   int rc = SQLITE_OK;                 /* Return code */
38731   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
38732   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38733   u32 nWrite;                         /* Bytes of header sector written */
38734   int ii;                             /* Loop counter */
38735 
38736   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38737 
38738   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38739     nHeader = JOURNAL_HDR_SZ(pPager);
38740   }
38741 
38742   /* If there are active savepoints and any of them were created
38743   ** since the most recent journal header was written, update the
38744   ** PagerSavepoint.iHdrOffset fields now.
38745   */
38746   for(ii=0; ii<pPager->nSavepoint; ii++){
38747     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38748       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38749     }
38750   }
38751 
38752   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38753 
38754   /*
38755   ** Write the nRec Field - the number of page records that follow this
38756   ** journal header. Normally, zero is written to this value at this time.
38757   ** After the records are added to the journal (and the journal synced,
38758   ** if in full-sync mode), the zero is overwritten with the true number
38759   ** of records (see syncJournal()).
38760   **
38761   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38762   ** reading the journal this value tells SQLite to assume that the
38763   ** rest of the journal file contains valid page records. This assumption
38764   ** is dangerous, as if a failure occurred whilst writing to the journal
38765   ** file it may contain some garbage data. There are two scenarios
38766   ** where this risk can be ignored:
38767   **
38768   **   * When the pager is in no-sync mode. Corruption can follow a
38769   **     power failure in this case anyway.
38770   **
38771   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38772   **     that garbage data is never appended to the journal file.
38773   */
38774   assert( isOpen(pPager->fd) || pPager->noSync );
38775   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38776    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
38777   ){
38778     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38779     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38780   }else{
38781     memset(zHeader, 0, sizeof(aJournalMagic)+4);
38782   }
38783 
38784   /* The random check-hash initializer */
38785   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38786   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38787   /* The initial database size */
38788   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38789   /* The assumed sector size for this process */
38790   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38791 
38792   /* The page size */
38793   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38794 
38795   /* Initializing the tail of the buffer is not necessary.  Everything
38796   ** works find if the following memset() is omitted.  But initializing
38797   ** the memory prevents valgrind from complaining, so we are willing to
38798   ** take the performance hit.
38799   */
38800   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38801          nHeader-(sizeof(aJournalMagic)+20));
38802 
38803   /* In theory, it is only necessary to write the 28 bytes that the
38804   ** journal header consumes to the journal file here. Then increment the
38805   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
38806   ** record is written to the following sector (leaving a gap in the file
38807   ** that will be implicitly filled in by the OS).
38808   **
38809   ** However it has been discovered that on some systems this pattern can
38810   ** be significantly slower than contiguously writing data to the file,
38811   ** even if that means explicitly writing data to the block of
38812   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38813   ** is done.
38814   **
38815   ** The loop is required here in case the sector-size is larger than the
38816   ** database page size. Since the zHeader buffer is only Pager.pageSize
38817   ** bytes in size, more than one call to sqlite3OsWrite() may be required
38818   ** to populate the entire journal header sector.
38819   */
38820   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38821     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38822     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38823     assert( pPager->journalHdr <= pPager->journalOff );
38824     pPager->journalOff += nHeader;
38825   }
38826 
38827   return rc;
38828 }
38829 
38830 /*
38831 ** The journal file must be open when this is called. A journal header file
38832 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38833 ** file. The current location in the journal file is given by
38834 ** pPager->journalOff. See comments above function writeJournalHdr() for
38835 ** a description of the journal header format.
38836 **
38837 ** If the header is read successfully, *pNRec is set to the number of
38838 ** page records following this header and *pDbSize is set to the size of the
38839 ** database before the transaction began, in pages. Also, pPager->cksumInit
38840 ** is set to the value read from the journal header. SQLITE_OK is returned
38841 ** in this case.
38842 **
38843 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38844 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
38845 ** cannot be read from the journal file an error code is returned.
38846 */
38847 static int readJournalHdr(
38848   Pager *pPager,               /* Pager object */
38849   int isHot,
38850   i64 journalSize,             /* Size of the open journal file in bytes */
38851   u32 *pNRec,                  /* OUT: Value read from the nRec field */
38852   u32 *pDbSize                 /* OUT: Value of original database size field */
38853 ){
38854   int rc;                      /* Return code */
38855   unsigned char aMagic[8];     /* A buffer to hold the magic header */
38856   i64 iHdrOff;                 /* Offset of journal header being read */
38857 
38858   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38859 
38860   /* Advance Pager.journalOff to the start of the next sector. If the
38861   ** journal file is too small for there to be a header stored at this
38862   ** point, return SQLITE_DONE.
38863   */
38864   pPager->journalOff = journalHdrOffset(pPager);
38865   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
38866     return SQLITE_DONE;
38867   }
38868   iHdrOff = pPager->journalOff;
38869 
38870   /* Read in the first 8 bytes of the journal header. If they do not match
38871   ** the  magic string found at the start of each journal header, return
38872   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
38873   ** proceed.
38874   */
38875   if( isHot || iHdrOff!=pPager->journalHdr ){
38876     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
38877     if( rc ){
38878       return rc;
38879     }
38880     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
38881       return SQLITE_DONE;
38882     }
38883   }
38884 
38885   /* Read the first three 32-bit fields of the journal header: The nRec
38886   ** field, the checksum-initializer and the database size at the start
38887   ** of the transaction. Return an error code if anything goes wrong.
38888   */
38889   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
38890    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
38891    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
38892   ){
38893     return rc;
38894   }
38895 
38896   if( pPager->journalOff==0 ){
38897     u32 iPageSize;               /* Page-size field of journal header */
38898     u32 iSectorSize;             /* Sector-size field of journal header */
38899 
38900     /* Read the page-size and sector-size journal header fields. */
38901     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
38902      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
38903     ){
38904       return rc;
38905     }
38906 
38907     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
38908     ** journal header to zero. In this case, assume that the Pager.pageSize
38909     ** variable is already set to the correct page size.
38910     */
38911     if( iPageSize==0 ){
38912       iPageSize = pPager->pageSize;
38913     }
38914 
38915     /* Check that the values read from the page-size and sector-size fields
38916     ** are within range. To be 'in range', both values need to be a power
38917     ** of two greater than or equal to 512 or 32, and not greater than their
38918     ** respective compile time maximum limits.
38919     */
38920     if( iPageSize<512                  || iSectorSize<32
38921      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
38922      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
38923     ){
38924       /* If the either the page-size or sector-size in the journal-header is
38925       ** invalid, then the process that wrote the journal-header must have
38926       ** crashed before the header was synced. In this case stop reading
38927       ** the journal file here.
38928       */
38929       return SQLITE_DONE;
38930     }
38931 
38932     /* Update the page-size to match the value read from the journal.
38933     ** Use a testcase() macro to make sure that malloc failure within
38934     ** PagerSetPagesize() is tested.
38935     */
38936     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
38937     testcase( rc!=SQLITE_OK );
38938 
38939     /* Update the assumed sector-size to match the value used by
38940     ** the process that created this journal. If this journal was
38941     ** created by a process other than this one, then this routine
38942     ** is being called from within pager_playback(). The local value
38943     ** of Pager.sectorSize is restored at the end of that routine.
38944     */
38945     pPager->sectorSize = iSectorSize;
38946   }
38947 
38948   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38949   return rc;
38950 }
38951 
38952 
38953 /*
38954 ** Write the supplied master journal name into the journal file for pager
38955 ** pPager at the current location. The master journal name must be the last
38956 ** thing written to a journal file. If the pager is in full-sync mode, the
38957 ** journal file descriptor is advanced to the next sector boundary before
38958 ** anything is written. The format is:
38959 **
38960 **   + 4 bytes: PAGER_MJ_PGNO.
38961 **   + N bytes: Master journal filename in utf-8.
38962 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38963 **   + 4 bytes: Master journal name checksum.
38964 **   + 8 bytes: aJournalMagic[].
38965 **
38966 ** The master journal page checksum is the sum of the bytes in the master
38967 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38968 **
38969 ** If zMaster is a NULL pointer (occurs for a single database transaction),
38970 ** this call is a no-op.
38971 */
38972 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38973   int rc;                          /* Return code */
38974   int nMaster;                     /* Length of string zMaster */
38975   i64 iHdrOff;                     /* Offset of header in journal file */
38976   i64 jrnlSize;                    /* Size of journal file on disk */
38977   u32 cksum = 0;                   /* Checksum of string zMaster */
38978 
38979   assert( pPager->setMaster==0 );
38980   assert( !pagerUseWal(pPager) );
38981 
38982   if( !zMaster
38983    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38984    || pPager->journalMode==PAGER_JOURNALMODE_OFF
38985   ){
38986     return SQLITE_OK;
38987   }
38988   pPager->setMaster = 1;
38989   assert( isOpen(pPager->jfd) );
38990   assert( pPager->journalHdr <= pPager->journalOff );
38991 
38992   /* Calculate the length in bytes and the checksum of zMaster */
38993   for(nMaster=0; zMaster[nMaster]; nMaster++){
38994     cksum += zMaster[nMaster];
38995   }
38996 
38997   /* If in full-sync mode, advance to the next disk sector before writing
38998   ** the master journal name. This is in case the previous page written to
38999   ** the journal has already been synced.
39000   */
39001   if( pPager->fullSync ){
39002     pPager->journalOff = journalHdrOffset(pPager);
39003   }
39004   iHdrOff = pPager->journalOff;
39005 
39006   /* Write the master journal data to the end of the journal file. If
39007   ** an error occurs, return the error code to the caller.
39008   */
39009   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
39010    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
39011    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
39012    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
39013    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
39014   ){
39015     return rc;
39016   }
39017   pPager->journalOff += (nMaster+20);
39018 
39019   /* If the pager is in peristent-journal mode, then the physical
39020   ** journal-file may extend past the end of the master-journal name
39021   ** and 8 bytes of magic data just written to the file. This is
39022   ** dangerous because the code to rollback a hot-journal file
39023   ** will not be able to find the master-journal name to determine
39024   ** whether or not the journal is hot.
39025   **
39026   ** Easiest thing to do in this scenario is to truncate the journal
39027   ** file to the required size.
39028   */
39029   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
39030    && jrnlSize>pPager->journalOff
39031   ){
39032     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
39033   }
39034   return rc;
39035 }
39036 
39037 /*
39038 ** Find a page in the hash table given its page number. Return
39039 ** a pointer to the page or NULL if the requested page is not
39040 ** already in memory.
39041 */
39042 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
39043   PgHdr *p;                         /* Return value */
39044 
39045   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
39046   ** fail, since no attempt to allocate dynamic memory will be made.
39047   */
39048   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
39049   return p;
39050 }
39051 
39052 /*
39053 ** Discard the entire contents of the in-memory page-cache.
39054 */
39055 static void pager_reset(Pager *pPager){
39056   sqlite3BackupRestart(pPager->pBackup);
39057   sqlite3PcacheClear(pPager->pPCache);
39058 }
39059 
39060 /*
39061 ** Free all structures in the Pager.aSavepoint[] array and set both
39062 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
39063 ** if it is open and the pager is not in exclusive mode.
39064 */
39065 static void releaseAllSavepoints(Pager *pPager){
39066   int ii;               /* Iterator for looping through Pager.aSavepoint */
39067   for(ii=0; ii<pPager->nSavepoint; ii++){
39068     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39069   }
39070   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
39071     sqlite3OsClose(pPager->sjfd);
39072   }
39073   sqlite3_free(pPager->aSavepoint);
39074   pPager->aSavepoint = 0;
39075   pPager->nSavepoint = 0;
39076   pPager->nSubRec = 0;
39077 }
39078 
39079 /*
39080 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
39081 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
39082 ** or SQLITE_NOMEM if a malloc failure occurs.
39083 */
39084 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
39085   int ii;                   /* Loop counter */
39086   int rc = SQLITE_OK;       /* Result code */
39087 
39088   for(ii=0; ii<pPager->nSavepoint; ii++){
39089     PagerSavepoint *p = &pPager->aSavepoint[ii];
39090     if( pgno<=p->nOrig ){
39091       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
39092       testcase( rc==SQLITE_NOMEM );
39093       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39094     }
39095   }
39096   return rc;
39097 }
39098 
39099 /*
39100 ** This function is a no-op if the pager is in exclusive mode and not
39101 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
39102 ** state.
39103 **
39104 ** If the pager is not in exclusive-access mode, the database file is
39105 ** completely unlocked. If the file is unlocked and the file-system does
39106 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
39107 ** closed (if it is open).
39108 **
39109 ** If the pager is in ERROR state when this function is called, the
39110 ** contents of the pager cache are discarded before switching back to
39111 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
39112 ** or not, any journal file left in the file-system will be treated
39113 ** as a hot-journal and rolled back the next time a read-transaction
39114 ** is opened (by this or by any other connection).
39115 */
39116 static void pager_unlock(Pager *pPager){
39117 
39118   assert( pPager->eState==PAGER_READER
39119        || pPager->eState==PAGER_OPEN
39120        || pPager->eState==PAGER_ERROR
39121   );
39122 
39123   sqlite3BitvecDestroy(pPager->pInJournal);
39124   pPager->pInJournal = 0;
39125   releaseAllSavepoints(pPager);
39126 
39127   if( pagerUseWal(pPager) ){
39128     assert( !isOpen(pPager->jfd) );
39129     sqlite3WalEndReadTransaction(pPager->pWal);
39130     pPager->eState = PAGER_OPEN;
39131   }else if( !pPager->exclusiveMode ){
39132     int rc;                       /* Error code returned by pagerUnlockDb() */
39133     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
39134 
39135     /* If the operating system support deletion of open files, then
39136     ** close the journal file when dropping the database lock.  Otherwise
39137     ** another connection with journal_mode=delete might delete the file
39138     ** out from under us.
39139     */
39140     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
39141     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
39142     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
39143     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
39144     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39145     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
39146     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
39147      || 1!=(pPager->journalMode & 5)
39148     ){
39149       sqlite3OsClose(pPager->jfd);
39150     }
39151 
39152     /* If the pager is in the ERROR state and the call to unlock the database
39153     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
39154     ** above the #define for UNKNOWN_LOCK for an explanation of why this
39155     ** is necessary.
39156     */
39157     rc = pagerUnlockDb(pPager, NO_LOCK);
39158     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
39159       pPager->eLock = UNKNOWN_LOCK;
39160     }
39161 
39162     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
39163     ** without clearing the error code. This is intentional - the error
39164     ** code is cleared and the cache reset in the block below.
39165     */
39166     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
39167     pPager->changeCountDone = 0;
39168     pPager->eState = PAGER_OPEN;
39169   }
39170 
39171   /* If Pager.errCode is set, the contents of the pager cache cannot be
39172   ** trusted. Now that there are no outstanding references to the pager,
39173   ** it can safely move back to PAGER_OPEN state. This happens in both
39174   ** normal and exclusive-locking mode.
39175   */
39176   if( pPager->errCode ){
39177     assert( !MEMDB );
39178     pager_reset(pPager);
39179     pPager->changeCountDone = pPager->tempFile;
39180     pPager->eState = PAGER_OPEN;
39181     pPager->errCode = SQLITE_OK;
39182   }
39183 
39184   pPager->journalOff = 0;
39185   pPager->journalHdr = 0;
39186   pPager->setMaster = 0;
39187 }
39188 
39189 /*
39190 ** This function is called whenever an IOERR or FULL error that requires
39191 ** the pager to transition into the ERROR state may ahve occurred.
39192 ** The first argument is a pointer to the pager structure, the second
39193 ** the error-code about to be returned by a pager API function. The
39194 ** value returned is a copy of the second argument to this function.
39195 **
39196 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
39197 ** IOERR sub-codes, the pager enters the ERROR state and the error code
39198 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
39199 ** all major API calls on the Pager will immediately return Pager.errCode.
39200 **
39201 ** The ERROR state indicates that the contents of the pager-cache
39202 ** cannot be trusted. This state can be cleared by completely discarding
39203 ** the contents of the pager-cache. If a transaction was active when
39204 ** the persistent error occurred, then the rollback journal may need
39205 ** to be replayed to restore the contents of the database file (as if
39206 ** it were a hot-journal).
39207 */
39208 static int pager_error(Pager *pPager, int rc){
39209   int rc2 = rc & 0xff;
39210   assert( rc==SQLITE_OK || !MEMDB );
39211   assert(
39212        pPager->errCode==SQLITE_FULL ||
39213        pPager->errCode==SQLITE_OK ||
39214        (pPager->errCode & 0xff)==SQLITE_IOERR
39215   );
39216   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
39217     pPager->errCode = rc;
39218     pPager->eState = PAGER_ERROR;
39219   }
39220   return rc;
39221 }
39222 
39223 static int pager_truncate(Pager *pPager, Pgno nPage);
39224 
39225 /*
39226 ** This routine ends a transaction. A transaction is usually ended by
39227 ** either a COMMIT or a ROLLBACK operation. This routine may be called
39228 ** after rollback of a hot-journal, or if an error occurs while opening
39229 ** the journal file or writing the very first journal-header of a
39230 ** database transaction.
39231 **
39232 ** This routine is never called in PAGER_ERROR state. If it is called
39233 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
39234 ** exclusive than a RESERVED lock, it is a no-op.
39235 **
39236 ** Otherwise, any active savepoints are released.
39237 **
39238 ** If the journal file is open, then it is "finalized". Once a journal
39239 ** file has been finalized it is not possible to use it to roll back a
39240 ** transaction. Nor will it be considered to be a hot-journal by this
39241 ** or any other database connection. Exactly how a journal is finalized
39242 ** depends on whether or not the pager is running in exclusive mode and
39243 ** the current journal-mode (Pager.journalMode value), as follows:
39244 **
39245 **   journalMode==MEMORY
39246 **     Journal file descriptor is simply closed. This destroys an
39247 **     in-memory journal.
39248 **
39249 **   journalMode==TRUNCATE
39250 **     Journal file is truncated to zero bytes in size.
39251 **
39252 **   journalMode==PERSIST
39253 **     The first 28 bytes of the journal file are zeroed. This invalidates
39254 **     the first journal header in the file, and hence the entire journal
39255 **     file. An invalid journal file cannot be rolled back.
39256 **
39257 **   journalMode==DELETE
39258 **     The journal file is closed and deleted using sqlite3OsDelete().
39259 **
39260 **     If the pager is running in exclusive mode, this method of finalizing
39261 **     the journal file is never used. Instead, if the journalMode is
39262 **     DELETE and the pager is in exclusive mode, the method described under
39263 **     journalMode==PERSIST is used instead.
39264 **
39265 ** After the journal is finalized, the pager moves to PAGER_READER state.
39266 ** If running in non-exclusive rollback mode, the lock on the file is
39267 ** downgraded to a SHARED_LOCK.
39268 **
39269 ** SQLITE_OK is returned if no error occurs. If an error occurs during
39270 ** any of the IO operations to finalize the journal file or unlock the
39271 ** database then the IO error code is returned to the user. If the
39272 ** operation to finalize the journal file fails, then the code still
39273 ** tries to unlock the database file if not in exclusive mode. If the
39274 ** unlock operation fails as well, then the first error code related
39275 ** to the first error encountered (the journal finalization one) is
39276 ** returned.
39277 */
39278 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
39279   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
39280   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
39281 
39282   /* Do nothing if the pager does not have an open write transaction
39283   ** or at least a RESERVED lock. This function may be called when there
39284   ** is no write-transaction active but a RESERVED or greater lock is
39285   ** held under two circumstances:
39286   **
39287   **   1. After a successful hot-journal rollback, it is called with
39288   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
39289   **
39290   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
39291   **      lock switches back to locking_mode=normal and then executes a
39292   **      read-transaction, this function is called with eState==PAGER_READER
39293   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
39294   */
39295   assert( assert_pager_state(pPager) );
39296   assert( pPager->eState!=PAGER_ERROR );
39297   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
39298     return SQLITE_OK;
39299   }
39300 
39301   releaseAllSavepoints(pPager);
39302   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
39303   if( isOpen(pPager->jfd) ){
39304     assert( !pagerUseWal(pPager) );
39305 
39306     /* Finalize the journal file. */
39307     if( sqlite3IsMemJournal(pPager->jfd) ){
39308       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
39309       sqlite3OsClose(pPager->jfd);
39310     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
39311       if( pPager->journalOff==0 ){
39312         rc = SQLITE_OK;
39313       }else{
39314         rc = sqlite3OsTruncate(pPager->jfd, 0);
39315       }
39316       pPager->journalOff = 0;
39317     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39318       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
39319     ){
39320       rc = zeroJournalHdr(pPager, hasMaster);
39321       pPager->journalOff = 0;
39322     }else{
39323       /* This branch may be executed with Pager.journalMode==MEMORY if
39324       ** a hot-journal was just rolled back. In this case the journal
39325       ** file should be closed and deleted. If this connection writes to
39326       ** the database file, it will do so using an in-memory journal.
39327       */
39328       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
39329       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
39330            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
39331            || pPager->journalMode==PAGER_JOURNALMODE_WAL
39332       );
39333       sqlite3OsClose(pPager->jfd);
39334       if( bDelete ){
39335         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39336       }
39337     }
39338   }
39339 
39340 #ifdef SQLITE_CHECK_PAGES
39341   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
39342   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
39343     PgHdr *p = pager_lookup(pPager, 1);
39344     if( p ){
39345       p->pageHash = 0;
39346       sqlite3PagerUnref(p);
39347     }
39348   }
39349 #endif
39350 
39351   sqlite3BitvecDestroy(pPager->pInJournal);
39352   pPager->pInJournal = 0;
39353   pPager->nRec = 0;
39354   sqlite3PcacheCleanAll(pPager->pPCache);
39355   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
39356 
39357   if( pagerUseWal(pPager) ){
39358     /* Drop the WAL write-lock, if any. Also, if the connection was in
39359     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
39360     ** lock held on the database file.
39361     */
39362     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
39363     assert( rc2==SQLITE_OK );
39364   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
39365     /* This branch is taken when committing a transaction in rollback-journal
39366     ** mode if the database file on disk is larger than the database image.
39367     ** At this point the journal has been finalized and the transaction
39368     ** successfully committed, but the EXCLUSIVE lock is still held on the
39369     ** file. So it is safe to truncate the database file to its minimum
39370     ** required size.  */
39371     assert( pPager->eLock==EXCLUSIVE_LOCK );
39372     rc = pager_truncate(pPager, pPager->dbSize);
39373   }
39374 
39375   if( !pPager->exclusiveMode
39376    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
39377   ){
39378     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
39379     pPager->changeCountDone = 0;
39380   }
39381   pPager->eState = PAGER_READER;
39382   pPager->setMaster = 0;
39383 
39384   return (rc==SQLITE_OK?rc2:rc);
39385 }
39386 
39387 /*
39388 ** Execute a rollback if a transaction is active and unlock the
39389 ** database file.
39390 **
39391 ** If the pager has already entered the ERROR state, do not attempt
39392 ** the rollback at this time. Instead, pager_unlock() is called. The
39393 ** call to pager_unlock() will discard all in-memory pages, unlock
39394 ** the database file and move the pager back to OPEN state. If this
39395 ** means that there is a hot-journal left in the file-system, the next
39396 ** connection to obtain a shared lock on the pager (which may be this one)
39397 ** will roll it back.
39398 **
39399 ** If the pager has not already entered the ERROR state, but an IO or
39400 ** malloc error occurs during a rollback, then this will itself cause
39401 ** the pager to enter the ERROR state. Which will be cleared by the
39402 ** call to pager_unlock(), as described above.
39403 */
39404 static void pagerUnlockAndRollback(Pager *pPager){
39405   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
39406     assert( assert_pager_state(pPager) );
39407     if( pPager->eState>=PAGER_WRITER_LOCKED ){
39408       sqlite3BeginBenignMalloc();
39409       sqlite3PagerRollback(pPager);
39410       sqlite3EndBenignMalloc();
39411     }else if( !pPager->exclusiveMode ){
39412       assert( pPager->eState==PAGER_READER );
39413       pager_end_transaction(pPager, 0, 0);
39414     }
39415   }
39416   pager_unlock(pPager);
39417 }
39418 
39419 /*
39420 ** Parameter aData must point to a buffer of pPager->pageSize bytes
39421 ** of data. Compute and return a checksum based ont the contents of the
39422 ** page of data and the current value of pPager->cksumInit.
39423 **
39424 ** This is not a real checksum. It is really just the sum of the
39425 ** random initial value (pPager->cksumInit) and every 200th byte
39426 ** of the page data, starting with byte offset (pPager->pageSize%200).
39427 ** Each byte is interpreted as an 8-bit unsigned integer.
39428 **
39429 ** Changing the formula used to compute this checksum results in an
39430 ** incompatible journal file format.
39431 **
39432 ** If journal corruption occurs due to a power failure, the most likely
39433 ** scenario is that one end or the other of the record will be changed.
39434 ** It is much less likely that the two ends of the journal record will be
39435 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
39436 ** though fast and simple, catches the mostly likely kind of corruption.
39437 */
39438 static u32 pager_cksum(Pager *pPager, const u8 *aData){
39439   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
39440   int i = pPager->pageSize-200;          /* Loop counter */
39441   while( i>0 ){
39442     cksum += aData[i];
39443     i -= 200;
39444   }
39445   return cksum;
39446 }
39447 
39448 /*
39449 ** Report the current page size and number of reserved bytes back
39450 ** to the codec.
39451 */
39452 #ifdef SQLITE_HAS_CODEC
39453 static void pagerReportSize(Pager *pPager){
39454   if( pPager->xCodecSizeChng ){
39455     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
39456                            (int)pPager->nReserve);
39457   }
39458 }
39459 #else
39460 # define pagerReportSize(X)     /* No-op if we do not support a codec */
39461 #endif
39462 
39463 /*
39464 ** Read a single page from either the journal file (if isMainJrnl==1) or
39465 ** from the sub-journal (if isMainJrnl==0) and playback that page.
39466 ** The page begins at offset *pOffset into the file. The *pOffset
39467 ** value is increased to the start of the next page in the journal.
39468 **
39469 ** The main rollback journal uses checksums - the statement journal does
39470 ** not.
39471 **
39472 ** If the page number of the page record read from the (sub-)journal file
39473 ** is greater than the current value of Pager.dbSize, then playback is
39474 ** skipped and SQLITE_OK is returned.
39475 **
39476 ** If pDone is not NULL, then it is a record of pages that have already
39477 ** been played back.  If the page at *pOffset has already been played back
39478 ** (if the corresponding pDone bit is set) then skip the playback.
39479 ** Make sure the pDone bit corresponding to the *pOffset page is set
39480 ** prior to returning.
39481 **
39482 ** If the page record is successfully read from the (sub-)journal file
39483 ** and played back, then SQLITE_OK is returned. If an IO error occurs
39484 ** while reading the record from the (sub-)journal file or while writing
39485 ** to the database file, then the IO error code is returned. If data
39486 ** is successfully read from the (sub-)journal file but appears to be
39487 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
39488 ** two circumstances:
39489 **
39490 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
39491 **   * If the record is being rolled back from the main journal file
39492 **     and the checksum field does not match the record content.
39493 **
39494 ** Neither of these two scenarios are possible during a savepoint rollback.
39495 **
39496 ** If this is a savepoint rollback, then memory may have to be dynamically
39497 ** allocated by this function. If this is the case and an allocation fails,
39498 ** SQLITE_NOMEM is returned.
39499 */
39500 static int pager_playback_one_page(
39501   Pager *pPager,                /* The pager being played back */
39502   i64 *pOffset,                 /* Offset of record to playback */
39503   Bitvec *pDone,                /* Bitvec of pages already played back */
39504   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
39505   int isSavepnt                 /* True for a savepoint rollback */
39506 ){
39507   int rc;
39508   PgHdr *pPg;                   /* An existing page in the cache */
39509   Pgno pgno;                    /* The page number of a page in journal */
39510   u32 cksum;                    /* Checksum used for sanity checking */
39511   char *aData;                  /* Temporary storage for the page */
39512   sqlite3_file *jfd;            /* The file descriptor for the journal file */
39513   int isSynced;                 /* True if journal page is synced */
39514 
39515   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
39516   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
39517   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
39518   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
39519 
39520   aData = pPager->pTmpSpace;
39521   assert( aData );         /* Temp storage must have already been allocated */
39522   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
39523 
39524   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
39525   ** or savepoint rollback done at the request of the caller) or this is
39526   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
39527   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
39528   ** only reads from the main journal, not the sub-journal.
39529   */
39530   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
39531        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
39532   );
39533   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
39534 
39535   /* Read the page number and page data from the journal or sub-journal
39536   ** file. Return an error code to the caller if an IO error occurs.
39537   */
39538   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
39539   rc = read32bits(jfd, *pOffset, &pgno);
39540   if( rc!=SQLITE_OK ) return rc;
39541   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
39542   if( rc!=SQLITE_OK ) return rc;
39543   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
39544 
39545   /* Sanity checking on the page.  This is more important that I originally
39546   ** thought.  If a power failure occurs while the journal is being written,
39547   ** it could cause invalid data to be written into the journal.  We need to
39548   ** detect this invalid data (with high probability) and ignore it.
39549   */
39550   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
39551     assert( !isSavepnt );
39552     return SQLITE_DONE;
39553   }
39554   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
39555     return SQLITE_OK;
39556   }
39557   if( isMainJrnl ){
39558     rc = read32bits(jfd, (*pOffset)-4, &cksum);
39559     if( rc ) return rc;
39560     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
39561       return SQLITE_DONE;
39562     }
39563   }
39564 
39565   /* If this page has already been played by before during the current
39566   ** rollback, then don't bother to play it back again.
39567   */
39568   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
39569     return rc;
39570   }
39571 
39572   /* When playing back page 1, restore the nReserve setting
39573   */
39574   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
39575     pPager->nReserve = ((u8*)aData)[20];
39576     pagerReportSize(pPager);
39577   }
39578 
39579   /* If the pager is in CACHEMOD state, then there must be a copy of this
39580   ** page in the pager cache. In this case just update the pager cache,
39581   ** not the database file. The page is left marked dirty in this case.
39582   **
39583   ** An exception to the above rule: If the database is in no-sync mode
39584   ** and a page is moved during an incremental vacuum then the page may
39585   ** not be in the pager cache. Later: if a malloc() or IO error occurs
39586   ** during a Movepage() call, then the page may not be in the cache
39587   ** either. So the condition described in the above paragraph is not
39588   ** assert()able.
39589   **
39590   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
39591   ** pager cache if it exists and the main file. The page is then marked
39592   ** not dirty. Since this code is only executed in PAGER_OPEN state for
39593   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
39594   ** if the pager is in OPEN state.
39595   **
39596   ** Ticket #1171:  The statement journal might contain page content that is
39597   ** different from the page content at the start of the transaction.
39598   ** This occurs when a page is changed prior to the start of a statement
39599   ** then changed again within the statement.  When rolling back such a
39600   ** statement we must not write to the original database unless we know
39601   ** for certain that original page contents are synced into the main rollback
39602   ** journal.  Otherwise, a power loss might leave modified data in the
39603   ** database file without an entry in the rollback journal that can
39604   ** restore the database to its original form.  Two conditions must be
39605   ** met before writing to the database files. (1) the database must be
39606   ** locked.  (2) we know that the original page content is fully synced
39607   ** in the main journal either because the page is not in cache or else
39608   ** the page is marked as needSync==0.
39609   **
39610   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
39611   ** is possible to fail a statement on a database that does not yet exist.
39612   ** Do not attempt to write if database file has never been opened.
39613   */
39614   if( pagerUseWal(pPager) ){
39615     pPg = 0;
39616   }else{
39617     pPg = pager_lookup(pPager, pgno);
39618   }
39619   assert( pPg || !MEMDB );
39620   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39621   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39622            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39623            (isMainJrnl?"main-journal":"sub-journal")
39624   ));
39625   if( isMainJrnl ){
39626     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39627   }else{
39628     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39629   }
39630   if( isOpen(pPager->fd)
39631    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39632    && isSynced
39633   ){
39634     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39635     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39636     assert( !pagerUseWal(pPager) );
39637     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39638     if( pgno>pPager->dbFileSize ){
39639       pPager->dbFileSize = pgno;
39640     }
39641     if( pPager->pBackup ){
39642       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39643       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39644       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39645     }
39646   }else if( !isMainJrnl && pPg==0 ){
39647     /* If this is a rollback of a savepoint and data was not written to
39648     ** the database and the page is not in-memory, there is a potential
39649     ** problem. When the page is next fetched by the b-tree layer, it
39650     ** will be read from the database file, which may or may not be
39651     ** current.
39652     **
39653     ** There are a couple of different ways this can happen. All are quite
39654     ** obscure. When running in synchronous mode, this can only happen
39655     ** if the page is on the free-list at the start of the transaction, then
39656     ** populated, then moved using sqlite3PagerMovepage().
39657     **
39658     ** The solution is to add an in-memory page to the cache containing
39659     ** the data just read from the sub-journal. Mark the page as dirty
39660     ** and if the pager requires a journal-sync, then mark the page as
39661     ** requiring a journal-sync before it is written.
39662     */
39663     assert( isSavepnt );
39664     assert( pPager->doNotSpill==0 );
39665     pPager->doNotSpill++;
39666     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39667     assert( pPager->doNotSpill==1 );
39668     pPager->doNotSpill--;
39669     if( rc!=SQLITE_OK ) return rc;
39670     pPg->flags &= ~PGHDR_NEED_READ;
39671     sqlite3PcacheMakeDirty(pPg);
39672   }
39673   if( pPg ){
39674     /* No page should ever be explicitly rolled back that is in use, except
39675     ** for page 1 which is held in use in order to keep the lock on the
39676     ** database active. However such a page may be rolled back as a result
39677     ** of an internal error resulting in an automatic call to
39678     ** sqlite3PagerRollback().
39679     */
39680     void *pData;
39681     pData = pPg->pData;
39682     memcpy(pData, (u8*)aData, pPager->pageSize);
39683     pPager->xReiniter(pPg);
39684     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39685       /* If the contents of this page were just restored from the main
39686       ** journal file, then its content must be as they were when the
39687       ** transaction was first opened. In this case we can mark the page
39688       ** as clean, since there will be no need to write it out to the
39689       ** database.
39690       **
39691       ** There is one exception to this rule. If the page is being rolled
39692       ** back as part of a savepoint (or statement) rollback from an
39693       ** unsynced portion of the main journal file, then it is not safe
39694       ** to mark the page as clean. This is because marking the page as
39695       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39696       ** already in the journal file (recorded in Pager.pInJournal) and
39697       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39698       ** again within this transaction, it will be marked as dirty but
39699       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39700       ** be written out into the database file before its journal file
39701       ** segment is synced. If a crash occurs during or following this,
39702       ** database corruption may ensue.
39703       */
39704       assert( !pagerUseWal(pPager) );
39705       sqlite3PcacheMakeClean(pPg);
39706     }
39707     pager_set_pagehash(pPg);
39708 
39709     /* If this was page 1, then restore the value of Pager.dbFileVers.
39710     ** Do this before any decoding. */
39711     if( pgno==1 ){
39712       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39713     }
39714 
39715     /* Decode the page just read from disk */
39716     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39717     sqlite3PcacheRelease(pPg);
39718   }
39719   return rc;
39720 }
39721 
39722 /*
39723 ** Parameter zMaster is the name of a master journal file. A single journal
39724 ** file that referred to the master journal file has just been rolled back.
39725 ** This routine checks if it is possible to delete the master journal file,
39726 ** and does so if it is.
39727 **
39728 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
39729 ** available for use within this function.
39730 **
39731 ** When a master journal file is created, it is populated with the names
39732 ** of all of its child journals, one after another, formatted as utf-8
39733 ** encoded text. The end of each child journal file is marked with a
39734 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39735 ** file for a transaction involving two databases might be:
39736 **
39737 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39738 **
39739 ** A master journal file may only be deleted once all of its child
39740 ** journals have been rolled back.
39741 **
39742 ** This function reads the contents of the master-journal file into
39743 ** memory and loops through each of the child journal names. For
39744 ** each child journal, it checks if:
39745 **
39746 **   * if the child journal exists, and if so
39747 **   * if the child journal contains a reference to master journal
39748 **     file zMaster
39749 **
39750 ** If a child journal can be found that matches both of the criteria
39751 ** above, this function returns without doing anything. Otherwise, if
39752 ** no such child journal can be found, file zMaster is deleted from
39753 ** the file-system using sqlite3OsDelete().
39754 **
39755 ** If an IO error within this function, an error code is returned. This
39756 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39757 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
39758 ** occur, SQLITE_OK is returned.
39759 **
39760 ** TODO: This function allocates a single block of memory to load
39761 ** the entire contents of the master journal file. This could be
39762 ** a couple of kilobytes or so - potentially larger than the page
39763 ** size.
39764 */
39765 static int pager_delmaster(Pager *pPager, const char *zMaster){
39766   sqlite3_vfs *pVfs = pPager->pVfs;
39767   int rc;                   /* Return code */
39768   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
39769   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
39770   char *zMasterJournal = 0; /* Contents of master journal file */
39771   i64 nMasterJournal;       /* Size of master journal file */
39772   char *zJournal;           /* Pointer to one journal within MJ file */
39773   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
39774   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
39775 
39776   /* Allocate space for both the pJournal and pMaster file descriptors.
39777   ** If successful, open the master journal file for reading.
39778   */
39779   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39780   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39781   if( !pMaster ){
39782     rc = SQLITE_NOMEM;
39783   }else{
39784     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39785     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39786   }
39787   if( rc!=SQLITE_OK ) goto delmaster_out;
39788 
39789   /* Load the entire master journal file into space obtained from
39790   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
39791   ** sufficient space (in zMasterPtr) to hold the names of master
39792   ** journal files extracted from regular rollback-journals.
39793   */
39794   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39795   if( rc!=SQLITE_OK ) goto delmaster_out;
39796   nMasterPtr = pVfs->mxPathname+1;
39797   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39798   if( !zMasterJournal ){
39799     rc = SQLITE_NOMEM;
39800     goto delmaster_out;
39801   }
39802   zMasterPtr = &zMasterJournal[nMasterJournal+1];
39803   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39804   if( rc!=SQLITE_OK ) goto delmaster_out;
39805   zMasterJournal[nMasterJournal] = 0;
39806 
39807   zJournal = zMasterJournal;
39808   while( (zJournal-zMasterJournal)<nMasterJournal ){
39809     int exists;
39810     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39811     if( rc!=SQLITE_OK ){
39812       goto delmaster_out;
39813     }
39814     if( exists ){
39815       /* One of the journals pointed to by the master journal exists.
39816       ** Open it and check if it points at the master journal. If
39817       ** so, return without deleting the master journal file.
39818       */
39819       int c;
39820       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39821       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39822       if( rc!=SQLITE_OK ){
39823         goto delmaster_out;
39824       }
39825 
39826       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39827       sqlite3OsClose(pJournal);
39828       if( rc!=SQLITE_OK ){
39829         goto delmaster_out;
39830       }
39831 
39832       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39833       if( c ){
39834         /* We have a match. Do not delete the master journal file. */
39835         goto delmaster_out;
39836       }
39837     }
39838     zJournal += (sqlite3Strlen30(zJournal)+1);
39839   }
39840 
39841   sqlite3OsClose(pMaster);
39842   rc = sqlite3OsDelete(pVfs, zMaster, 0);
39843 
39844 delmaster_out:
39845   sqlite3_free(zMasterJournal);
39846   if( pMaster ){
39847     sqlite3OsClose(pMaster);
39848     assert( !isOpen(pJournal) );
39849     sqlite3_free(pMaster);
39850   }
39851   return rc;
39852 }
39853 
39854 
39855 /*
39856 ** This function is used to change the actual size of the database
39857 ** file in the file-system. This only happens when committing a transaction,
39858 ** or rolling back a transaction (including rolling back a hot-journal).
39859 **
39860 ** If the main database file is not open, or the pager is not in either
39861 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
39862 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
39863 ** If the file on disk is currently larger than nPage pages, then use the VFS
39864 ** xTruncate() method to truncate it.
39865 **
39866 ** Or, it might might be the case that the file on disk is smaller than
39867 ** nPage pages. Some operating system implementations can get confused if
39868 ** you try to truncate a file to some size that is larger than it
39869 ** currently is, so detect this case and write a single zero byte to
39870 ** the end of the new file instead.
39871 **
39872 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
39873 ** the database file, return the error code to the caller.
39874 */
39875 static int pager_truncate(Pager *pPager, Pgno nPage){
39876   int rc = SQLITE_OK;
39877   assert( pPager->eState!=PAGER_ERROR );
39878   assert( pPager->eState!=PAGER_READER );
39879 
39880   if( isOpen(pPager->fd)
39881    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39882   ){
39883     i64 currentSize, newSize;
39884     int szPage = pPager->pageSize;
39885     assert( pPager->eLock==EXCLUSIVE_LOCK );
39886     /* TODO: Is it safe to use Pager.dbFileSize here? */
39887     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
39888     newSize = szPage*(i64)nPage;
39889     if( rc==SQLITE_OK && currentSize!=newSize ){
39890       if( currentSize>newSize ){
39891         rc = sqlite3OsTruncate(pPager->fd, newSize);
39892       }else if( (currentSize+szPage)<=newSize ){
39893         char *pTmp = pPager->pTmpSpace;
39894         memset(pTmp, 0, szPage);
39895         testcase( (newSize-szPage) == currentSize );
39896         testcase( (newSize-szPage) >  currentSize );
39897         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
39898       }
39899       if( rc==SQLITE_OK ){
39900         pPager->dbFileSize = nPage;
39901       }
39902     }
39903   }
39904   return rc;
39905 }
39906 
39907 /*
39908 ** Return a sanitized version of the sector-size of OS file pFile. The
39909 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
39910 */
39911 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
39912   int iRet = sqlite3OsSectorSize(pFile);
39913   if( iRet<32 ){
39914     iRet = 512;
39915   }else if( iRet>MAX_SECTOR_SIZE ){
39916     assert( MAX_SECTOR_SIZE>=512 );
39917     iRet = MAX_SECTOR_SIZE;
39918   }
39919   return iRet;
39920 }
39921 
39922 /*
39923 ** Set the value of the Pager.sectorSize variable for the given
39924 ** pager based on the value returned by the xSectorSize method
39925 ** of the open database file. The sector size will be used used
39926 ** to determine the size and alignment of journal header and
39927 ** master journal pointers within created journal files.
39928 **
39929 ** For temporary files the effective sector size is always 512 bytes.
39930 **
39931 ** Otherwise, for non-temporary files, the effective sector size is
39932 ** the value returned by the xSectorSize() method rounded up to 32 if
39933 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
39934 ** is greater than MAX_SECTOR_SIZE.
39935 **
39936 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
39937 ** the effective sector size to its minimum value (512).  The purpose of
39938 ** pPager->sectorSize is to define the "blast radius" of bytes that
39939 ** might change if a crash occurs while writing to a single byte in
39940 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
39941 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
39942 ** size.  For backwards compatibility of the rollback journal file format,
39943 ** we cannot reduce the effective sector size below 512.
39944 */
39945 static void setSectorSize(Pager *pPager){
39946   assert( isOpen(pPager->fd) || pPager->tempFile );
39947 
39948   if( pPager->tempFile
39949    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
39950               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
39951   ){
39952     /* Sector size doesn't matter for temporary files. Also, the file
39953     ** may not have been opened yet, in which case the OsSectorSize()
39954     ** call will segfault. */
39955     pPager->sectorSize = 512;
39956   }else{
39957     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
39958   }
39959 }
39960 
39961 /*
39962 ** Playback the journal and thus restore the database file to
39963 ** the state it was in before we started making changes.
39964 **
39965 ** The journal file format is as follows:
39966 **
39967 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
39968 **  (2)  4 byte big-endian integer which is the number of valid page records
39969 **       in the journal.  If this value is 0xffffffff, then compute the
39970 **       number of page records from the journal size.
39971 **  (3)  4 byte big-endian integer which is the initial value for the
39972 **       sanity checksum.
39973 **  (4)  4 byte integer which is the number of pages to truncate the
39974 **       database to during a rollback.
39975 **  (5)  4 byte big-endian integer which is the sector size.  The header
39976 **       is this many bytes in size.
39977 **  (6)  4 byte big-endian integer which is the page size.
39978 **  (7)  zero padding out to the next sector size.
39979 **  (8)  Zero or more pages instances, each as follows:
39980 **        +  4 byte page number.
39981 **        +  pPager->pageSize bytes of data.
39982 **        +  4 byte checksum
39983 **
39984 ** When we speak of the journal header, we mean the first 7 items above.
39985 ** Each entry in the journal is an instance of the 8th item.
39986 **
39987 ** Call the value from the second bullet "nRec".  nRec is the number of
39988 ** valid page entries in the journal.  In most cases, you can compute the
39989 ** value of nRec from the size of the journal file.  But if a power
39990 ** failure occurred while the journal was being written, it could be the
39991 ** case that the size of the journal file had already been increased but
39992 ** the extra entries had not yet made it safely to disk.  In such a case,
39993 ** the value of nRec computed from the file size would be too large.  For
39994 ** that reason, we always use the nRec value in the header.
39995 **
39996 ** If the nRec value is 0xffffffff it means that nRec should be computed
39997 ** from the file size.  This value is used when the user selects the
39998 ** no-sync option for the journal.  A power failure could lead to corruption
39999 ** in this case.  But for things like temporary table (which will be
40000 ** deleted when the power is restored) we don't care.
40001 **
40002 ** If the file opened as the journal file is not a well-formed
40003 ** journal file then all pages up to the first corrupted page are rolled
40004 ** back (or no pages if the journal header is corrupted). The journal file
40005 ** is then deleted and SQLITE_OK returned, just as if no corruption had
40006 ** been encountered.
40007 **
40008 ** If an I/O or malloc() error occurs, the journal-file is not deleted
40009 ** and an error code is returned.
40010 **
40011 ** The isHot parameter indicates that we are trying to rollback a journal
40012 ** that might be a hot journal.  Or, it could be that the journal is
40013 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
40014 ** If the journal really is hot, reset the pager cache prior rolling
40015 ** back any content.  If the journal is merely persistent, no reset is
40016 ** needed.
40017 */
40018 static int pager_playback(Pager *pPager, int isHot){
40019   sqlite3_vfs *pVfs = pPager->pVfs;
40020   i64 szJ;                 /* Size of the journal file in bytes */
40021   u32 nRec;                /* Number of Records in the journal */
40022   u32 u;                   /* Unsigned loop counter */
40023   Pgno mxPg = 0;           /* Size of the original file in pages */
40024   int rc;                  /* Result code of a subroutine */
40025   int res = 1;             /* Value returned by sqlite3OsAccess() */
40026   char *zMaster = 0;       /* Name of master journal file if any */
40027   int needPagerReset;      /* True to reset page prior to first page rollback */
40028 
40029   /* Figure out how many records are in the journal.  Abort early if
40030   ** the journal is empty.
40031   */
40032   assert( isOpen(pPager->jfd) );
40033   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
40034   if( rc!=SQLITE_OK ){
40035     goto end_playback;
40036   }
40037 
40038   /* Read the master journal name from the journal, if it is present.
40039   ** If a master journal file name is specified, but the file is not
40040   ** present on disk, then the journal is not hot and does not need to be
40041   ** played back.
40042   **
40043   ** TODO: Technically the following is an error because it assumes that
40044   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
40045   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
40046   **  mxPathname is 512, which is the same as the minimum allowable value
40047   ** for pageSize.
40048   */
40049   zMaster = pPager->pTmpSpace;
40050   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40051   if( rc==SQLITE_OK && zMaster[0] ){
40052     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
40053   }
40054   zMaster = 0;
40055   if( rc!=SQLITE_OK || !res ){
40056     goto end_playback;
40057   }
40058   pPager->journalOff = 0;
40059   needPagerReset = isHot;
40060 
40061   /* This loop terminates either when a readJournalHdr() or
40062   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
40063   ** occurs.
40064   */
40065   while( 1 ){
40066     /* Read the next journal header from the journal file.  If there are
40067     ** not enough bytes left in the journal file for a complete header, or
40068     ** it is corrupted, then a process must have failed while writing it.
40069     ** This indicates nothing more needs to be rolled back.
40070     */
40071     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
40072     if( rc!=SQLITE_OK ){
40073       if( rc==SQLITE_DONE ){
40074         rc = SQLITE_OK;
40075       }
40076       goto end_playback;
40077     }
40078 
40079     /* If nRec is 0xffffffff, then this journal was created by a process
40080     ** working in no-sync mode. This means that the rest of the journal
40081     ** file consists of pages, there are no more journal headers. Compute
40082     ** the value of nRec based on this assumption.
40083     */
40084     if( nRec==0xffffffff ){
40085       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
40086       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
40087     }
40088 
40089     /* If nRec is 0 and this rollback is of a transaction created by this
40090     ** process and if this is the final header in the journal, then it means
40091     ** that this part of the journal was being filled but has not yet been
40092     ** synced to disk.  Compute the number of pages based on the remaining
40093     ** size of the file.
40094     **
40095     ** The third term of the test was added to fix ticket #2565.
40096     ** When rolling back a hot journal, nRec==0 always means that the next
40097     ** chunk of the journal contains zero pages to be rolled back.  But
40098     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
40099     ** the journal, it means that the journal might contain additional
40100     ** pages that need to be rolled back and that the number of pages
40101     ** should be computed based on the journal file size.
40102     */
40103     if( nRec==0 && !isHot &&
40104         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
40105       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
40106     }
40107 
40108     /* If this is the first header read from the journal, truncate the
40109     ** database file back to its original size.
40110     */
40111     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
40112       rc = pager_truncate(pPager, mxPg);
40113       if( rc!=SQLITE_OK ){
40114         goto end_playback;
40115       }
40116       pPager->dbSize = mxPg;
40117     }
40118 
40119     /* Copy original pages out of the journal and back into the
40120     ** database file and/or page cache.
40121     */
40122     for(u=0; u<nRec; u++){
40123       if( needPagerReset ){
40124         pager_reset(pPager);
40125         needPagerReset = 0;
40126       }
40127       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
40128       if( rc!=SQLITE_OK ){
40129         if( rc==SQLITE_DONE ){
40130           pPager->journalOff = szJ;
40131           break;
40132         }else if( rc==SQLITE_IOERR_SHORT_READ ){
40133           /* If the journal has been truncated, simply stop reading and
40134           ** processing the journal. This might happen if the journal was
40135           ** not completely written and synced prior to a crash.  In that
40136           ** case, the database should have never been written in the
40137           ** first place so it is OK to simply abandon the rollback. */
40138           rc = SQLITE_OK;
40139           goto end_playback;
40140         }else{
40141           /* If we are unable to rollback, quit and return the error
40142           ** code.  This will cause the pager to enter the error state
40143           ** so that no further harm will be done.  Perhaps the next
40144           ** process to come along will be able to rollback the database.
40145           */
40146           goto end_playback;
40147         }
40148       }
40149     }
40150   }
40151   /*NOTREACHED*/
40152   assert( 0 );
40153 
40154 end_playback:
40155   /* Following a rollback, the database file should be back in its original
40156   ** state prior to the start of the transaction, so invoke the
40157   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
40158   ** assertion that the transaction counter was modified.
40159   */
40160 #ifdef SQLITE_DEBUG
40161   if( pPager->fd->pMethods ){
40162     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
40163   }
40164 #endif
40165 
40166   /* If this playback is happening automatically as a result of an IO or
40167   ** malloc error that occurred after the change-counter was updated but
40168   ** before the transaction was committed, then the change-counter
40169   ** modification may just have been reverted. If this happens in exclusive
40170   ** mode, then subsequent transactions performed by the connection will not
40171   ** update the change-counter at all. This may lead to cache inconsistency
40172   ** problems for other processes at some point in the future. So, just
40173   ** in case this has happened, clear the changeCountDone flag now.
40174   */
40175   pPager->changeCountDone = pPager->tempFile;
40176 
40177   if( rc==SQLITE_OK ){
40178     zMaster = pPager->pTmpSpace;
40179     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40180     testcase( rc!=SQLITE_OK );
40181   }
40182   if( rc==SQLITE_OK
40183    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40184   ){
40185     rc = sqlite3PagerSync(pPager);
40186   }
40187   if( rc==SQLITE_OK ){
40188     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
40189     testcase( rc!=SQLITE_OK );
40190   }
40191   if( rc==SQLITE_OK && zMaster[0] && res ){
40192     /* If there was a master journal and this routine will return success,
40193     ** see if it is possible to delete the master journal.
40194     */
40195     rc = pager_delmaster(pPager, zMaster);
40196     testcase( rc!=SQLITE_OK );
40197   }
40198 
40199   /* The Pager.sectorSize variable may have been updated while rolling
40200   ** back a journal created by a process with a different sector size
40201   ** value. Reset it to the correct value for this process.
40202   */
40203   setSectorSize(pPager);
40204   return rc;
40205 }
40206 
40207 
40208 /*
40209 ** Read the content for page pPg out of the database file and into
40210 ** pPg->pData. A shared lock or greater must be held on the database
40211 ** file before this function is called.
40212 **
40213 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
40214 ** the value read from the database file.
40215 **
40216 ** If an IO error occurs, then the IO error is returned to the caller.
40217 ** Otherwise, SQLITE_OK is returned.
40218 */
40219 static int readDbPage(PgHdr *pPg){
40220   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
40221   Pgno pgno = pPg->pgno;       /* Page number to read */
40222   int rc = SQLITE_OK;          /* Return code */
40223   int isInWal = 0;             /* True if page is in log file */
40224   int pgsz = pPager->pageSize; /* Number of bytes to read */
40225 
40226   assert( pPager->eState>=PAGER_READER && !MEMDB );
40227   assert( isOpen(pPager->fd) );
40228 
40229   if( NEVER(!isOpen(pPager->fd)) ){
40230     assert( pPager->tempFile );
40231     memset(pPg->pData, 0, pPager->pageSize);
40232     return SQLITE_OK;
40233   }
40234 
40235   if( pagerUseWal(pPager) ){
40236     /* Try to pull the page from the write-ahead log. */
40237     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
40238   }
40239   if( rc==SQLITE_OK && !isInWal ){
40240     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
40241     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
40242     if( rc==SQLITE_IOERR_SHORT_READ ){
40243       rc = SQLITE_OK;
40244     }
40245   }
40246 
40247   if( pgno==1 ){
40248     if( rc ){
40249       /* If the read is unsuccessful, set the dbFileVers[] to something
40250       ** that will never be a valid file version.  dbFileVers[] is a copy
40251       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
40252       ** zero or the size of the database in page. Bytes 32..35 and 35..39
40253       ** should be page numbers which are never 0xffffffff.  So filling
40254       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
40255       **
40256       ** For an encrypted database, the situation is more complex:  bytes
40257       ** 24..39 of the database are white noise.  But the probability of
40258       ** white noising equaling 16 bytes of 0xff is vanishingly small so
40259       ** we should still be ok.
40260       */
40261       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
40262     }else{
40263       u8 *dbFileVers = &((u8*)pPg->pData)[24];
40264       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
40265     }
40266   }
40267   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
40268 
40269   PAGER_INCR(sqlite3_pager_readdb_count);
40270   PAGER_INCR(pPager->nRead);
40271   IOTRACE(("PGIN %p %d\n", pPager, pgno));
40272   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
40273                PAGERID(pPager), pgno, pager_pagehash(pPg)));
40274 
40275   return rc;
40276 }
40277 
40278 /*
40279 ** Update the value of the change-counter at offsets 24 and 92 in
40280 ** the header and the sqlite version number at offset 96.
40281 **
40282 ** This is an unconditional update.  See also the pager_incr_changecounter()
40283 ** routine which only updates the change-counter if the update is actually
40284 ** needed, as determined by the pPager->changeCountDone state variable.
40285 */
40286 static void pager_write_changecounter(PgHdr *pPg){
40287   u32 change_counter;
40288 
40289   /* Increment the value just read and write it back to byte 24. */
40290   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
40291   put32bits(((char*)pPg->pData)+24, change_counter);
40292 
40293   /* Also store the SQLite version number in bytes 96..99 and in
40294   ** bytes 92..95 store the change counter for which the version number
40295   ** is valid. */
40296   put32bits(((char*)pPg->pData)+92, change_counter);
40297   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
40298 }
40299 
40300 #ifndef SQLITE_OMIT_WAL
40301 /*
40302 ** This function is invoked once for each page that has already been
40303 ** written into the log file when a WAL transaction is rolled back.
40304 ** Parameter iPg is the page number of said page. The pCtx argument
40305 ** is actually a pointer to the Pager structure.
40306 **
40307 ** If page iPg is present in the cache, and has no outstanding references,
40308 ** it is discarded. Otherwise, if there are one or more outstanding
40309 ** references, the page content is reloaded from the database. If the
40310 ** attempt to reload content from the database is required and fails,
40311 ** return an SQLite error code. Otherwise, SQLITE_OK.
40312 */
40313 static int pagerUndoCallback(void *pCtx, Pgno iPg){
40314   int rc = SQLITE_OK;
40315   Pager *pPager = (Pager *)pCtx;
40316   PgHdr *pPg;
40317 
40318   pPg = sqlite3PagerLookup(pPager, iPg);
40319   if( pPg ){
40320     if( sqlite3PcachePageRefcount(pPg)==1 ){
40321       sqlite3PcacheDrop(pPg);
40322     }else{
40323       rc = readDbPage(pPg);
40324       if( rc==SQLITE_OK ){
40325         pPager->xReiniter(pPg);
40326       }
40327       sqlite3PagerUnref(pPg);
40328     }
40329   }
40330 
40331   /* Normally, if a transaction is rolled back, any backup processes are
40332   ** updated as data is copied out of the rollback journal and into the
40333   ** database. This is not generally possible with a WAL database, as
40334   ** rollback involves simply truncating the log file. Therefore, if one
40335   ** or more frames have already been written to the log (and therefore
40336   ** also copied into the backup databases) as part of this transaction,
40337   ** the backups must be restarted.
40338   */
40339   sqlite3BackupRestart(pPager->pBackup);
40340 
40341   return rc;
40342 }
40343 
40344 /*
40345 ** This function is called to rollback a transaction on a WAL database.
40346 */
40347 static int pagerRollbackWal(Pager *pPager){
40348   int rc;                         /* Return Code */
40349   PgHdr *pList;                   /* List of dirty pages to revert */
40350 
40351   /* For all pages in the cache that are currently dirty or have already
40352   ** been written (but not committed) to the log file, do one of the
40353   ** following:
40354   **
40355   **   + Discard the cached page (if refcount==0), or
40356   **   + Reload page content from the database (if refcount>0).
40357   */
40358   pPager->dbSize = pPager->dbOrigSize;
40359   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
40360   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40361   while( pList && rc==SQLITE_OK ){
40362     PgHdr *pNext = pList->pDirty;
40363     rc = pagerUndoCallback((void *)pPager, pList->pgno);
40364     pList = pNext;
40365   }
40366 
40367   return rc;
40368 }
40369 
40370 /*
40371 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
40372 ** the contents of the list of pages headed by pList (connected by pDirty),
40373 ** this function notifies any active backup processes that the pages have
40374 ** changed.
40375 **
40376 ** The list of pages passed into this routine is always sorted by page number.
40377 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
40378 */
40379 static int pagerWalFrames(
40380   Pager *pPager,                  /* Pager object */
40381   PgHdr *pList,                   /* List of frames to log */
40382   Pgno nTruncate,                 /* Database size after this commit */
40383   int isCommit                    /* True if this is a commit */
40384 ){
40385   int rc;                         /* Return code */
40386   int nList;                      /* Number of pages in pList */
40387 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
40388   PgHdr *p;                       /* For looping over pages */
40389 #endif
40390 
40391   assert( pPager->pWal );
40392   assert( pList );
40393 #ifdef SQLITE_DEBUG
40394   /* Verify that the page list is in accending order */
40395   for(p=pList; p && p->pDirty; p=p->pDirty){
40396     assert( p->pgno < p->pDirty->pgno );
40397   }
40398 #endif
40399 
40400   assert( pList->pDirty==0 || isCommit );
40401   if( isCommit ){
40402     /* If a WAL transaction is being committed, there is no point in writing
40403     ** any pages with page numbers greater than nTruncate into the WAL file.
40404     ** They will never be read by any client. So remove them from the pDirty
40405     ** list here. */
40406     PgHdr *p;
40407     PgHdr **ppNext = &pList;
40408     nList = 0;
40409     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
40410       if( p->pgno<=nTruncate ){
40411         ppNext = &p->pDirty;
40412         nList++;
40413       }
40414     }
40415     assert( pList );
40416   }else{
40417     nList = 1;
40418   }
40419   pPager->aStat[PAGER_STAT_WRITE] += nList;
40420 
40421   if( pList->pgno==1 ) pager_write_changecounter(pList);
40422   rc = sqlite3WalFrames(pPager->pWal,
40423       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
40424   );
40425   if( rc==SQLITE_OK && pPager->pBackup ){
40426     PgHdr *p;
40427     for(p=pList; p; p=p->pDirty){
40428       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
40429     }
40430   }
40431 
40432 #ifdef SQLITE_CHECK_PAGES
40433   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40434   for(p=pList; p; p=p->pDirty){
40435     pager_set_pagehash(p);
40436   }
40437 #endif
40438 
40439   return rc;
40440 }
40441 
40442 /*
40443 ** Begin a read transaction on the WAL.
40444 **
40445 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
40446 ** makes a snapshot of the database at the current point in time and preserves
40447 ** that snapshot for use by the reader in spite of concurrently changes by
40448 ** other writers or checkpointers.
40449 */
40450 static int pagerBeginReadTransaction(Pager *pPager){
40451   int rc;                         /* Return code */
40452   int changed = 0;                /* True if cache must be reset */
40453 
40454   assert( pagerUseWal(pPager) );
40455   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
40456 
40457   /* sqlite3WalEndReadTransaction() was not called for the previous
40458   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
40459   ** are in locking_mode=NORMAL and EndRead() was previously called,
40460   ** the duplicate call is harmless.
40461   */
40462   sqlite3WalEndReadTransaction(pPager->pWal);
40463 
40464   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
40465   if( rc!=SQLITE_OK || changed ){
40466     pager_reset(pPager);
40467   }
40468 
40469   return rc;
40470 }
40471 #endif
40472 
40473 /*
40474 ** This function is called as part of the transition from PAGER_OPEN
40475 ** to PAGER_READER state to determine the size of the database file
40476 ** in pages (assuming the page size currently stored in Pager.pageSize).
40477 **
40478 ** If no error occurs, SQLITE_OK is returned and the size of the database
40479 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
40480 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
40481 */
40482 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
40483   Pgno nPage;                     /* Value to return via *pnPage */
40484 
40485   /* Query the WAL sub-system for the database size. The WalDbsize()
40486   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
40487   ** if the database size is not available. The database size is not
40488   ** available from the WAL sub-system if the log file is empty or
40489   ** contains no valid committed transactions.
40490   */
40491   assert( pPager->eState==PAGER_OPEN );
40492   assert( pPager->eLock>=SHARED_LOCK );
40493   nPage = sqlite3WalDbsize(pPager->pWal);
40494 
40495   /* If the database size was not available from the WAL sub-system,
40496   ** determine it based on the size of the database file. If the size
40497   ** of the database file is not an integer multiple of the page-size,
40498   ** round down to the nearest page. Except, any file larger than 0
40499   ** bytes in size is considered to contain at least one page.
40500   */
40501   if( nPage==0 ){
40502     i64 n = 0;                    /* Size of db file in bytes */
40503     assert( isOpen(pPager->fd) || pPager->tempFile );
40504     if( isOpen(pPager->fd) ){
40505       int rc = sqlite3OsFileSize(pPager->fd, &n);
40506       if( rc!=SQLITE_OK ){
40507         return rc;
40508       }
40509     }
40510     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
40511   }
40512 
40513   /* If the current number of pages in the file is greater than the
40514   ** configured maximum pager number, increase the allowed limit so
40515   ** that the file can be read.
40516   */
40517   if( nPage>pPager->mxPgno ){
40518     pPager->mxPgno = (Pgno)nPage;
40519   }
40520 
40521   *pnPage = nPage;
40522   return SQLITE_OK;
40523 }
40524 
40525 #ifndef SQLITE_OMIT_WAL
40526 /*
40527 ** Check if the *-wal file that corresponds to the database opened by pPager
40528 ** exists if the database is not empy, or verify that the *-wal file does
40529 ** not exist (by deleting it) if the database file is empty.
40530 **
40531 ** If the database is not empty and the *-wal file exists, open the pager
40532 ** in WAL mode.  If the database is empty or if no *-wal file exists and
40533 ** if no error occurs, make sure Pager.journalMode is not set to
40534 ** PAGER_JOURNALMODE_WAL.
40535 **
40536 ** Return SQLITE_OK or an error code.
40537 **
40538 ** The caller must hold a SHARED lock on the database file to call this
40539 ** function. Because an EXCLUSIVE lock on the db file is required to delete
40540 ** a WAL on a none-empty database, this ensures there is no race condition
40541 ** between the xAccess() below and an xDelete() being executed by some
40542 ** other connection.
40543 */
40544 static int pagerOpenWalIfPresent(Pager *pPager){
40545   int rc = SQLITE_OK;
40546   assert( pPager->eState==PAGER_OPEN );
40547   assert( pPager->eLock>=SHARED_LOCK );
40548 
40549   if( !pPager->tempFile ){
40550     int isWal;                    /* True if WAL file exists */
40551     Pgno nPage;                   /* Size of the database file */
40552 
40553     rc = pagerPagecount(pPager, &nPage);
40554     if( rc ) return rc;
40555     if( nPage==0 ){
40556       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
40557       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
40558       isWal = 0;
40559     }else{
40560       rc = sqlite3OsAccess(
40561           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
40562       );
40563     }
40564     if( rc==SQLITE_OK ){
40565       if( isWal ){
40566         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
40567         rc = sqlite3PagerOpenWal(pPager, 0);
40568       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
40569         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
40570       }
40571     }
40572   }
40573   return rc;
40574 }
40575 #endif
40576 
40577 /*
40578 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
40579 ** the entire master journal file. The case pSavepoint==NULL occurs when
40580 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
40581 ** savepoint.
40582 **
40583 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
40584 ** being rolled back), then the rollback consists of up to three stages,
40585 ** performed in the order specified:
40586 **
40587 **   * Pages are played back from the main journal starting at byte
40588 **     offset PagerSavepoint.iOffset and continuing to
40589 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
40590 **     file if PagerSavepoint.iHdrOffset is zero.
40591 **
40592 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
40593 **     back starting from the journal header immediately following
40594 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
40595 **
40596 **   * Pages are then played back from the sub-journal file, starting
40597 **     with the PagerSavepoint.iSubRec and continuing to the end of
40598 **     the journal file.
40599 **
40600 ** Throughout the rollback process, each time a page is rolled back, the
40601 ** corresponding bit is set in a bitvec structure (variable pDone in the
40602 ** implementation below). This is used to ensure that a page is only
40603 ** rolled back the first time it is encountered in either journal.
40604 **
40605 ** If pSavepoint is NULL, then pages are only played back from the main
40606 ** journal file. There is no need for a bitvec in this case.
40607 **
40608 ** In either case, before playback commences the Pager.dbSize variable
40609 ** is reset to the value that it held at the start of the savepoint
40610 ** (or transaction). No page with a page-number greater than this value
40611 ** is played back. If one is encountered it is simply skipped.
40612 */
40613 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
40614   i64 szJ;                 /* Effective size of the main journal */
40615   i64 iHdrOff;             /* End of first segment of main-journal records */
40616   int rc = SQLITE_OK;      /* Return code */
40617   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
40618 
40619   assert( pPager->eState!=PAGER_ERROR );
40620   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40621 
40622   /* Allocate a bitvec to use to store the set of pages rolled back */
40623   if( pSavepoint ){
40624     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
40625     if( !pDone ){
40626       return SQLITE_NOMEM;
40627     }
40628   }
40629 
40630   /* Set the database size back to the value it was before the savepoint
40631   ** being reverted was opened.
40632   */
40633   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
40634   pPager->changeCountDone = pPager->tempFile;
40635 
40636   if( !pSavepoint && pagerUseWal(pPager) ){
40637     return pagerRollbackWal(pPager);
40638   }
40639 
40640   /* Use pPager->journalOff as the effective size of the main rollback
40641   ** journal.  The actual file might be larger than this in
40642   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
40643   ** past pPager->journalOff is off-limits to us.
40644   */
40645   szJ = pPager->journalOff;
40646   assert( pagerUseWal(pPager)==0 || szJ==0 );
40647 
40648   /* Begin by rolling back records from the main journal starting at
40649   ** PagerSavepoint.iOffset and continuing to the next journal header.
40650   ** There might be records in the main journal that have a page number
40651   ** greater than the current database size (pPager->dbSize) but those
40652   ** will be skipped automatically.  Pages are added to pDone as they
40653   ** are played back.
40654   */
40655   if( pSavepoint && !pagerUseWal(pPager) ){
40656     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40657     pPager->journalOff = pSavepoint->iOffset;
40658     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40659       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40660     }
40661     assert( rc!=SQLITE_DONE );
40662   }else{
40663     pPager->journalOff = 0;
40664   }
40665 
40666   /* Continue rolling back records out of the main journal starting at
40667   ** the first journal header seen and continuing until the effective end
40668   ** of the main journal file.  Continue to skip out-of-range pages and
40669   ** continue adding pages rolled back to pDone.
40670   */
40671   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40672     u32 ii;            /* Loop counter */
40673     u32 nJRec = 0;     /* Number of Journal Records */
40674     u32 dummy;
40675     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40676     assert( rc!=SQLITE_DONE );
40677 
40678     /*
40679     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40680     ** test is related to ticket #2565.  See the discussion in the
40681     ** pager_playback() function for additional information.
40682     */
40683     if( nJRec==0
40684      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40685     ){
40686       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40687     }
40688     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40689       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40690     }
40691     assert( rc!=SQLITE_DONE );
40692   }
40693   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40694 
40695   /* Finally,  rollback pages from the sub-journal.  Page that were
40696   ** previously rolled back out of the main journal (and are hence in pDone)
40697   ** will be skipped.  Out-of-range pages are also skipped.
40698   */
40699   if( pSavepoint ){
40700     u32 ii;            /* Loop counter */
40701     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
40702 
40703     if( pagerUseWal(pPager) ){
40704       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40705     }
40706     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40707       assert( offset==(i64)ii*(4+pPager->pageSize) );
40708       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40709     }
40710     assert( rc!=SQLITE_DONE );
40711   }
40712 
40713   sqlite3BitvecDestroy(pDone);
40714   if( rc==SQLITE_OK ){
40715     pPager->journalOff = szJ;
40716   }
40717 
40718   return rc;
40719 }
40720 
40721 /*
40722 ** Change the maximum number of in-memory pages that are allowed.
40723 */
40724 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40725   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40726 }
40727 
40728 /*
40729 ** Free as much memory as possible from the pager.
40730 */
40731 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
40732   sqlite3PcacheShrink(pPager->pPCache);
40733 }
40734 
40735 /*
40736 ** Adjust the robustness of the database to damage due to OS crashes
40737 ** or power failures by changing the number of syncs()s when writing
40738 ** the rollback journal.  There are three levels:
40739 **
40740 **    OFF       sqlite3OsSync() is never called.  This is the default
40741 **              for temporary and transient files.
40742 **
40743 **    NORMAL    The journal is synced once before writes begin on the
40744 **              database.  This is normally adequate protection, but
40745 **              it is theoretically possible, though very unlikely,
40746 **              that an inopertune power failure could leave the journal
40747 **              in a state which would cause damage to the database
40748 **              when it is rolled back.
40749 **
40750 **    FULL      The journal is synced twice before writes begin on the
40751 **              database (with some additional information - the nRec field
40752 **              of the journal header - being written in between the two
40753 **              syncs).  If we assume that writing a
40754 **              single disk sector is atomic, then this mode provides
40755 **              assurance that the journal will not be corrupted to the
40756 **              point of causing damage to the database during rollback.
40757 **
40758 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
40759 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
40760 ** prior to the start of checkpoint and that the database file is synced
40761 ** at the conclusion of the checkpoint if the entire content of the WAL
40762 ** was written back into the database.  But no sync operations occur for
40763 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
40764 ** file is synced following each commit operation, in addition to the
40765 ** syncs associated with NORMAL.
40766 **
40767 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
40768 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40769 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
40770 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
40771 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
40772 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40773 ** the xSync primitive is called and is relevant to all platforms.
40774 **
40775 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40776 ** and FULL=3.
40777 */
40778 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40779 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40780   Pager *pPager,        /* The pager to set safety level for */
40781   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
40782   int bFullFsync,       /* PRAGMA fullfsync */
40783   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
40784 ){
40785   assert( level>=1 && level<=3 );
40786   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
40787   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40788   if( pPager->noSync ){
40789     pPager->syncFlags = 0;
40790     pPager->ckptSyncFlags = 0;
40791   }else if( bFullFsync ){
40792     pPager->syncFlags = SQLITE_SYNC_FULL;
40793     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40794   }else if( bCkptFullFsync ){
40795     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40796     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40797   }else{
40798     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40799     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40800   }
40801   pPager->walSyncFlags = pPager->syncFlags;
40802   if( pPager->fullSync ){
40803     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
40804   }
40805 }
40806 #endif
40807 
40808 /*
40809 ** The following global variable is incremented whenever the library
40810 ** attempts to open a temporary file.  This information is used for
40811 ** testing and analysis only.
40812 */
40813 #ifdef SQLITE_TEST
40814 SQLITE_API int sqlite3_opentemp_count = 0;
40815 #endif
40816 
40817 /*
40818 ** Open a temporary file.
40819 **
40820 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
40821 ** or some other error code if we fail. The OS will automatically
40822 ** delete the temporary file when it is closed.
40823 **
40824 ** The flags passed to the VFS layer xOpen() call are those specified
40825 ** by parameter vfsFlags ORed with the following:
40826 **
40827 **     SQLITE_OPEN_READWRITE
40828 **     SQLITE_OPEN_CREATE
40829 **     SQLITE_OPEN_EXCLUSIVE
40830 **     SQLITE_OPEN_DELETEONCLOSE
40831 */
40832 static int pagerOpentemp(
40833   Pager *pPager,        /* The pager object */
40834   sqlite3_file *pFile,  /* Write the file descriptor here */
40835   int vfsFlags          /* Flags passed through to the VFS */
40836 ){
40837   int rc;               /* Return code */
40838 
40839 #ifdef SQLITE_TEST
40840   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
40841 #endif
40842 
40843   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40844             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40845   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40846   assert( rc!=SQLITE_OK || isOpen(pFile) );
40847   return rc;
40848 }
40849 
40850 /*
40851 ** Set the busy handler function.
40852 **
40853 ** The pager invokes the busy-handler if sqlite3OsLock() returns
40854 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40855 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
40856 ** lock. It does *not* invoke the busy handler when upgrading from
40857 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40858 ** (which occurs during hot-journal rollback). Summary:
40859 **
40860 **   Transition                        | Invokes xBusyHandler
40861 **   --------------------------------------------------------
40862 **   NO_LOCK       -> SHARED_LOCK      | Yes
40863 **   SHARED_LOCK   -> RESERVED_LOCK    | No
40864 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
40865 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
40866 **
40867 ** If the busy-handler callback returns non-zero, the lock is
40868 ** retried. If it returns zero, then the SQLITE_BUSY error is
40869 ** returned to the caller of the pager API function.
40870 */
40871 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40872   Pager *pPager,                       /* Pager object */
40873   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
40874   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
40875 ){
40876   pPager->xBusyHandler = xBusyHandler;
40877   pPager->pBusyHandlerArg = pBusyHandlerArg;
40878 
40879   if( isOpen(pPager->fd) ){
40880     void **ap = (void **)&pPager->xBusyHandler;
40881     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
40882     assert( ap[1]==pBusyHandlerArg );
40883     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
40884   }
40885 }
40886 
40887 /*
40888 ** Change the page size used by the Pager object. The new page size
40889 ** is passed in *pPageSize.
40890 **
40891 ** If the pager is in the error state when this function is called, it
40892 ** is a no-op. The value returned is the error state error code (i.e.
40893 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40894 **
40895 ** Otherwise, if all of the following are true:
40896 **
40897 **   * the new page size (value of *pPageSize) is valid (a power
40898 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40899 **
40900 **   * there are no outstanding page references, and
40901 **
40902 **   * the database is either not an in-memory database or it is
40903 **     an in-memory database that currently consists of zero pages.
40904 **
40905 ** then the pager object page size is set to *pPageSize.
40906 **
40907 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
40908 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
40909 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
40910 ** In all other cases, SQLITE_OK is returned.
40911 **
40912 ** If the page size is not changed, either because one of the enumerated
40913 ** conditions above is not true, the pager was in error state when this
40914 ** function was called, or because the memory allocation attempt failed,
40915 ** then *pPageSize is set to the old, retained page size before returning.
40916 */
40917 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
40918   int rc = SQLITE_OK;
40919 
40920   /* It is not possible to do a full assert_pager_state() here, as this
40921   ** function may be called from within PagerOpen(), before the state
40922   ** of the Pager object is internally consistent.
40923   **
40924   ** At one point this function returned an error if the pager was in
40925   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
40926   ** there is at least one outstanding page reference, this function
40927   ** is a no-op for that case anyhow.
40928   */
40929 
40930   u32 pageSize = *pPageSize;
40931   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
40932   if( (pPager->memDb==0 || pPager->dbSize==0)
40933    && sqlite3PcacheRefCount(pPager->pPCache)==0
40934    && pageSize && pageSize!=(u32)pPager->pageSize
40935   ){
40936     char *pNew = NULL;             /* New temp space */
40937     i64 nByte = 0;
40938 
40939     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
40940       rc = sqlite3OsFileSize(pPager->fd, &nByte);
40941     }
40942     if( rc==SQLITE_OK ){
40943       pNew = (char *)sqlite3PageMalloc(pageSize);
40944       if( !pNew ) rc = SQLITE_NOMEM;
40945     }
40946 
40947     if( rc==SQLITE_OK ){
40948       pager_reset(pPager);
40949       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
40950       pPager->pageSize = pageSize;
40951       sqlite3PageFree(pPager->pTmpSpace);
40952       pPager->pTmpSpace = pNew;
40953       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
40954     }
40955   }
40956 
40957   *pPageSize = pPager->pageSize;
40958   if( rc==SQLITE_OK ){
40959     if( nReserve<0 ) nReserve = pPager->nReserve;
40960     assert( nReserve>=0 && nReserve<1000 );
40961     pPager->nReserve = (i16)nReserve;
40962     pagerReportSize(pPager);
40963   }
40964   return rc;
40965 }
40966 
40967 /*
40968 ** Return a pointer to the "temporary page" buffer held internally
40969 ** by the pager.  This is a buffer that is big enough to hold the
40970 ** entire content of a database page.  This buffer is used internally
40971 ** during rollback and will be overwritten whenever a rollback
40972 ** occurs.  But other modules are free to use it too, as long as
40973 ** no rollbacks are happening.
40974 */
40975 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
40976   return pPager->pTmpSpace;
40977 }
40978 
40979 /*
40980 ** Attempt to set the maximum database page count if mxPage is positive.
40981 ** Make no changes if mxPage is zero or negative.  And never reduce the
40982 ** maximum page count below the current size of the database.
40983 **
40984 ** Regardless of mxPage, return the current maximum page count.
40985 */
40986 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
40987   if( mxPage>0 ){
40988     pPager->mxPgno = mxPage;
40989   }
40990   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
40991   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
40992   return pPager->mxPgno;
40993 }
40994 
40995 /*
40996 ** The following set of routines are used to disable the simulated
40997 ** I/O error mechanism.  These routines are used to avoid simulated
40998 ** errors in places where we do not care about errors.
40999 **
41000 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
41001 ** and generate no code.
41002 */
41003 #ifdef SQLITE_TEST
41004 SQLITE_API extern int sqlite3_io_error_pending;
41005 SQLITE_API extern int sqlite3_io_error_hit;
41006 static int saved_cnt;
41007 void disable_simulated_io_errors(void){
41008   saved_cnt = sqlite3_io_error_pending;
41009   sqlite3_io_error_pending = -1;
41010 }
41011 void enable_simulated_io_errors(void){
41012   sqlite3_io_error_pending = saved_cnt;
41013 }
41014 #else
41015 # define disable_simulated_io_errors()
41016 # define enable_simulated_io_errors()
41017 #endif
41018 
41019 /*
41020 ** Read the first N bytes from the beginning of the file into memory
41021 ** that pDest points to.
41022 **
41023 ** If the pager was opened on a transient file (zFilename==""), or
41024 ** opened on a file less than N bytes in size, the output buffer is
41025 ** zeroed and SQLITE_OK returned. The rationale for this is that this
41026 ** function is used to read database headers, and a new transient or
41027 ** zero sized database has a header than consists entirely of zeroes.
41028 **
41029 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
41030 ** the error code is returned to the caller and the contents of the
41031 ** output buffer undefined.
41032 */
41033 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
41034   int rc = SQLITE_OK;
41035   memset(pDest, 0, N);
41036   assert( isOpen(pPager->fd) || pPager->tempFile );
41037 
41038   /* This routine is only called by btree immediately after creating
41039   ** the Pager object.  There has not been an opportunity to transition
41040   ** to WAL mode yet.
41041   */
41042   assert( !pagerUseWal(pPager) );
41043 
41044   if( isOpen(pPager->fd) ){
41045     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
41046     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
41047     if( rc==SQLITE_IOERR_SHORT_READ ){
41048       rc = SQLITE_OK;
41049     }
41050   }
41051   return rc;
41052 }
41053 
41054 /*
41055 ** This function may only be called when a read-transaction is open on
41056 ** the pager. It returns the total number of pages in the database.
41057 **
41058 ** However, if the file is between 1 and <page-size> bytes in size, then
41059 ** this is considered a 1 page file.
41060 */
41061 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
41062   assert( pPager->eState>=PAGER_READER );
41063   assert( pPager->eState!=PAGER_WRITER_FINISHED );
41064   *pnPage = (int)pPager->dbSize;
41065 }
41066 
41067 
41068 /*
41069 ** Try to obtain a lock of type locktype on the database file. If
41070 ** a similar or greater lock is already held, this function is a no-op
41071 ** (returning SQLITE_OK immediately).
41072 **
41073 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
41074 ** the busy callback if the lock is currently not available. Repeat
41075 ** until the busy callback returns false or until the attempt to
41076 ** obtain the lock succeeds.
41077 **
41078 ** Return SQLITE_OK on success and an error code if we cannot obtain
41079 ** the lock. If the lock is obtained successfully, set the Pager.state
41080 ** variable to locktype before returning.
41081 */
41082 static int pager_wait_on_lock(Pager *pPager, int locktype){
41083   int rc;                              /* Return code */
41084 
41085   /* Check that this is either a no-op (because the requested lock is
41086   ** already held, or one of the transistions that the busy-handler
41087   ** may be invoked during, according to the comment above
41088   ** sqlite3PagerSetBusyhandler().
41089   */
41090   assert( (pPager->eLock>=locktype)
41091        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
41092        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
41093   );
41094 
41095   do {
41096     rc = pagerLockDb(pPager, locktype);
41097   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
41098   return rc;
41099 }
41100 
41101 /*
41102 ** Function assertTruncateConstraint(pPager) checks that one of the
41103 ** following is true for all dirty pages currently in the page-cache:
41104 **
41105 **   a) The page number is less than or equal to the size of the
41106 **      current database image, in pages, OR
41107 **
41108 **   b) if the page content were written at this time, it would not
41109 **      be necessary to write the current content out to the sub-journal
41110 **      (as determined by function subjRequiresPage()).
41111 **
41112 ** If the condition asserted by this function were not true, and the
41113 ** dirty page were to be discarded from the cache via the pagerStress()
41114 ** routine, pagerStress() would not write the current page content to
41115 ** the database file. If a savepoint transaction were rolled back after
41116 ** this happened, the correct behavior would be to restore the current
41117 ** content of the page. However, since this content is not present in either
41118 ** the database file or the portion of the rollback journal and
41119 ** sub-journal rolled back the content could not be restored and the
41120 ** database image would become corrupt. It is therefore fortunate that
41121 ** this circumstance cannot arise.
41122 */
41123 #if defined(SQLITE_DEBUG)
41124 static void assertTruncateConstraintCb(PgHdr *pPg){
41125   assert( pPg->flags&PGHDR_DIRTY );
41126   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
41127 }
41128 static void assertTruncateConstraint(Pager *pPager){
41129   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
41130 }
41131 #else
41132 # define assertTruncateConstraint(pPager)
41133 #endif
41134 
41135 /*
41136 ** Truncate the in-memory database file image to nPage pages. This
41137 ** function does not actually modify the database file on disk. It
41138 ** just sets the internal state of the pager object so that the
41139 ** truncation will be done when the current transaction is committed.
41140 **
41141 ** This function is only called right before committing a transaction.
41142 ** Once this function has been called, the transaction must either be
41143 ** rolled back or committed. It is not safe to call this function and
41144 ** then continue writing to the database.
41145 */
41146 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
41147   assert( pPager->dbSize>=nPage );
41148   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41149   pPager->dbSize = nPage;
41150 
41151   /* At one point the code here called assertTruncateConstraint() to
41152   ** ensure that all pages being truncated away by this operation are,
41153   ** if one or more savepoints are open, present in the savepoint
41154   ** journal so that they can be restored if the savepoint is rolled
41155   ** back. This is no longer necessary as this function is now only
41156   ** called right before committing a transaction. So although the
41157   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
41158   ** they cannot be rolled back. So the assertTruncateConstraint() call
41159   ** is no longer correct. */
41160 }
41161 
41162 
41163 /*
41164 ** This function is called before attempting a hot-journal rollback. It
41165 ** syncs the journal file to disk, then sets pPager->journalHdr to the
41166 ** size of the journal file so that the pager_playback() routine knows
41167 ** that the entire journal file has been synced.
41168 **
41169 ** Syncing a hot-journal to disk before attempting to roll it back ensures
41170 ** that if a power-failure occurs during the rollback, the process that
41171 ** attempts rollback following system recovery sees the same journal
41172 ** content as this process.
41173 **
41174 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
41175 ** an SQLite error code.
41176 */
41177 static int pagerSyncHotJournal(Pager *pPager){
41178   int rc = SQLITE_OK;
41179   if( !pPager->noSync ){
41180     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
41181   }
41182   if( rc==SQLITE_OK ){
41183     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
41184   }
41185   return rc;
41186 }
41187 
41188 /*
41189 ** Shutdown the page cache.  Free all memory and close all files.
41190 **
41191 ** If a transaction was in progress when this routine is called, that
41192 ** transaction is rolled back.  All outstanding pages are invalidated
41193 ** and their memory is freed.  Any attempt to use a page associated
41194 ** with this page cache after this function returns will likely
41195 ** result in a coredump.
41196 **
41197 ** This function always succeeds. If a transaction is active an attempt
41198 ** is made to roll it back. If an error occurs during the rollback
41199 ** a hot journal may be left in the filesystem but no error is returned
41200 ** to the caller.
41201 */
41202 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
41203   u8 *pTmp = (u8 *)pPager->pTmpSpace;
41204 
41205   assert( assert_pager_state(pPager) );
41206   disable_simulated_io_errors();
41207   sqlite3BeginBenignMalloc();
41208   /* pPager->errCode = 0; */
41209   pPager->exclusiveMode = 0;
41210 #ifndef SQLITE_OMIT_WAL
41211   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
41212   pPager->pWal = 0;
41213 #endif
41214   pager_reset(pPager);
41215   if( MEMDB ){
41216     pager_unlock(pPager);
41217   }else{
41218     /* If it is open, sync the journal file before calling UnlockAndRollback.
41219     ** If this is not done, then an unsynced portion of the open journal
41220     ** file may be played back into the database. If a power failure occurs
41221     ** while this is happening, the database could become corrupt.
41222     **
41223     ** If an error occurs while trying to sync the journal, shift the pager
41224     ** into the ERROR state. This causes UnlockAndRollback to unlock the
41225     ** database and close the journal file without attempting to roll it
41226     ** back or finalize it. The next database user will have to do hot-journal
41227     ** rollback before accessing the database file.
41228     */
41229     if( isOpen(pPager->jfd) ){
41230       pager_error(pPager, pagerSyncHotJournal(pPager));
41231     }
41232     pagerUnlockAndRollback(pPager);
41233   }
41234   sqlite3EndBenignMalloc();
41235   enable_simulated_io_errors();
41236   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
41237   IOTRACE(("CLOSE %p\n", pPager))
41238   sqlite3OsClose(pPager->jfd);
41239   sqlite3OsClose(pPager->fd);
41240   sqlite3PageFree(pTmp);
41241   sqlite3PcacheClose(pPager->pPCache);
41242 
41243 #ifdef SQLITE_HAS_CODEC
41244   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
41245 #endif
41246 
41247   assert( !pPager->aSavepoint && !pPager->pInJournal );
41248   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
41249 
41250   sqlite3_free(pPager);
41251   return SQLITE_OK;
41252 }
41253 
41254 #if !defined(NDEBUG) || defined(SQLITE_TEST)
41255 /*
41256 ** Return the page number for page pPg.
41257 */
41258 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
41259   return pPg->pgno;
41260 }
41261 #endif
41262 
41263 /*
41264 ** Increment the reference count for page pPg.
41265 */
41266 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
41267   sqlite3PcacheRef(pPg);
41268 }
41269 
41270 /*
41271 ** Sync the journal. In other words, make sure all the pages that have
41272 ** been written to the journal have actually reached the surface of the
41273 ** disk and can be restored in the event of a hot-journal rollback.
41274 **
41275 ** If the Pager.noSync flag is set, then this function is a no-op.
41276 ** Otherwise, the actions required depend on the journal-mode and the
41277 ** device characteristics of the file-system, as follows:
41278 **
41279 **   * If the journal file is an in-memory journal file, no action need
41280 **     be taken.
41281 **
41282 **   * Otherwise, if the device does not support the SAFE_APPEND property,
41283 **     then the nRec field of the most recently written journal header
41284 **     is updated to contain the number of journal records that have
41285 **     been written following it. If the pager is operating in full-sync
41286 **     mode, then the journal file is synced before this field is updated.
41287 **
41288 **   * If the device does not support the SEQUENTIAL property, then
41289 **     journal file is synced.
41290 **
41291 ** Or, in pseudo-code:
41292 **
41293 **   if( NOT <in-memory journal> ){
41294 **     if( NOT SAFE_APPEND ){
41295 **       if( <full-sync mode> ) xSync(<journal file>);
41296 **       <update nRec field>
41297 **     }
41298 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
41299 **   }
41300 **
41301 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
41302 ** page currently held in memory before returning SQLITE_OK. If an IO
41303 ** error is encountered, then the IO error code is returned to the caller.
41304 */
41305 static int syncJournal(Pager *pPager, int newHdr){
41306   int rc;                         /* Return code */
41307 
41308   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41309        || pPager->eState==PAGER_WRITER_DBMOD
41310   );
41311   assert( assert_pager_state(pPager) );
41312   assert( !pagerUseWal(pPager) );
41313 
41314   rc = sqlite3PagerExclusiveLock(pPager);
41315   if( rc!=SQLITE_OK ) return rc;
41316 
41317   if( !pPager->noSync ){
41318     assert( !pPager->tempFile );
41319     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
41320       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41321       assert( isOpen(pPager->jfd) );
41322 
41323       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41324         /* This block deals with an obscure problem. If the last connection
41325         ** that wrote to this database was operating in persistent-journal
41326         ** mode, then the journal file may at this point actually be larger
41327         ** than Pager.journalOff bytes. If the next thing in the journal
41328         ** file happens to be a journal-header (written as part of the
41329         ** previous connection's transaction), and a crash or power-failure
41330         ** occurs after nRec is updated but before this connection writes
41331         ** anything else to the journal file (or commits/rolls back its
41332         ** transaction), then SQLite may become confused when doing the
41333         ** hot-journal rollback following recovery. It may roll back all
41334         ** of this connections data, then proceed to rolling back the old,
41335         ** out-of-date data that follows it. Database corruption.
41336         **
41337         ** To work around this, if the journal file does appear to contain
41338         ** a valid header following Pager.journalOff, then write a 0x00
41339         ** byte to the start of it to prevent it from being recognized.
41340         **
41341         ** Variable iNextHdrOffset is set to the offset at which this
41342         ** problematic header will occur, if it exists. aMagic is used
41343         ** as a temporary buffer to inspect the first couple of bytes of
41344         ** the potential journal header.
41345         */
41346         i64 iNextHdrOffset;
41347         u8 aMagic[8];
41348         u8 zHeader[sizeof(aJournalMagic)+4];
41349 
41350         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41351         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
41352 
41353         iNextHdrOffset = journalHdrOffset(pPager);
41354         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
41355         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
41356           static const u8 zerobyte = 0;
41357           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
41358         }
41359         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
41360           return rc;
41361         }
41362 
41363         /* Write the nRec value into the journal file header. If in
41364         ** full-synchronous mode, sync the journal first. This ensures that
41365         ** all data has really hit the disk before nRec is updated to mark
41366         ** it as a candidate for rollback.
41367         **
41368         ** This is not required if the persistent media supports the
41369         ** SAFE_APPEND property. Because in this case it is not possible
41370         ** for garbage data to be appended to the file, the nRec field
41371         ** is populated with 0xFFFFFFFF when the journal header is written
41372         ** and never needs to be updated.
41373         */
41374         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41375           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41376           IOTRACE(("JSYNC %p\n", pPager))
41377           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
41378           if( rc!=SQLITE_OK ) return rc;
41379         }
41380         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
41381         rc = sqlite3OsWrite(
41382             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
41383         );
41384         if( rc!=SQLITE_OK ) return rc;
41385       }
41386       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41387         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41388         IOTRACE(("JSYNC %p\n", pPager))
41389         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
41390           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
41391         );
41392         if( rc!=SQLITE_OK ) return rc;
41393       }
41394 
41395       pPager->journalHdr = pPager->journalOff;
41396       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41397         pPager->nRec = 0;
41398         rc = writeJournalHdr(pPager);
41399         if( rc!=SQLITE_OK ) return rc;
41400       }
41401     }else{
41402       pPager->journalHdr = pPager->journalOff;
41403     }
41404   }
41405 
41406   /* Unless the pager is in noSync mode, the journal file was just
41407   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
41408   ** all pages.
41409   */
41410   sqlite3PcacheClearSyncFlags(pPager->pPCache);
41411   pPager->eState = PAGER_WRITER_DBMOD;
41412   assert( assert_pager_state(pPager) );
41413   return SQLITE_OK;
41414 }
41415 
41416 /*
41417 ** The argument is the first in a linked list of dirty pages connected
41418 ** by the PgHdr.pDirty pointer. This function writes each one of the
41419 ** in-memory pages in the list to the database file. The argument may
41420 ** be NULL, representing an empty list. In this case this function is
41421 ** a no-op.
41422 **
41423 ** The pager must hold at least a RESERVED lock when this function
41424 ** is called. Before writing anything to the database file, this lock
41425 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
41426 ** SQLITE_BUSY is returned and no data is written to the database file.
41427 **
41428 ** If the pager is a temp-file pager and the actual file-system file
41429 ** is not yet open, it is created and opened before any data is
41430 ** written out.
41431 **
41432 ** Once the lock has been upgraded and, if necessary, the file opened,
41433 ** the pages are written out to the database file in list order. Writing
41434 ** a page is skipped if it meets either of the following criteria:
41435 **
41436 **   * The page number is greater than Pager.dbSize, or
41437 **   * The PGHDR_DONT_WRITE flag is set on the page.
41438 **
41439 ** If writing out a page causes the database file to grow, Pager.dbFileSize
41440 ** is updated accordingly. If page 1 is written out, then the value cached
41441 ** in Pager.dbFileVers[] is updated to match the new value stored in
41442 ** the database file.
41443 **
41444 ** If everything is successful, SQLITE_OK is returned. If an IO error
41445 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
41446 ** be obtained, SQLITE_BUSY is returned.
41447 */
41448 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
41449   int rc = SQLITE_OK;                  /* Return code */
41450 
41451   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
41452   assert( !pagerUseWal(pPager) );
41453   assert( pPager->eState==PAGER_WRITER_DBMOD );
41454   assert( pPager->eLock==EXCLUSIVE_LOCK );
41455 
41456   /* If the file is a temp-file has not yet been opened, open it now. It
41457   ** is not possible for rc to be other than SQLITE_OK if this branch
41458   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
41459   */
41460   if( !isOpen(pPager->fd) ){
41461     assert( pPager->tempFile && rc==SQLITE_OK );
41462     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
41463   }
41464 
41465   /* Before the first write, give the VFS a hint of what the final
41466   ** file size will be.
41467   */
41468   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
41469   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
41470     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
41471     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
41472     pPager->dbHintSize = pPager->dbSize;
41473   }
41474 
41475   while( rc==SQLITE_OK && pList ){
41476     Pgno pgno = pList->pgno;
41477 
41478     /* If there are dirty pages in the page cache with page numbers greater
41479     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
41480     ** make the file smaller (presumably by auto-vacuum code). Do not write
41481     ** any such pages to the file.
41482     **
41483     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
41484     ** set (set by sqlite3PagerDontWrite()).
41485     */
41486     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
41487       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
41488       char *pData;                                   /* Data to write */
41489 
41490       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
41491       if( pList->pgno==1 ) pager_write_changecounter(pList);
41492 
41493       /* Encode the database */
41494       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
41495 
41496       /* Write out the page data. */
41497       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
41498 
41499       /* If page 1 was just written, update Pager.dbFileVers to match
41500       ** the value now stored in the database file. If writing this
41501       ** page caused the database file to grow, update dbFileSize.
41502       */
41503       if( pgno==1 ){
41504         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
41505       }
41506       if( pgno>pPager->dbFileSize ){
41507         pPager->dbFileSize = pgno;
41508       }
41509       pPager->aStat[PAGER_STAT_WRITE]++;
41510 
41511       /* Update any backup objects copying the contents of this pager. */
41512       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
41513 
41514       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
41515                    PAGERID(pPager), pgno, pager_pagehash(pList)));
41516       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
41517       PAGER_INCR(sqlite3_pager_writedb_count);
41518     }else{
41519       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
41520     }
41521     pager_set_pagehash(pList);
41522     pList = pList->pDirty;
41523   }
41524 
41525   return rc;
41526 }
41527 
41528 /*
41529 ** Ensure that the sub-journal file is open. If it is already open, this
41530 ** function is a no-op.
41531 **
41532 ** SQLITE_OK is returned if everything goes according to plan. An
41533 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
41534 ** fails.
41535 */
41536 static int openSubJournal(Pager *pPager){
41537   int rc = SQLITE_OK;
41538   if( !isOpen(pPager->sjfd) ){
41539     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
41540       sqlite3MemJournalOpen(pPager->sjfd);
41541     }else{
41542       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
41543     }
41544   }
41545   return rc;
41546 }
41547 
41548 /*
41549 ** Append a record of the current state of page pPg to the sub-journal.
41550 ** It is the callers responsibility to use subjRequiresPage() to check
41551 ** that it is really required before calling this function.
41552 **
41553 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
41554 ** for all open savepoints before returning.
41555 **
41556 ** This function returns SQLITE_OK if everything is successful, an IO
41557 ** error code if the attempt to write to the sub-journal fails, or
41558 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
41559 ** bitvec.
41560 */
41561 static int subjournalPage(PgHdr *pPg){
41562   int rc = SQLITE_OK;
41563   Pager *pPager = pPg->pPager;
41564   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41565 
41566     /* Open the sub-journal, if it has not already been opened */
41567     assert( pPager->useJournal );
41568     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
41569     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
41570     assert( pagerUseWal(pPager)
41571          || pageInJournal(pPg)
41572          || pPg->pgno>pPager->dbOrigSize
41573     );
41574     rc = openSubJournal(pPager);
41575 
41576     /* If the sub-journal was opened successfully (or was already open),
41577     ** write the journal record into the file.  */
41578     if( rc==SQLITE_OK ){
41579       void *pData = pPg->pData;
41580       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
41581       char *pData2;
41582 
41583       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41584       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
41585       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
41586       if( rc==SQLITE_OK ){
41587         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
41588       }
41589     }
41590   }
41591   if( rc==SQLITE_OK ){
41592     pPager->nSubRec++;
41593     assert( pPager->nSavepoint>0 );
41594     rc = addToSavepointBitvecs(pPager, pPg->pgno);
41595   }
41596   return rc;
41597 }
41598 
41599 /*
41600 ** This function is called by the pcache layer when it has reached some
41601 ** soft memory limit. The first argument is a pointer to a Pager object
41602 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
41603 ** database). The second argument is a reference to a page that is
41604 ** currently dirty but has no outstanding references. The page
41605 ** is always associated with the Pager object passed as the first
41606 ** argument.
41607 **
41608 ** The job of this function is to make pPg clean by writing its contents
41609 ** out to the database file, if possible. This may involve syncing the
41610 ** journal file.
41611 **
41612 ** If successful, sqlite3PcacheMakeClean() is called on the page and
41613 ** SQLITE_OK returned. If an IO error occurs while trying to make the
41614 ** page clean, the IO error code is returned. If the page cannot be
41615 ** made clean for some other reason, but no error occurs, then SQLITE_OK
41616 ** is returned by sqlite3PcacheMakeClean() is not called.
41617 */
41618 static int pagerStress(void *p, PgHdr *pPg){
41619   Pager *pPager = (Pager *)p;
41620   int rc = SQLITE_OK;
41621 
41622   assert( pPg->pPager==pPager );
41623   assert( pPg->flags&PGHDR_DIRTY );
41624 
41625   /* The doNotSyncSpill flag is set during times when doing a sync of
41626   ** journal (and adding a new header) is not allowed.  This occurs
41627   ** during calls to sqlite3PagerWrite() while trying to journal multiple
41628   ** pages belonging to the same sector.
41629   **
41630   ** The doNotSpill flag inhibits all cache spilling regardless of whether
41631   ** or not a sync is required.  This is set during a rollback.
41632   **
41633   ** Spilling is also prohibited when in an error state since that could
41634   ** lead to database corruption.   In the current implementaton it
41635   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
41636   ** while in the error state, hence it is impossible for this routine to
41637   ** be called in the error state.  Nevertheless, we include a NEVER()
41638   ** test for the error state as a safeguard against future changes.
41639   */
41640   if( NEVER(pPager->errCode) ) return SQLITE_OK;
41641   if( pPager->doNotSpill ) return SQLITE_OK;
41642   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
41643     return SQLITE_OK;
41644   }
41645 
41646   pPg->pDirty = 0;
41647   if( pagerUseWal(pPager) ){
41648     /* Write a single frame for this page to the log. */
41649     if( subjRequiresPage(pPg) ){
41650       rc = subjournalPage(pPg);
41651     }
41652     if( rc==SQLITE_OK ){
41653       rc = pagerWalFrames(pPager, pPg, 0, 0);
41654     }
41655   }else{
41656 
41657     /* Sync the journal file if required. */
41658     if( pPg->flags&PGHDR_NEED_SYNC
41659      || pPager->eState==PAGER_WRITER_CACHEMOD
41660     ){
41661       rc = syncJournal(pPager, 1);
41662     }
41663 
41664     /* If the page number of this page is larger than the current size of
41665     ** the database image, it may need to be written to the sub-journal.
41666     ** This is because the call to pager_write_pagelist() below will not
41667     ** actually write data to the file in this case.
41668     **
41669     ** Consider the following sequence of events:
41670     **
41671     **   BEGIN;
41672     **     <journal page X>
41673     **     <modify page X>
41674     **     SAVEPOINT sp;
41675     **       <shrink database file to Y pages>
41676     **       pagerStress(page X)
41677     **     ROLLBACK TO sp;
41678     **
41679     ** If (X>Y), then when pagerStress is called page X will not be written
41680     ** out to the database file, but will be dropped from the cache. Then,
41681     ** following the "ROLLBACK TO sp" statement, reading page X will read
41682     ** data from the database file. This will be the copy of page X as it
41683     ** was when the transaction started, not as it was when "SAVEPOINT sp"
41684     ** was executed.
41685     **
41686     ** The solution is to write the current data for page X into the
41687     ** sub-journal file now (if it is not already there), so that it will
41688     ** be restored to its current value when the "ROLLBACK TO sp" is
41689     ** executed.
41690     */
41691     if( NEVER(
41692         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41693     ) ){
41694       rc = subjournalPage(pPg);
41695     }
41696 
41697     /* Write the contents of the page out to the database file. */
41698     if( rc==SQLITE_OK ){
41699       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41700       rc = pager_write_pagelist(pPager, pPg);
41701     }
41702   }
41703 
41704   /* Mark the page as clean. */
41705   if( rc==SQLITE_OK ){
41706     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41707     sqlite3PcacheMakeClean(pPg);
41708   }
41709 
41710   return pager_error(pPager, rc);
41711 }
41712 
41713 
41714 /*
41715 ** Allocate and initialize a new Pager object and put a pointer to it
41716 ** in *ppPager. The pager should eventually be freed by passing it
41717 ** to sqlite3PagerClose().
41718 **
41719 ** The zFilename argument is the path to the database file to open.
41720 ** If zFilename is NULL then a randomly-named temporary file is created
41721 ** and used as the file to be cached. Temporary files are be deleted
41722 ** automatically when they are closed. If zFilename is ":memory:" then
41723 ** all information is held in cache. It is never written to disk.
41724 ** This can be used to implement an in-memory database.
41725 **
41726 ** The nExtra parameter specifies the number of bytes of space allocated
41727 ** along with each page reference. This space is available to the user
41728 ** via the sqlite3PagerGetExtra() API.
41729 **
41730 ** The flags argument is used to specify properties that affect the
41731 ** operation of the pager. It should be passed some bitwise combination
41732 ** of the PAGER_* flags.
41733 **
41734 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41735 ** of the xOpen() method of the supplied VFS when opening files.
41736 **
41737 ** If the pager object is allocated and the specified file opened
41738 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41739 ** the new pager object. If an error occurs, *ppPager is set to NULL
41740 ** and error code returned. This function may return SQLITE_NOMEM
41741 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
41742 ** various SQLITE_IO_XXX errors.
41743 */
41744 SQLITE_PRIVATE int sqlite3PagerOpen(
41745   sqlite3_vfs *pVfs,       /* The virtual file system to use */
41746   Pager **ppPager,         /* OUT: Return the Pager structure here */
41747   const char *zFilename,   /* Name of the database file to open */
41748   int nExtra,              /* Extra bytes append to each in-memory page */
41749   int flags,               /* flags controlling this file */
41750   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
41751   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41752 ){
41753   u8 *pPtr;
41754   Pager *pPager = 0;       /* Pager object to allocate and return */
41755   int rc = SQLITE_OK;      /* Return code */
41756   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
41757   int memDb = 0;           /* True if this is an in-memory file */
41758   int readOnly = 0;        /* True if this is a read-only file */
41759   int journalFileSize;     /* Bytes to allocate for each journal fd */
41760   char *zPathname = 0;     /* Full path to database file */
41761   int nPathname = 0;       /* Number of bytes in zPathname */
41762   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41763   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
41764   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
41765   const char *zUri = 0;    /* URI args to copy */
41766   int nUri = 0;            /* Number of bytes of URI args at *zUri */
41767 
41768   /* Figure out how much space is required for each journal file-handle
41769   ** (there are two of them, the main journal and the sub-journal). This
41770   ** is the maximum space required for an in-memory journal file handle
41771   ** and a regular journal file-handle. Note that a "regular journal-handle"
41772   ** may be a wrapper capable of caching the first portion of the journal
41773   ** file in memory to implement the atomic-write optimization (see
41774   ** source file journal.c).
41775   */
41776   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41777     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41778   }else{
41779     journalFileSize = ROUND8(sqlite3MemJournalSize());
41780   }
41781 
41782   /* Set the output variable to NULL in case an error occurs. */
41783   *ppPager = 0;
41784 
41785 #ifndef SQLITE_OMIT_MEMORYDB
41786   if( flags & PAGER_MEMORY ){
41787     memDb = 1;
41788     if( zFilename && zFilename[0] ){
41789       zPathname = sqlite3DbStrDup(0, zFilename);
41790       if( zPathname==0  ) return SQLITE_NOMEM;
41791       nPathname = sqlite3Strlen30(zPathname);
41792       zFilename = 0;
41793     }
41794   }
41795 #endif
41796 
41797   /* Compute and store the full pathname in an allocated buffer pointed
41798   ** to by zPathname, length nPathname. Or, if this is a temporary file,
41799   ** leave both nPathname and zPathname set to 0.
41800   */
41801   if( zFilename && zFilename[0] ){
41802     const char *z;
41803     nPathname = pVfs->mxPathname+1;
41804     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
41805     if( zPathname==0 ){
41806       return SQLITE_NOMEM;
41807     }
41808     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41809     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41810     nPathname = sqlite3Strlen30(zPathname);
41811     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41812     while( *z ){
41813       z += sqlite3Strlen30(z)+1;
41814       z += sqlite3Strlen30(z)+1;
41815     }
41816     nUri = (int)(&z[1] - zUri);
41817     assert( nUri>=0 );
41818     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41819       /* This branch is taken when the journal path required by
41820       ** the database being opened will be more than pVfs->mxPathname
41821       ** bytes in length. This means the database cannot be opened,
41822       ** as it will not be possible to open the journal file or even
41823       ** check for a hot-journal before reading.
41824       */
41825       rc = SQLITE_CANTOPEN_BKPT;
41826     }
41827     if( rc!=SQLITE_OK ){
41828       sqlite3DbFree(0, zPathname);
41829       return rc;
41830     }
41831   }
41832 
41833   /* Allocate memory for the Pager structure, PCache object, the
41834   ** three file descriptors, the database file name and the journal
41835   ** file name. The layout in memory is as follows:
41836   **
41837   **     Pager object                    (sizeof(Pager) bytes)
41838   **     PCache object                   (sqlite3PcacheSize() bytes)
41839   **     Database file handle            (pVfs->szOsFile bytes)
41840   **     Sub-journal file handle         (journalFileSize bytes)
41841   **     Main journal file handle        (journalFileSize bytes)
41842   **     Database file name              (nPathname+1 bytes)
41843   **     Journal file name               (nPathname+8+1 bytes)
41844   */
41845   pPtr = (u8 *)sqlite3MallocZero(
41846     ROUND8(sizeof(*pPager)) +      /* Pager structure */
41847     ROUND8(pcacheSize) +           /* PCache object */
41848     ROUND8(pVfs->szOsFile) +       /* The main db file */
41849     journalFileSize * 2 +          /* The two journal files */
41850     nPathname + 1 + nUri +         /* zFilename */
41851     nPathname + 8 + 2              /* zJournal */
41852 #ifndef SQLITE_OMIT_WAL
41853     + nPathname + 4 + 2            /* zWal */
41854 #endif
41855   );
41856   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41857   if( !pPtr ){
41858     sqlite3DbFree(0, zPathname);
41859     return SQLITE_NOMEM;
41860   }
41861   pPager =              (Pager*)(pPtr);
41862   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41863   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41864   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41865   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
41866   pPager->zFilename =    (char*)(pPtr += journalFileSize);
41867   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41868 
41869   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41870   if( zPathname ){
41871     assert( nPathname>0 );
41872     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
41873     memcpy(pPager->zFilename, zPathname, nPathname);
41874     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41875     memcpy(pPager->zJournal, zPathname, nPathname);
41876     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
41877     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41878 #ifndef SQLITE_OMIT_WAL
41879     pPager->zWal = &pPager->zJournal[nPathname+8+1];
41880     memcpy(pPager->zWal, zPathname, nPathname);
41881     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
41882     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41883 #endif
41884     sqlite3DbFree(0, zPathname);
41885   }
41886   pPager->pVfs = pVfs;
41887   pPager->vfsFlags = vfsFlags;
41888 
41889   /* Open the pager file.
41890   */
41891   if( zFilename && zFilename[0] ){
41892     int fout = 0;                    /* VFS flags returned by xOpen() */
41893     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41894     assert( !memDb );
41895     readOnly = (fout&SQLITE_OPEN_READONLY);
41896 
41897     /* If the file was successfully opened for read/write access,
41898     ** choose a default page size in case we have to create the
41899     ** database file. The default page size is the maximum of:
41900     **
41901     **    + SQLITE_DEFAULT_PAGE_SIZE,
41902     **    + The value returned by sqlite3OsSectorSize()
41903     **    + The largest page size that can be written atomically.
41904     */
41905     if( rc==SQLITE_OK && !readOnly ){
41906       setSectorSize(pPager);
41907       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41908       if( szPageDflt<pPager->sectorSize ){
41909         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41910           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41911         }else{
41912           szPageDflt = (u32)pPager->sectorSize;
41913         }
41914       }
41915 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41916       {
41917         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41918         int ii;
41919         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41920         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41921         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41922         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41923           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41924             szPageDflt = ii;
41925           }
41926         }
41927       }
41928 #endif
41929     }
41930   }else{
41931     /* If a temporary file is requested, it is not opened immediately.
41932     ** In this case we accept the default page size and delay actually
41933     ** opening the file until the first call to OsWrite().
41934     **
41935     ** This branch is also run for an in-memory database. An in-memory
41936     ** database is the same as a temp-file that is never written out to
41937     ** disk and uses an in-memory rollback journal.
41938     */
41939     tempFile = 1;
41940     pPager->eState = PAGER_READER;
41941     pPager->eLock = EXCLUSIVE_LOCK;
41942     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
41943   }
41944 
41945   /* The following call to PagerSetPagesize() serves to set the value of
41946   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
41947   */
41948   if( rc==SQLITE_OK ){
41949     assert( pPager->memDb==0 );
41950     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
41951     testcase( rc!=SQLITE_OK );
41952   }
41953 
41954   /* If an error occurred in either of the blocks above, free the
41955   ** Pager structure and close the file.
41956   */
41957   if( rc!=SQLITE_OK ){
41958     assert( !pPager->pTmpSpace );
41959     sqlite3OsClose(pPager->fd);
41960     sqlite3_free(pPager);
41961     return rc;
41962   }
41963 
41964   /* Initialize the PCache object. */
41965   assert( nExtra<1000 );
41966   nExtra = ROUND8(nExtra);
41967   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
41968                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
41969 
41970   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
41971   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
41972 
41973   pPager->useJournal = (u8)useJournal;
41974   /* pPager->stmtOpen = 0; */
41975   /* pPager->stmtInUse = 0; */
41976   /* pPager->nRef = 0; */
41977   /* pPager->stmtSize = 0; */
41978   /* pPager->stmtJSize = 0; */
41979   /* pPager->nPage = 0; */
41980   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
41981   /* pPager->state = PAGER_UNLOCK; */
41982 #if 0
41983   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
41984 #endif
41985   /* pPager->errMask = 0; */
41986   pPager->tempFile = (u8)tempFile;
41987   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
41988           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
41989   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
41990   pPager->exclusiveMode = (u8)tempFile;
41991   pPager->changeCountDone = pPager->tempFile;
41992   pPager->memDb = (u8)memDb;
41993   pPager->readOnly = (u8)readOnly;
41994   assert( useJournal || pPager->tempFile );
41995   pPager->noSync = pPager->tempFile;
41996   if( pPager->noSync ){
41997     assert( pPager->fullSync==0 );
41998     assert( pPager->syncFlags==0 );
41999     assert( pPager->walSyncFlags==0 );
42000     assert( pPager->ckptSyncFlags==0 );
42001   }else{
42002     pPager->fullSync = 1;
42003     pPager->syncFlags = SQLITE_SYNC_NORMAL;
42004     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
42005     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
42006   }
42007   /* pPager->pFirst = 0; */
42008   /* pPager->pFirstSynced = 0; */
42009   /* pPager->pLast = 0; */
42010   pPager->nExtra = (u16)nExtra;
42011   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
42012   assert( isOpen(pPager->fd) || tempFile );
42013   setSectorSize(pPager);
42014   if( !useJournal ){
42015     pPager->journalMode = PAGER_JOURNALMODE_OFF;
42016   }else if( memDb ){
42017     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
42018   }
42019   /* pPager->xBusyHandler = 0; */
42020   /* pPager->pBusyHandlerArg = 0; */
42021   pPager->xReiniter = xReinit;
42022   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
42023 
42024   *ppPager = pPager;
42025   return SQLITE_OK;
42026 }
42027 
42028 
42029 
42030 /*
42031 ** This function is called after transitioning from PAGER_UNLOCK to
42032 ** PAGER_SHARED state. It tests if there is a hot journal present in
42033 ** the file-system for the given pager. A hot journal is one that
42034 ** needs to be played back. According to this function, a hot-journal
42035 ** file exists if the following criteria are met:
42036 **
42037 **   * The journal file exists in the file system, and
42038 **   * No process holds a RESERVED or greater lock on the database file, and
42039 **   * The database file itself is greater than 0 bytes in size, and
42040 **   * The first byte of the journal file exists and is not 0x00.
42041 **
42042 ** If the current size of the database file is 0 but a journal file
42043 ** exists, that is probably an old journal left over from a prior
42044 ** database with the same name. In this case the journal file is
42045 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
42046 ** is returned.
42047 **
42048 ** This routine does not check if there is a master journal filename
42049 ** at the end of the file. If there is, and that master journal file
42050 ** does not exist, then the journal file is not really hot. In this
42051 ** case this routine will return a false-positive. The pager_playback()
42052 ** routine will discover that the journal file is not really hot and
42053 ** will not roll it back.
42054 **
42055 ** If a hot-journal file is found to exist, *pExists is set to 1 and
42056 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
42057 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
42058 ** to determine whether or not a hot-journal file exists, the IO error
42059 ** code is returned and the value of *pExists is undefined.
42060 */
42061 static int hasHotJournal(Pager *pPager, int *pExists){
42062   sqlite3_vfs * const pVfs = pPager->pVfs;
42063   int rc = SQLITE_OK;           /* Return code */
42064   int exists = 1;               /* True if a journal file is present */
42065   int jrnlOpen = !!isOpen(pPager->jfd);
42066 
42067   assert( pPager->useJournal );
42068   assert( isOpen(pPager->fd) );
42069   assert( pPager->eState==PAGER_OPEN );
42070 
42071   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
42072     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
42073   ));
42074 
42075   *pExists = 0;
42076   if( !jrnlOpen ){
42077     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
42078   }
42079   if( rc==SQLITE_OK && exists ){
42080     int locked = 0;             /* True if some process holds a RESERVED lock */
42081 
42082     /* Race condition here:  Another process might have been holding the
42083     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
42084     ** call above, but then delete the journal and drop the lock before
42085     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
42086     ** is the case, this routine might think there is a hot journal when
42087     ** in fact there is none.  This results in a false-positive which will
42088     ** be dealt with by the playback routine.  Ticket #3883.
42089     */
42090     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
42091     if( rc==SQLITE_OK && !locked ){
42092       Pgno nPage;                 /* Number of pages in database file */
42093 
42094       /* Check the size of the database file. If it consists of 0 pages,
42095       ** then delete the journal file. See the header comment above for
42096       ** the reasoning here.  Delete the obsolete journal file under
42097       ** a RESERVED lock to avoid race conditions and to avoid violating
42098       ** [H33020].
42099       */
42100       rc = pagerPagecount(pPager, &nPage);
42101       if( rc==SQLITE_OK ){
42102         if( nPage==0 ){
42103           sqlite3BeginBenignMalloc();
42104           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
42105             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
42106             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
42107           }
42108           sqlite3EndBenignMalloc();
42109         }else{
42110           /* The journal file exists and no other connection has a reserved
42111           ** or greater lock on the database file. Now check that there is
42112           ** at least one non-zero bytes at the start of the journal file.
42113           ** If there is, then we consider this journal to be hot. If not,
42114           ** it can be ignored.
42115           */
42116           if( !jrnlOpen ){
42117             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
42118             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
42119           }
42120           if( rc==SQLITE_OK ){
42121             u8 first = 0;
42122             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
42123             if( rc==SQLITE_IOERR_SHORT_READ ){
42124               rc = SQLITE_OK;
42125             }
42126             if( !jrnlOpen ){
42127               sqlite3OsClose(pPager->jfd);
42128             }
42129             *pExists = (first!=0);
42130           }else if( rc==SQLITE_CANTOPEN ){
42131             /* If we cannot open the rollback journal file in order to see if
42132             ** its has a zero header, that might be due to an I/O error, or
42133             ** it might be due to the race condition described above and in
42134             ** ticket #3883.  Either way, assume that the journal is hot.
42135             ** This might be a false positive.  But if it is, then the
42136             ** automatic journal playback and recovery mechanism will deal
42137             ** with it under an EXCLUSIVE lock where we do not need to
42138             ** worry so much with race conditions.
42139             */
42140             *pExists = 1;
42141             rc = SQLITE_OK;
42142           }
42143         }
42144       }
42145     }
42146   }
42147 
42148   return rc;
42149 }
42150 
42151 /*
42152 ** This function is called to obtain a shared lock on the database file.
42153 ** It is illegal to call sqlite3PagerAcquire() until after this function
42154 ** has been successfully called. If a shared-lock is already held when
42155 ** this function is called, it is a no-op.
42156 **
42157 ** The following operations are also performed by this function.
42158 **
42159 **   1) If the pager is currently in PAGER_OPEN state (no lock held
42160 **      on the database file), then an attempt is made to obtain a
42161 **      SHARED lock on the database file. Immediately after obtaining
42162 **      the SHARED lock, the file-system is checked for a hot-journal,
42163 **      which is played back if present. Following any hot-journal
42164 **      rollback, the contents of the cache are validated by checking
42165 **      the 'change-counter' field of the database file header and
42166 **      discarded if they are found to be invalid.
42167 **
42168 **   2) If the pager is running in exclusive-mode, and there are currently
42169 **      no outstanding references to any pages, and is in the error state,
42170 **      then an attempt is made to clear the error state by discarding
42171 **      the contents of the page cache and rolling back any open journal
42172 **      file.
42173 **
42174 ** If everything is successful, SQLITE_OK is returned. If an IO error
42175 ** occurs while locking the database, checking for a hot-journal file or
42176 ** rolling back a journal file, the IO error code is returned.
42177 */
42178 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
42179   int rc = SQLITE_OK;                /* Return code */
42180 
42181   /* This routine is only called from b-tree and only when there are no
42182   ** outstanding pages. This implies that the pager state should either
42183   ** be OPEN or READER. READER is only possible if the pager is or was in
42184   ** exclusive access mode.
42185   */
42186   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
42187   assert( assert_pager_state(pPager) );
42188   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42189   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
42190 
42191   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
42192     int bHotJournal = 1;          /* True if there exists a hot journal-file */
42193 
42194     assert( !MEMDB );
42195 
42196     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
42197     if( rc!=SQLITE_OK ){
42198       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
42199       goto failed;
42200     }
42201 
42202     /* If a journal file exists, and there is no RESERVED lock on the
42203     ** database file, then it either needs to be played back or deleted.
42204     */
42205     if( pPager->eLock<=SHARED_LOCK ){
42206       rc = hasHotJournal(pPager, &bHotJournal);
42207     }
42208     if( rc!=SQLITE_OK ){
42209       goto failed;
42210     }
42211     if( bHotJournal ){
42212       if( pPager->readOnly ){
42213         rc = SQLITE_READONLY_ROLLBACK;
42214         goto failed;
42215       }
42216 
42217       /* Get an EXCLUSIVE lock on the database file. At this point it is
42218       ** important that a RESERVED lock is not obtained on the way to the
42219       ** EXCLUSIVE lock. If it were, another process might open the
42220       ** database file, detect the RESERVED lock, and conclude that the
42221       ** database is safe to read while this process is still rolling the
42222       ** hot-journal back.
42223       **
42224       ** Because the intermediate RESERVED lock is not requested, any
42225       ** other process attempting to access the database file will get to
42226       ** this point in the code and fail to obtain its own EXCLUSIVE lock
42227       ** on the database file.
42228       **
42229       ** Unless the pager is in locking_mode=exclusive mode, the lock is
42230       ** downgraded to SHARED_LOCK before this function returns.
42231       */
42232       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42233       if( rc!=SQLITE_OK ){
42234         goto failed;
42235       }
42236 
42237       /* If it is not already open and the file exists on disk, open the
42238       ** journal for read/write access. Write access is required because
42239       ** in exclusive-access mode the file descriptor will be kept open
42240       ** and possibly used for a transaction later on. Also, write-access
42241       ** is usually required to finalize the journal in journal_mode=persist
42242       ** mode (and also for journal_mode=truncate on some systems).
42243       **
42244       ** If the journal does not exist, it usually means that some
42245       ** other connection managed to get in and roll it back before
42246       ** this connection obtained the exclusive lock above. Or, it
42247       ** may mean that the pager was in the error-state when this
42248       ** function was called and the journal file does not exist.
42249       */
42250       if( !isOpen(pPager->jfd) ){
42251         sqlite3_vfs * const pVfs = pPager->pVfs;
42252         int bExists;              /* True if journal file exists */
42253         rc = sqlite3OsAccess(
42254             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
42255         if( rc==SQLITE_OK && bExists ){
42256           int fout = 0;
42257           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
42258           assert( !pPager->tempFile );
42259           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
42260           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42261           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
42262             rc = SQLITE_CANTOPEN_BKPT;
42263             sqlite3OsClose(pPager->jfd);
42264           }
42265         }
42266       }
42267 
42268       /* Playback and delete the journal.  Drop the database write
42269       ** lock and reacquire the read lock. Purge the cache before
42270       ** playing back the hot-journal so that we don't end up with
42271       ** an inconsistent cache.  Sync the hot journal before playing
42272       ** it back since the process that crashed and left the hot journal
42273       ** probably did not sync it and we are required to always sync
42274       ** the journal before playing it back.
42275       */
42276       if( isOpen(pPager->jfd) ){
42277         assert( rc==SQLITE_OK );
42278         rc = pagerSyncHotJournal(pPager);
42279         if( rc==SQLITE_OK ){
42280           rc = pager_playback(pPager, 1);
42281           pPager->eState = PAGER_OPEN;
42282         }
42283       }else if( !pPager->exclusiveMode ){
42284         pagerUnlockDb(pPager, SHARED_LOCK);
42285       }
42286 
42287       if( rc!=SQLITE_OK ){
42288         /* This branch is taken if an error occurs while trying to open
42289         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
42290         ** pager_unlock() routine will be called before returning to unlock
42291         ** the file. If the unlock attempt fails, then Pager.eLock must be
42292         ** set to UNKNOWN_LOCK (see the comment above the #define for
42293         ** UNKNOWN_LOCK above for an explanation).
42294         **
42295         ** In order to get pager_unlock() to do this, set Pager.eState to
42296         ** PAGER_ERROR now. This is not actually counted as a transition
42297         ** to ERROR state in the state diagram at the top of this file,
42298         ** since we know that the same call to pager_unlock() will very
42299         ** shortly transition the pager object to the OPEN state. Calling
42300         ** assert_pager_state() would fail now, as it should not be possible
42301         ** to be in ERROR state when there are zero outstanding page
42302         ** references.
42303         */
42304         pager_error(pPager, rc);
42305         goto failed;
42306       }
42307 
42308       assert( pPager->eState==PAGER_OPEN );
42309       assert( (pPager->eLock==SHARED_LOCK)
42310            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
42311       );
42312     }
42313 
42314     if( !pPager->tempFile
42315      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
42316     ){
42317       /* The shared-lock has just been acquired on the database file
42318       ** and there are already pages in the cache (from a previous
42319       ** read or write transaction).  Check to see if the database
42320       ** has been modified.  If the database has changed, flush the
42321       ** cache.
42322       **
42323       ** Database changes is detected by looking at 15 bytes beginning
42324       ** at offset 24 into the file.  The first 4 of these 16 bytes are
42325       ** a 32-bit counter that is incremented with each change.  The
42326       ** other bytes change randomly with each file change when
42327       ** a codec is in use.
42328       **
42329       ** There is a vanishingly small chance that a change will not be
42330       ** detected.  The chance of an undetected change is so small that
42331       ** it can be neglected.
42332       */
42333       Pgno nPage = 0;
42334       char dbFileVers[sizeof(pPager->dbFileVers)];
42335 
42336       rc = pagerPagecount(pPager, &nPage);
42337       if( rc ) goto failed;
42338 
42339       if( nPage>0 ){
42340         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
42341         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
42342         if( rc!=SQLITE_OK ){
42343           goto failed;
42344         }
42345       }else{
42346         memset(dbFileVers, 0, sizeof(dbFileVers));
42347       }
42348 
42349       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
42350         pager_reset(pPager);
42351       }
42352     }
42353 
42354     /* If there is a WAL file in the file-system, open this database in WAL
42355     ** mode. Otherwise, the following function call is a no-op.
42356     */
42357     rc = pagerOpenWalIfPresent(pPager);
42358 #ifndef SQLITE_OMIT_WAL
42359     assert( pPager->pWal==0 || rc==SQLITE_OK );
42360 #endif
42361   }
42362 
42363   if( pagerUseWal(pPager) ){
42364     assert( rc==SQLITE_OK );
42365     rc = pagerBeginReadTransaction(pPager);
42366   }
42367 
42368   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
42369     rc = pagerPagecount(pPager, &pPager->dbSize);
42370   }
42371 
42372  failed:
42373   if( rc!=SQLITE_OK ){
42374     assert( !MEMDB );
42375     pager_unlock(pPager);
42376     assert( pPager->eState==PAGER_OPEN );
42377   }else{
42378     pPager->eState = PAGER_READER;
42379   }
42380   return rc;
42381 }
42382 
42383 /*
42384 ** If the reference count has reached zero, rollback any active
42385 ** transaction and unlock the pager.
42386 **
42387 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
42388 ** the rollback journal, the unlock is not performed and there is
42389 ** nothing to rollback, so this routine is a no-op.
42390 */
42391 static void pagerUnlockIfUnused(Pager *pPager){
42392   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
42393     pagerUnlockAndRollback(pPager);
42394   }
42395 }
42396 
42397 /*
42398 ** Acquire a reference to page number pgno in pager pPager (a page
42399 ** reference has type DbPage*). If the requested reference is
42400 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
42401 **
42402 ** If the requested page is already in the cache, it is returned.
42403 ** Otherwise, a new page object is allocated and populated with data
42404 ** read from the database file. In some cases, the pcache module may
42405 ** choose not to allocate a new page object and may reuse an existing
42406 ** object with no outstanding references.
42407 **
42408 ** The extra data appended to a page is always initialized to zeros the
42409 ** first time a page is loaded into memory. If the page requested is
42410 ** already in the cache when this function is called, then the extra
42411 ** data is left as it was when the page object was last used.
42412 **
42413 ** If the database image is smaller than the requested page or if a
42414 ** non-zero value is passed as the noContent parameter and the
42415 ** requested page is not already stored in the cache, then no
42416 ** actual disk read occurs. In this case the memory image of the
42417 ** page is initialized to all zeros.
42418 **
42419 ** If noContent is true, it means that we do not care about the contents
42420 ** of the page. This occurs in two seperate scenarios:
42421 **
42422 **   a) When reading a free-list leaf page from the database, and
42423 **
42424 **   b) When a savepoint is being rolled back and we need to load
42425 **      a new page into the cache to be filled with the data read
42426 **      from the savepoint journal.
42427 **
42428 ** If noContent is true, then the data returned is zeroed instead of
42429 ** being read from the database. Additionally, the bits corresponding
42430 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
42431 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
42432 ** savepoints are set. This means if the page is made writable at any
42433 ** point in the future, using a call to sqlite3PagerWrite(), its contents
42434 ** will not be journaled. This saves IO.
42435 **
42436 ** The acquisition might fail for several reasons.  In all cases,
42437 ** an appropriate error code is returned and *ppPage is set to NULL.
42438 **
42439 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
42440 ** to find a page in the in-memory cache first.  If the page is not already
42441 ** in memory, this routine goes to disk to read it in whereas Lookup()
42442 ** just returns 0.  This routine acquires a read-lock the first time it
42443 ** has to go to disk, and could also playback an old journal if necessary.
42444 ** Since Lookup() never goes to disk, it never has to deal with locks
42445 ** or journal files.
42446 */
42447 SQLITE_PRIVATE int sqlite3PagerAcquire(
42448   Pager *pPager,      /* The pager open on the database file */
42449   Pgno pgno,          /* Page number to fetch */
42450   DbPage **ppPage,    /* Write a pointer to the page here */
42451   int noContent       /* Do not bother reading content from disk if true */
42452 ){
42453   int rc;
42454   PgHdr *pPg;
42455 
42456   assert( pPager->eState>=PAGER_READER );
42457   assert( assert_pager_state(pPager) );
42458 
42459   if( pgno==0 ){
42460     return SQLITE_CORRUPT_BKPT;
42461   }
42462 
42463   /* If the pager is in the error state, return an error immediately.
42464   ** Otherwise, request the page from the PCache layer. */
42465   if( pPager->errCode!=SQLITE_OK ){
42466     rc = pPager->errCode;
42467   }else{
42468     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
42469   }
42470 
42471   if( rc!=SQLITE_OK ){
42472     /* Either the call to sqlite3PcacheFetch() returned an error or the
42473     ** pager was already in the error-state when this function was called.
42474     ** Set pPg to 0 and jump to the exception handler.  */
42475     pPg = 0;
42476     goto pager_acquire_err;
42477   }
42478   assert( (*ppPage)->pgno==pgno );
42479   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
42480 
42481   if( (*ppPage)->pPager && !noContent ){
42482     /* In this case the pcache already contains an initialized copy of
42483     ** the page. Return without further ado.  */
42484     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
42485     pPager->aStat[PAGER_STAT_HIT]++;
42486     return SQLITE_OK;
42487 
42488   }else{
42489     /* The pager cache has created a new page. Its content needs to
42490     ** be initialized.  */
42491 
42492     pPg = *ppPage;
42493     pPg->pPager = pPager;
42494 
42495     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
42496     ** number greater than this, or the unused locking-page, is requested. */
42497     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
42498       rc = SQLITE_CORRUPT_BKPT;
42499       goto pager_acquire_err;
42500     }
42501 
42502     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
42503       if( pgno>pPager->mxPgno ){
42504         rc = SQLITE_FULL;
42505         goto pager_acquire_err;
42506       }
42507       if( noContent ){
42508         /* Failure to set the bits in the InJournal bit-vectors is benign.
42509         ** It merely means that we might do some extra work to journal a
42510         ** page that does not need to be journaled.  Nevertheless, be sure
42511         ** to test the case where a malloc error occurs while trying to set
42512         ** a bit in a bit vector.
42513         */
42514         sqlite3BeginBenignMalloc();
42515         if( pgno<=pPager->dbOrigSize ){
42516           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
42517           testcase( rc==SQLITE_NOMEM );
42518         }
42519         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
42520         testcase( rc==SQLITE_NOMEM );
42521         sqlite3EndBenignMalloc();
42522       }
42523       memset(pPg->pData, 0, pPager->pageSize);
42524       IOTRACE(("ZERO %p %d\n", pPager, pgno));
42525     }else{
42526       assert( pPg->pPager==pPager );
42527       pPager->aStat[PAGER_STAT_MISS]++;
42528       rc = readDbPage(pPg);
42529       if( rc!=SQLITE_OK ){
42530         goto pager_acquire_err;
42531       }
42532     }
42533     pager_set_pagehash(pPg);
42534   }
42535 
42536   return SQLITE_OK;
42537 
42538 pager_acquire_err:
42539   assert( rc!=SQLITE_OK );
42540   if( pPg ){
42541     sqlite3PcacheDrop(pPg);
42542   }
42543   pagerUnlockIfUnused(pPager);
42544 
42545   *ppPage = 0;
42546   return rc;
42547 }
42548 
42549 /*
42550 ** Acquire a page if it is already in the in-memory cache.  Do
42551 ** not read the page from disk.  Return a pointer to the page,
42552 ** or 0 if the page is not in cache.
42553 **
42554 ** See also sqlite3PagerGet().  The difference between this routine
42555 ** and sqlite3PagerGet() is that _get() will go to the disk and read
42556 ** in the page if the page is not already in cache.  This routine
42557 ** returns NULL if the page is not in cache or if a disk I/O error
42558 ** has ever happened.
42559 */
42560 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
42561   PgHdr *pPg = 0;
42562   assert( pPager!=0 );
42563   assert( pgno!=0 );
42564   assert( pPager->pPCache!=0 );
42565   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
42566   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
42567   return pPg;
42568 }
42569 
42570 /*
42571 ** Release a page reference.
42572 **
42573 ** If the number of references to the page drop to zero, then the
42574 ** page is added to the LRU list.  When all references to all pages
42575 ** are released, a rollback occurs and the lock on the database is
42576 ** removed.
42577 */
42578 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
42579   if( pPg ){
42580     Pager *pPager = pPg->pPager;
42581     sqlite3PcacheRelease(pPg);
42582     pagerUnlockIfUnused(pPager);
42583   }
42584 }
42585 
42586 /*
42587 ** This function is called at the start of every write transaction.
42588 ** There must already be a RESERVED or EXCLUSIVE lock on the database
42589 ** file when this routine is called.
42590 **
42591 ** Open the journal file for pager pPager and write a journal header
42592 ** to the start of it. If there are active savepoints, open the sub-journal
42593 ** as well. This function is only used when the journal file is being
42594 ** opened to write a rollback log for a transaction. It is not used
42595 ** when opening a hot journal file to roll it back.
42596 **
42597 ** If the journal file is already open (as it may be in exclusive mode),
42598 ** then this function just writes a journal header to the start of the
42599 ** already open file.
42600 **
42601 ** Whether or not the journal file is opened by this function, the
42602 ** Pager.pInJournal bitvec structure is allocated.
42603 **
42604 ** Return SQLITE_OK if everything is successful. Otherwise, return
42605 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
42606 ** an IO error code if opening or writing the journal file fails.
42607 */
42608 static int pager_open_journal(Pager *pPager){
42609   int rc = SQLITE_OK;                        /* Return code */
42610   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
42611 
42612   assert( pPager->eState==PAGER_WRITER_LOCKED );
42613   assert( assert_pager_state(pPager) );
42614   assert( pPager->pInJournal==0 );
42615 
42616   /* If already in the error state, this function is a no-op.  But on
42617   ** the other hand, this routine is never called if we are already in
42618   ** an error state. */
42619   if( NEVER(pPager->errCode) ) return pPager->errCode;
42620 
42621   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42622     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
42623     if( pPager->pInJournal==0 ){
42624       return SQLITE_NOMEM;
42625     }
42626 
42627     /* Open the journal file if it is not already open. */
42628     if( !isOpen(pPager->jfd) ){
42629       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
42630         sqlite3MemJournalOpen(pPager->jfd);
42631       }else{
42632         const int flags =                   /* VFS flags to open journal file */
42633           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42634           (pPager->tempFile ?
42635             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
42636             (SQLITE_OPEN_MAIN_JOURNAL)
42637           );
42638   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42639         rc = sqlite3JournalOpen(
42640             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
42641         );
42642   #else
42643         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
42644   #endif
42645       }
42646       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42647     }
42648 
42649 
42650     /* Write the first journal header to the journal file and open
42651     ** the sub-journal if necessary.
42652     */
42653     if( rc==SQLITE_OK ){
42654       /* TODO: Check if all of these are really required. */
42655       pPager->nRec = 0;
42656       pPager->journalOff = 0;
42657       pPager->setMaster = 0;
42658       pPager->journalHdr = 0;
42659       rc = writeJournalHdr(pPager);
42660     }
42661   }
42662 
42663   if( rc!=SQLITE_OK ){
42664     sqlite3BitvecDestroy(pPager->pInJournal);
42665     pPager->pInJournal = 0;
42666   }else{
42667     assert( pPager->eState==PAGER_WRITER_LOCKED );
42668     pPager->eState = PAGER_WRITER_CACHEMOD;
42669   }
42670 
42671   return rc;
42672 }
42673 
42674 /*
42675 ** Begin a write-transaction on the specified pager object. If a
42676 ** write-transaction has already been opened, this function is a no-op.
42677 **
42678 ** If the exFlag argument is false, then acquire at least a RESERVED
42679 ** lock on the database file. If exFlag is true, then acquire at least
42680 ** an EXCLUSIVE lock. If such a lock is already held, no locking
42681 ** functions need be called.
42682 **
42683 ** If the subjInMemory argument is non-zero, then any sub-journal opened
42684 ** within this transaction will be opened as an in-memory file. This
42685 ** has no effect if the sub-journal is already opened (as it may be when
42686 ** running in exclusive mode) or if the transaction does not require a
42687 ** sub-journal. If the subjInMemory argument is zero, then any required
42688 ** sub-journal is implemented in-memory if pPager is an in-memory database,
42689 ** or using a temporary file otherwise.
42690 */
42691 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42692   int rc = SQLITE_OK;
42693 
42694   if( pPager->errCode ) return pPager->errCode;
42695   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42696   pPager->subjInMemory = (u8)subjInMemory;
42697 
42698   if( ALWAYS(pPager->eState==PAGER_READER) ){
42699     assert( pPager->pInJournal==0 );
42700 
42701     if( pagerUseWal(pPager) ){
42702       /* If the pager is configured to use locking_mode=exclusive, and an
42703       ** exclusive lock on the database is not already held, obtain it now.
42704       */
42705       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42706         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42707         if( rc!=SQLITE_OK ){
42708           return rc;
42709         }
42710         sqlite3WalExclusiveMode(pPager->pWal, 1);
42711       }
42712 
42713       /* Grab the write lock on the log file. If successful, upgrade to
42714       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42715       ** The busy-handler is not invoked if another connection already
42716       ** holds the write-lock. If possible, the upper layer will call it.
42717       */
42718       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42719     }else{
42720       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42721       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42722       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42723       ** lock, but not when obtaining the RESERVED lock.
42724       */
42725       rc = pagerLockDb(pPager, RESERVED_LOCK);
42726       if( rc==SQLITE_OK && exFlag ){
42727         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42728       }
42729     }
42730 
42731     if( rc==SQLITE_OK ){
42732       /* Change to WRITER_LOCKED state.
42733       **
42734       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42735       ** when it has an open transaction, but never to DBMOD or FINISHED.
42736       ** This is because in those states the code to roll back savepoint
42737       ** transactions may copy data from the sub-journal into the database
42738       ** file as well as into the page cache. Which would be incorrect in
42739       ** WAL mode.
42740       */
42741       pPager->eState = PAGER_WRITER_LOCKED;
42742       pPager->dbHintSize = pPager->dbSize;
42743       pPager->dbFileSize = pPager->dbSize;
42744       pPager->dbOrigSize = pPager->dbSize;
42745       pPager->journalOff = 0;
42746     }
42747 
42748     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42749     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42750     assert( assert_pager_state(pPager) );
42751   }
42752 
42753   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42754   return rc;
42755 }
42756 
42757 /*
42758 ** Mark a single data page as writeable. The page is written into the
42759 ** main journal or sub-journal as required. If the page is written into
42760 ** one of the journals, the corresponding bit is set in the
42761 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42762 ** of any open savepoints as appropriate.
42763 */
42764 static int pager_write(PgHdr *pPg){
42765   void *pData = pPg->pData;
42766   Pager *pPager = pPg->pPager;
42767   int rc = SQLITE_OK;
42768 
42769   /* This routine is not called unless a write-transaction has already
42770   ** been started. The journal file may or may not be open at this point.
42771   ** It is never called in the ERROR state.
42772   */
42773   assert( pPager->eState==PAGER_WRITER_LOCKED
42774        || pPager->eState==PAGER_WRITER_CACHEMOD
42775        || pPager->eState==PAGER_WRITER_DBMOD
42776   );
42777   assert( assert_pager_state(pPager) );
42778 
42779   /* If an error has been previously detected, report the same error
42780   ** again. This should not happen, but the check provides robustness. */
42781   if( NEVER(pPager->errCode) )  return pPager->errCode;
42782 
42783   /* Higher-level routines never call this function if database is not
42784   ** writable.  But check anyway, just for robustness. */
42785   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42786 
42787   CHECK_PAGE(pPg);
42788 
42789   /* The journal file needs to be opened. Higher level routines have already
42790   ** obtained the necessary locks to begin the write-transaction, but the
42791   ** rollback journal might not yet be open. Open it now if this is the case.
42792   **
42793   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
42794   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42795   ** an error might occur and the pager would end up in WRITER_LOCKED state
42796   ** with pages marked as dirty in the cache.
42797   */
42798   if( pPager->eState==PAGER_WRITER_LOCKED ){
42799     rc = pager_open_journal(pPager);
42800     if( rc!=SQLITE_OK ) return rc;
42801   }
42802   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42803   assert( assert_pager_state(pPager) );
42804 
42805   /* Mark the page as dirty.  If the page has already been written
42806   ** to the journal then we can return right away.
42807   */
42808   sqlite3PcacheMakeDirty(pPg);
42809   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42810     assert( !pagerUseWal(pPager) );
42811   }else{
42812 
42813     /* The transaction journal now exists and we have a RESERVED or an
42814     ** EXCLUSIVE lock on the main database file.  Write the current page to
42815     ** the transaction journal if it is not there already.
42816     */
42817     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42818       assert( pagerUseWal(pPager)==0 );
42819       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42820         u32 cksum;
42821         char *pData2;
42822         i64 iOff = pPager->journalOff;
42823 
42824         /* We should never write to the journal file the page that
42825         ** contains the database locks.  The following assert verifies
42826         ** that we do not. */
42827         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42828 
42829         assert( pPager->journalHdr<=pPager->journalOff );
42830         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42831         cksum = pager_cksum(pPager, (u8*)pData2);
42832 
42833         /* Even if an IO or diskfull error occurs while journalling the
42834         ** page in the block above, set the need-sync flag for the page.
42835         ** Otherwise, when the transaction is rolled back, the logic in
42836         ** playback_one_page() will think that the page needs to be restored
42837         ** in the database file. And if an IO error occurs while doing so,
42838         ** then corruption may follow.
42839         */
42840         pPg->flags |= PGHDR_NEED_SYNC;
42841 
42842         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42843         if( rc!=SQLITE_OK ) return rc;
42844         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42845         if( rc!=SQLITE_OK ) return rc;
42846         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42847         if( rc!=SQLITE_OK ) return rc;
42848 
42849         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
42850                  pPager->journalOff, pPager->pageSize));
42851         PAGER_INCR(sqlite3_pager_writej_count);
42852         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42853              PAGERID(pPager), pPg->pgno,
42854              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42855 
42856         pPager->journalOff += 8 + pPager->pageSize;
42857         pPager->nRec++;
42858         assert( pPager->pInJournal!=0 );
42859         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42860         testcase( rc==SQLITE_NOMEM );
42861         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42862         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42863         if( rc!=SQLITE_OK ){
42864           assert( rc==SQLITE_NOMEM );
42865           return rc;
42866         }
42867       }else{
42868         if( pPager->eState!=PAGER_WRITER_DBMOD ){
42869           pPg->flags |= PGHDR_NEED_SYNC;
42870         }
42871         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42872                 PAGERID(pPager), pPg->pgno,
42873                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42874       }
42875     }
42876 
42877     /* If the statement journal is open and the page is not in it,
42878     ** then write the current page to the statement journal.  Note that
42879     ** the statement journal format differs from the standard journal format
42880     ** in that it omits the checksums and the header.
42881     */
42882     if( subjRequiresPage(pPg) ){
42883       rc = subjournalPage(pPg);
42884     }
42885   }
42886 
42887   /* Update the database size and return.
42888   */
42889   if( pPager->dbSize<pPg->pgno ){
42890     pPager->dbSize = pPg->pgno;
42891   }
42892   return rc;
42893 }
42894 
42895 /*
42896 ** Mark a data page as writeable. This routine must be called before
42897 ** making changes to a page. The caller must check the return value
42898 ** of this function and be careful not to change any page data unless
42899 ** this routine returns SQLITE_OK.
42900 **
42901 ** The difference between this function and pager_write() is that this
42902 ** function also deals with the special case where 2 or more pages
42903 ** fit on a single disk sector. In this case all co-resident pages
42904 ** must have been written to the journal file before returning.
42905 **
42906 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42907 ** as appropriate. Otherwise, SQLITE_OK.
42908 */
42909 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42910   int rc = SQLITE_OK;
42911 
42912   PgHdr *pPg = pDbPage;
42913   Pager *pPager = pPg->pPager;
42914   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42915 
42916   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42917   assert( pPager->eState!=PAGER_ERROR );
42918   assert( assert_pager_state(pPager) );
42919 
42920   if( nPagePerSector>1 ){
42921     Pgno nPageCount;          /* Total number of pages in database file */
42922     Pgno pg1;                 /* First page of the sector pPg is located on. */
42923     int nPage = 0;            /* Number of pages starting at pg1 to journal */
42924     int ii;                   /* Loop counter */
42925     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
42926 
42927     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42928     ** a journal header to be written between the pages journaled by
42929     ** this function.
42930     */
42931     assert( !MEMDB );
42932     assert( pPager->doNotSyncSpill==0 );
42933     pPager->doNotSyncSpill++;
42934 
42935     /* This trick assumes that both the page-size and sector-size are
42936     ** an integer power of 2. It sets variable pg1 to the identifier
42937     ** of the first page of the sector pPg is located on.
42938     */
42939     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42940 
42941     nPageCount = pPager->dbSize;
42942     if( pPg->pgno>nPageCount ){
42943       nPage = (pPg->pgno - pg1)+1;
42944     }else if( (pg1+nPagePerSector-1)>nPageCount ){
42945       nPage = nPageCount+1-pg1;
42946     }else{
42947       nPage = nPagePerSector;
42948     }
42949     assert(nPage>0);
42950     assert(pg1<=pPg->pgno);
42951     assert((pg1+nPage)>pPg->pgno);
42952 
42953     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
42954       Pgno pg = pg1+ii;
42955       PgHdr *pPage;
42956       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
42957         if( pg!=PAGER_MJ_PGNO(pPager) ){
42958           rc = sqlite3PagerGet(pPager, pg, &pPage);
42959           if( rc==SQLITE_OK ){
42960             rc = pager_write(pPage);
42961             if( pPage->flags&PGHDR_NEED_SYNC ){
42962               needSync = 1;
42963             }
42964             sqlite3PagerUnref(pPage);
42965           }
42966         }
42967       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
42968         if( pPage->flags&PGHDR_NEED_SYNC ){
42969           needSync = 1;
42970         }
42971         sqlite3PagerUnref(pPage);
42972       }
42973     }
42974 
42975     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
42976     ** starting at pg1, then it needs to be set for all of them. Because
42977     ** writing to any of these nPage pages may damage the others, the
42978     ** journal file must contain sync()ed copies of all of them
42979     ** before any of them can be written out to the database file.
42980     */
42981     if( rc==SQLITE_OK && needSync ){
42982       assert( !MEMDB );
42983       for(ii=0; ii<nPage; ii++){
42984         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42985         if( pPage ){
42986           pPage->flags |= PGHDR_NEED_SYNC;
42987           sqlite3PagerUnref(pPage);
42988         }
42989       }
42990     }
42991 
42992     assert( pPager->doNotSyncSpill==1 );
42993     pPager->doNotSyncSpill--;
42994   }else{
42995     rc = pager_write(pDbPage);
42996   }
42997   return rc;
42998 }
42999 
43000 /*
43001 ** Return TRUE if the page given in the argument was previously passed
43002 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
43003 ** to change the content of the page.
43004 */
43005 #ifndef NDEBUG
43006 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
43007   return pPg->flags&PGHDR_DIRTY;
43008 }
43009 #endif
43010 
43011 /*
43012 ** A call to this routine tells the pager that it is not necessary to
43013 ** write the information on page pPg back to the disk, even though
43014 ** that page might be marked as dirty.  This happens, for example, when
43015 ** the page has been added as a leaf of the freelist and so its
43016 ** content no longer matters.
43017 **
43018 ** The overlying software layer calls this routine when all of the data
43019 ** on the given page is unused. The pager marks the page as clean so
43020 ** that it does not get written to disk.
43021 **
43022 ** Tests show that this optimization can quadruple the speed of large
43023 ** DELETE operations.
43024 */
43025 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
43026   Pager *pPager = pPg->pPager;
43027   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
43028     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
43029     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
43030     pPg->flags |= PGHDR_DONT_WRITE;
43031     pager_set_pagehash(pPg);
43032   }
43033 }
43034 
43035 /*
43036 ** This routine is called to increment the value of the database file
43037 ** change-counter, stored as a 4-byte big-endian integer starting at
43038 ** byte offset 24 of the pager file.  The secondary change counter at
43039 ** 92 is also updated, as is the SQLite version number at offset 96.
43040 **
43041 ** But this only happens if the pPager->changeCountDone flag is false.
43042 ** To avoid excess churning of page 1, the update only happens once.
43043 ** See also the pager_write_changecounter() routine that does an
43044 ** unconditional update of the change counters.
43045 **
43046 ** If the isDirectMode flag is zero, then this is done by calling
43047 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
43048 ** page data. In this case the file will be updated when the current
43049 ** transaction is committed.
43050 **
43051 ** The isDirectMode flag may only be non-zero if the library was compiled
43052 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
43053 ** if isDirect is non-zero, then the database file is updated directly
43054 ** by writing an updated version of page 1 using a call to the
43055 ** sqlite3OsWrite() function.
43056 */
43057 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
43058   int rc = SQLITE_OK;
43059 
43060   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43061        || pPager->eState==PAGER_WRITER_DBMOD
43062   );
43063   assert( assert_pager_state(pPager) );
43064 
43065   /* Declare and initialize constant integer 'isDirect'. If the
43066   ** atomic-write optimization is enabled in this build, then isDirect
43067   ** is initialized to the value passed as the isDirectMode parameter
43068   ** to this function. Otherwise, it is always set to zero.
43069   **
43070   ** The idea is that if the atomic-write optimization is not
43071   ** enabled at compile time, the compiler can omit the tests of
43072   ** 'isDirect' below, as well as the block enclosed in the
43073   ** "if( isDirect )" condition.
43074   */
43075 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
43076 # define DIRECT_MODE 0
43077   assert( isDirectMode==0 );
43078   UNUSED_PARAMETER(isDirectMode);
43079 #else
43080 # define DIRECT_MODE isDirectMode
43081 #endif
43082 
43083   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
43084     PgHdr *pPgHdr;                /* Reference to page 1 */
43085 
43086     assert( !pPager->tempFile && isOpen(pPager->fd) );
43087 
43088     /* Open page 1 of the file for writing. */
43089     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
43090     assert( pPgHdr==0 || rc==SQLITE_OK );
43091 
43092     /* If page one was fetched successfully, and this function is not
43093     ** operating in direct-mode, make page 1 writable.  When not in
43094     ** direct mode, page 1 is always held in cache and hence the PagerGet()
43095     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
43096     */
43097     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
43098       rc = sqlite3PagerWrite(pPgHdr);
43099     }
43100 
43101     if( rc==SQLITE_OK ){
43102       /* Actually do the update of the change counter */
43103       pager_write_changecounter(pPgHdr);
43104 
43105       /* If running in direct mode, write the contents of page 1 to the file. */
43106       if( DIRECT_MODE ){
43107         const void *zBuf;
43108         assert( pPager->dbFileSize>0 );
43109         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
43110         if( rc==SQLITE_OK ){
43111           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
43112           pPager->aStat[PAGER_STAT_WRITE]++;
43113         }
43114         if( rc==SQLITE_OK ){
43115           pPager->changeCountDone = 1;
43116         }
43117       }else{
43118         pPager->changeCountDone = 1;
43119       }
43120     }
43121 
43122     /* Release the page reference. */
43123     sqlite3PagerUnref(pPgHdr);
43124   }
43125   return rc;
43126 }
43127 
43128 /*
43129 ** Sync the database file to disk. This is a no-op for in-memory databases
43130 ** or pages with the Pager.noSync flag set.
43131 **
43132 ** If successful, or if called on a pager for which it is a no-op, this
43133 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
43134 */
43135 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
43136   int rc = SQLITE_OK;
43137   if( !pPager->noSync ){
43138     assert( !MEMDB );
43139     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
43140   }else if( isOpen(pPager->fd) ){
43141     assert( !MEMDB );
43142     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
43143     if( rc==SQLITE_NOTFOUND ){
43144       rc = SQLITE_OK;
43145     }
43146   }
43147   return rc;
43148 }
43149 
43150 /*
43151 ** This function may only be called while a write-transaction is active in
43152 ** rollback. If the connection is in WAL mode, this call is a no-op.
43153 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
43154 ** the database file, an attempt is made to obtain one.
43155 **
43156 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
43157 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
43158 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
43159 ** returned.
43160 */
43161 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
43162   int rc = SQLITE_OK;
43163   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43164        || pPager->eState==PAGER_WRITER_DBMOD
43165        || pPager->eState==PAGER_WRITER_LOCKED
43166   );
43167   assert( assert_pager_state(pPager) );
43168   if( 0==pagerUseWal(pPager) ){
43169     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43170   }
43171   return rc;
43172 }
43173 
43174 /*
43175 ** Sync the database file for the pager pPager. zMaster points to the name
43176 ** of a master journal file that should be written into the individual
43177 ** journal file. zMaster may be NULL, which is interpreted as no master
43178 ** journal (a single database transaction).
43179 **
43180 ** This routine ensures that:
43181 **
43182 **   * The database file change-counter is updated,
43183 **   * the journal is synced (unless the atomic-write optimization is used),
43184 **   * all dirty pages are written to the database file,
43185 **   * the database file is truncated (if required), and
43186 **   * the database file synced.
43187 **
43188 ** The only thing that remains to commit the transaction is to finalize
43189 ** (delete, truncate or zero the first part of) the journal file (or
43190 ** delete the master journal file if specified).
43191 **
43192 ** Note that if zMaster==NULL, this does not overwrite a previous value
43193 ** passed to an sqlite3PagerCommitPhaseOne() call.
43194 **
43195 ** If the final parameter - noSync - is true, then the database file itself
43196 ** is not synced. The caller must call sqlite3PagerSync() directly to
43197 ** sync the database file before calling CommitPhaseTwo() to delete the
43198 ** journal file in this case.
43199 */
43200 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
43201   Pager *pPager,                  /* Pager object */
43202   const char *zMaster,            /* If not NULL, the master journal name */
43203   int noSync                      /* True to omit the xSync on the db file */
43204 ){
43205   int rc = SQLITE_OK;             /* Return code */
43206 
43207   assert( pPager->eState==PAGER_WRITER_LOCKED
43208        || pPager->eState==PAGER_WRITER_CACHEMOD
43209        || pPager->eState==PAGER_WRITER_DBMOD
43210        || pPager->eState==PAGER_ERROR
43211   );
43212   assert( assert_pager_state(pPager) );
43213 
43214   /* If a prior error occurred, report that error again. */
43215   if( NEVER(pPager->errCode) ) return pPager->errCode;
43216 
43217   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
43218       pPager->zFilename, zMaster, pPager->dbSize));
43219 
43220   /* If no database changes have been made, return early. */
43221   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
43222 
43223   if( MEMDB ){
43224     /* If this is an in-memory db, or no pages have been written to, or this
43225     ** function has already been called, it is mostly a no-op.  However, any
43226     ** backup in progress needs to be restarted.
43227     */
43228     sqlite3BackupRestart(pPager->pBackup);
43229   }else{
43230     if( pagerUseWal(pPager) ){
43231       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
43232       PgHdr *pPageOne = 0;
43233       if( pList==0 ){
43234         /* Must have at least one page for the WAL commit flag.
43235         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
43236         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
43237         pList = pPageOne;
43238         pList->pDirty = 0;
43239       }
43240       assert( rc==SQLITE_OK );
43241       if( ALWAYS(pList) ){
43242         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
43243       }
43244       sqlite3PagerUnref(pPageOne);
43245       if( rc==SQLITE_OK ){
43246         sqlite3PcacheCleanAll(pPager->pPCache);
43247       }
43248     }else{
43249       /* The following block updates the change-counter. Exactly how it
43250       ** does this depends on whether or not the atomic-update optimization
43251       ** was enabled at compile time, and if this transaction meets the
43252       ** runtime criteria to use the operation:
43253       **
43254       **    * The file-system supports the atomic-write property for
43255       **      blocks of size page-size, and
43256       **    * This commit is not part of a multi-file transaction, and
43257       **    * Exactly one page has been modified and store in the journal file.
43258       **
43259       ** If the optimization was not enabled at compile time, then the
43260       ** pager_incr_changecounter() function is called to update the change
43261       ** counter in 'indirect-mode'. If the optimization is compiled in but
43262       ** is not applicable to this transaction, call sqlite3JournalCreate()
43263       ** to make sure the journal file has actually been created, then call
43264       ** pager_incr_changecounter() to update the change-counter in indirect
43265       ** mode.
43266       **
43267       ** Otherwise, if the optimization is both enabled and applicable,
43268       ** then call pager_incr_changecounter() to update the change-counter
43269       ** in 'direct' mode. In this case the journal file will never be
43270       ** created for this transaction.
43271       */
43272   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43273       PgHdr *pPg;
43274       assert( isOpen(pPager->jfd)
43275            || pPager->journalMode==PAGER_JOURNALMODE_OFF
43276            || pPager->journalMode==PAGER_JOURNALMODE_WAL
43277       );
43278       if( !zMaster && isOpen(pPager->jfd)
43279        && pPager->journalOff==jrnlBufferSize(pPager)
43280        && pPager->dbSize>=pPager->dbOrigSize
43281        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
43282       ){
43283         /* Update the db file change counter via the direct-write method. The
43284         ** following call will modify the in-memory representation of page 1
43285         ** to include the updated change counter and then write page 1
43286         ** directly to the database file. Because of the atomic-write
43287         ** property of the host file-system, this is safe.
43288         */
43289         rc = pager_incr_changecounter(pPager, 1);
43290       }else{
43291         rc = sqlite3JournalCreate(pPager->jfd);
43292         if( rc==SQLITE_OK ){
43293           rc = pager_incr_changecounter(pPager, 0);
43294         }
43295       }
43296   #else
43297       rc = pager_incr_changecounter(pPager, 0);
43298   #endif
43299       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43300 
43301       /* Write the master journal name into the journal file. If a master
43302       ** journal file name has already been written to the journal file,
43303       ** or if zMaster is NULL (no master journal), then this call is a no-op.
43304       */
43305       rc = writeMasterJournal(pPager, zMaster);
43306       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43307 
43308       /* Sync the journal file and write all dirty pages to the database.
43309       ** If the atomic-update optimization is being used, this sync will not
43310       ** create the journal file or perform any real IO.
43311       **
43312       ** Because the change-counter page was just modified, unless the
43313       ** atomic-update optimization is used it is almost certain that the
43314       ** journal requires a sync here. However, in locking_mode=exclusive
43315       ** on a system under memory pressure it is just possible that this is
43316       ** not the case. In this case it is likely enough that the redundant
43317       ** xSync() call will be changed to a no-op by the OS anyhow.
43318       */
43319       rc = syncJournal(pPager, 0);
43320       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43321 
43322       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
43323       if( rc!=SQLITE_OK ){
43324         assert( rc!=SQLITE_IOERR_BLOCKED );
43325         goto commit_phase_one_exit;
43326       }
43327       sqlite3PcacheCleanAll(pPager->pPCache);
43328 
43329       /* If the file on disk is smaller than the database image, use
43330       ** pager_truncate to grow the file here. This can happen if the database
43331       ** image was extended as part of the current transaction and then the
43332       ** last page in the db image moved to the free-list. In this case the
43333       ** last page is never written out to disk, leaving the database file
43334       ** undersized. Fix this now if it is the case.  */
43335       if( pPager->dbSize>pPager->dbFileSize ){
43336         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
43337         assert( pPager->eState==PAGER_WRITER_DBMOD );
43338         rc = pager_truncate(pPager, nNew);
43339         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43340       }
43341 
43342       /* Finally, sync the database file. */
43343       if( !noSync ){
43344         rc = sqlite3PagerSync(pPager);
43345       }
43346       IOTRACE(("DBSYNC %p\n", pPager))
43347     }
43348   }
43349 
43350 commit_phase_one_exit:
43351   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
43352     pPager->eState = PAGER_WRITER_FINISHED;
43353   }
43354   return rc;
43355 }
43356 
43357 
43358 /*
43359 ** When this function is called, the database file has been completely
43360 ** updated to reflect the changes made by the current transaction and
43361 ** synced to disk. The journal file still exists in the file-system
43362 ** though, and if a failure occurs at this point it will eventually
43363 ** be used as a hot-journal and the current transaction rolled back.
43364 **
43365 ** This function finalizes the journal file, either by deleting,
43366 ** truncating or partially zeroing it, so that it cannot be used
43367 ** for hot-journal rollback. Once this is done the transaction is
43368 ** irrevocably committed.
43369 **
43370 ** If an error occurs, an IO error code is returned and the pager
43371 ** moves into the error state. Otherwise, SQLITE_OK is returned.
43372 */
43373 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
43374   int rc = SQLITE_OK;                  /* Return code */
43375 
43376   /* This routine should not be called if a prior error has occurred.
43377   ** But if (due to a coding error elsewhere in the system) it does get
43378   ** called, just return the same error code without doing anything. */
43379   if( NEVER(pPager->errCode) ) return pPager->errCode;
43380 
43381   assert( pPager->eState==PAGER_WRITER_LOCKED
43382        || pPager->eState==PAGER_WRITER_FINISHED
43383        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
43384   );
43385   assert( assert_pager_state(pPager) );
43386 
43387   /* An optimization. If the database was not actually modified during
43388   ** this transaction, the pager is running in exclusive-mode and is
43389   ** using persistent journals, then this function is a no-op.
43390   **
43391   ** The start of the journal file currently contains a single journal
43392   ** header with the nRec field set to 0. If such a journal is used as
43393   ** a hot-journal during hot-journal rollback, 0 changes will be made
43394   ** to the database file. So there is no need to zero the journal
43395   ** header. Since the pager is in exclusive mode, there is no need
43396   ** to drop any locks either.
43397   */
43398   if( pPager->eState==PAGER_WRITER_LOCKED
43399    && pPager->exclusiveMode
43400    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43401   ){
43402     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
43403     pPager->eState = PAGER_READER;
43404     return SQLITE_OK;
43405   }
43406 
43407   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
43408   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
43409   return pager_error(pPager, rc);
43410 }
43411 
43412 /*
43413 ** If a write transaction is open, then all changes made within the
43414 ** transaction are reverted and the current write-transaction is closed.
43415 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
43416 ** state if an error occurs.
43417 **
43418 ** If the pager is already in PAGER_ERROR state when this function is called,
43419 ** it returns Pager.errCode immediately. No work is performed in this case.
43420 **
43421 ** Otherwise, in rollback mode, this function performs two functions:
43422 **
43423 **   1) It rolls back the journal file, restoring all database file and
43424 **      in-memory cache pages to the state they were in when the transaction
43425 **      was opened, and
43426 **
43427 **   2) It finalizes the journal file, so that it is not used for hot
43428 **      rollback at any point in the future.
43429 **
43430 ** Finalization of the journal file (task 2) is only performed if the
43431 ** rollback is successful.
43432 **
43433 ** In WAL mode, all cache-entries containing data modified within the
43434 ** current transaction are either expelled from the cache or reverted to
43435 ** their pre-transaction state by re-reading data from the database or
43436 ** WAL files. The WAL transaction is then closed.
43437 */
43438 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
43439   int rc = SQLITE_OK;                  /* Return code */
43440   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
43441 
43442   /* PagerRollback() is a no-op if called in READER or OPEN state. If
43443   ** the pager is already in the ERROR state, the rollback is not
43444   ** attempted here. Instead, the error code is returned to the caller.
43445   */
43446   assert( assert_pager_state(pPager) );
43447   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
43448   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
43449 
43450   if( pagerUseWal(pPager) ){
43451     int rc2;
43452     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
43453     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
43454     if( rc==SQLITE_OK ) rc = rc2;
43455   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
43456     int eState = pPager->eState;
43457     rc = pager_end_transaction(pPager, 0, 0);
43458     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
43459       /* This can happen using journal_mode=off. Move the pager to the error
43460       ** state to indicate that the contents of the cache may not be trusted.
43461       ** Any active readers will get SQLITE_ABORT.
43462       */
43463       pPager->errCode = SQLITE_ABORT;
43464       pPager->eState = PAGER_ERROR;
43465       return rc;
43466     }
43467   }else{
43468     rc = pager_playback(pPager, 0);
43469   }
43470 
43471   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
43472   assert( rc==SQLITE_OK || rc==SQLITE_FULL
43473           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
43474 
43475   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
43476   ** cache. So call pager_error() on the way out to make any error persistent.
43477   */
43478   return pager_error(pPager, rc);
43479 }
43480 
43481 /*
43482 ** Return TRUE if the database file is opened read-only.  Return FALSE
43483 ** if the database is (in theory) writable.
43484 */
43485 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
43486   return pPager->readOnly;
43487 }
43488 
43489 /*
43490 ** Return the number of references to the pager.
43491 */
43492 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
43493   return sqlite3PcacheRefCount(pPager->pPCache);
43494 }
43495 
43496 /*
43497 ** Return the approximate number of bytes of memory currently
43498 ** used by the pager and its associated cache.
43499 */
43500 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
43501   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
43502                                      + 5*sizeof(void*);
43503   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
43504            + sqlite3MallocSize(pPager)
43505            + pPager->pageSize;
43506 }
43507 
43508 /*
43509 ** Return the number of references to the specified page.
43510 */
43511 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
43512   return sqlite3PcachePageRefcount(pPage);
43513 }
43514 
43515 #ifdef SQLITE_TEST
43516 /*
43517 ** This routine is used for testing and analysis only.
43518 */
43519 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
43520   static int a[11];
43521   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
43522   a[1] = sqlite3PcachePagecount(pPager->pPCache);
43523   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
43524   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
43525   a[4] = pPager->eState;
43526   a[5] = pPager->errCode;
43527   a[6] = pPager->aStat[PAGER_STAT_HIT];
43528   a[7] = pPager->aStat[PAGER_STAT_MISS];
43529   a[8] = 0;  /* Used to be pPager->nOvfl */
43530   a[9] = pPager->nRead;
43531   a[10] = pPager->aStat[PAGER_STAT_WRITE];
43532   return a;
43533 }
43534 #endif
43535 
43536 /*
43537 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
43538 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
43539 ** current cache hit or miss count, according to the value of eStat. If the
43540 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
43541 ** returning.
43542 */
43543 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
43544 
43545   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
43546        || eStat==SQLITE_DBSTATUS_CACHE_MISS
43547        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
43548   );
43549 
43550   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
43551   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
43552   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
43553 
43554   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
43555   if( reset ){
43556     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
43557   }
43558 }
43559 
43560 /*
43561 ** Return true if this is an in-memory pager.
43562 */
43563 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
43564   return MEMDB;
43565 }
43566 
43567 /*
43568 ** Check that there are at least nSavepoint savepoints open. If there are
43569 ** currently less than nSavepoints open, then open one or more savepoints
43570 ** to make up the difference. If the number of savepoints is already
43571 ** equal to nSavepoint, then this function is a no-op.
43572 **
43573 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
43574 ** occurs while opening the sub-journal file, then an IO error code is
43575 ** returned. Otherwise, SQLITE_OK.
43576 */
43577 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
43578   int rc = SQLITE_OK;                       /* Return code */
43579   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
43580 
43581   assert( pPager->eState>=PAGER_WRITER_LOCKED );
43582   assert( assert_pager_state(pPager) );
43583 
43584   if( nSavepoint>nCurrent && pPager->useJournal ){
43585     int ii;                                 /* Iterator variable */
43586     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
43587 
43588     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
43589     ** if the allocation fails. Otherwise, zero the new portion in case a
43590     ** malloc failure occurs while populating it in the for(...) loop below.
43591     */
43592     aNew = (PagerSavepoint *)sqlite3Realloc(
43593         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
43594     );
43595     if( !aNew ){
43596       return SQLITE_NOMEM;
43597     }
43598     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
43599     pPager->aSavepoint = aNew;
43600 
43601     /* Populate the PagerSavepoint structures just allocated. */
43602     for(ii=nCurrent; ii<nSavepoint; ii++){
43603       aNew[ii].nOrig = pPager->dbSize;
43604       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
43605         aNew[ii].iOffset = pPager->journalOff;
43606       }else{
43607         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
43608       }
43609       aNew[ii].iSubRec = pPager->nSubRec;
43610       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
43611       if( !aNew[ii].pInSavepoint ){
43612         return SQLITE_NOMEM;
43613       }
43614       if( pagerUseWal(pPager) ){
43615         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
43616       }
43617       pPager->nSavepoint = ii+1;
43618     }
43619     assert( pPager->nSavepoint==nSavepoint );
43620     assertTruncateConstraint(pPager);
43621   }
43622 
43623   return rc;
43624 }
43625 
43626 /*
43627 ** This function is called to rollback or release (commit) a savepoint.
43628 ** The savepoint to release or rollback need not be the most recently
43629 ** created savepoint.
43630 **
43631 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
43632 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
43633 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
43634 ** that have occurred since the specified savepoint was created.
43635 **
43636 ** The savepoint to rollback or release is identified by parameter
43637 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
43638 ** (the first created). A value of (Pager.nSavepoint-1) means operate
43639 ** on the most recently created savepoint. If iSavepoint is greater than
43640 ** (Pager.nSavepoint-1), then this function is a no-op.
43641 **
43642 ** If a negative value is passed to this function, then the current
43643 ** transaction is rolled back. This is different to calling
43644 ** sqlite3PagerRollback() because this function does not terminate
43645 ** the transaction or unlock the database, it just restores the
43646 ** contents of the database to its original state.
43647 **
43648 ** In any case, all savepoints with an index greater than iSavepoint
43649 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
43650 ** then savepoint iSavepoint is also destroyed.
43651 **
43652 ** This function may return SQLITE_NOMEM if a memory allocation fails,
43653 ** or an IO error code if an IO error occurs while rolling back a
43654 ** savepoint. If no errors occur, SQLITE_OK is returned.
43655 */
43656 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
43657   int rc = pPager->errCode;       /* Return code */
43658 
43659   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
43660   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
43661 
43662   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
43663     int ii;            /* Iterator variable */
43664     int nNew;          /* Number of remaining savepoints after this op. */
43665 
43666     /* Figure out how many savepoints will still be active after this
43667     ** operation. Store this value in nNew. Then free resources associated
43668     ** with any savepoints that are destroyed by this operation.
43669     */
43670     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
43671     for(ii=nNew; ii<pPager->nSavepoint; ii++){
43672       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43673     }
43674     pPager->nSavepoint = nNew;
43675 
43676     /* If this is a release of the outermost savepoint, truncate
43677     ** the sub-journal to zero bytes in size. */
43678     if( op==SAVEPOINT_RELEASE ){
43679       if( nNew==0 && isOpen(pPager->sjfd) ){
43680         /* Only truncate if it is an in-memory sub-journal. */
43681         if( sqlite3IsMemJournal(pPager->sjfd) ){
43682           rc = sqlite3OsTruncate(pPager->sjfd, 0);
43683           assert( rc==SQLITE_OK );
43684         }
43685         pPager->nSubRec = 0;
43686       }
43687     }
43688     /* Else this is a rollback operation, playback the specified savepoint.
43689     ** If this is a temp-file, it is possible that the journal file has
43690     ** not yet been opened. In this case there have been no changes to
43691     ** the database file, so the playback operation can be skipped.
43692     */
43693     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43694       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43695       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43696       assert(rc!=SQLITE_DONE);
43697     }
43698   }
43699 
43700   return rc;
43701 }
43702 
43703 /*
43704 ** Return the full pathname of the database file.
43705 **
43706 ** Except, if the pager is in-memory only, then return an empty string if
43707 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
43708 ** used to report the filename to the user, for compatibility with legacy
43709 ** behavior.  But when the Btree needs to know the filename for matching to
43710 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
43711 ** participate in shared-cache.
43712 */
43713 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
43714   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
43715 }
43716 
43717 /*
43718 ** Return the VFS structure for the pager.
43719 */
43720 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43721   return pPager->pVfs;
43722 }
43723 
43724 /*
43725 ** Return the file handle for the database file associated
43726 ** with the pager.  This might return NULL if the file has
43727 ** not yet been opened.
43728 */
43729 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43730   return pPager->fd;
43731 }
43732 
43733 /*
43734 ** Return the full pathname of the journal file.
43735 */
43736 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43737   return pPager->zJournal;
43738 }
43739 
43740 /*
43741 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
43742 ** if fsync()s are executed normally.
43743 */
43744 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43745   return pPager->noSync;
43746 }
43747 
43748 #ifdef SQLITE_HAS_CODEC
43749 /*
43750 ** Set or retrieve the codec for this pager
43751 */
43752 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43753   Pager *pPager,
43754   void *(*xCodec)(void*,void*,Pgno,int),
43755   void (*xCodecSizeChng)(void*,int,int),
43756   void (*xCodecFree)(void*),
43757   void *pCodec
43758 ){
43759   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43760   pPager->xCodec = pPager->memDb ? 0 : xCodec;
43761   pPager->xCodecSizeChng = xCodecSizeChng;
43762   pPager->xCodecFree = xCodecFree;
43763   pPager->pCodec = pCodec;
43764   pagerReportSize(pPager);
43765 }
43766 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43767   return pPager->pCodec;
43768 }
43769 #endif
43770 
43771 #ifndef SQLITE_OMIT_AUTOVACUUM
43772 /*
43773 ** Move the page pPg to location pgno in the file.
43774 **
43775 ** There must be no references to the page previously located at
43776 ** pgno (which we call pPgOld) though that page is allowed to be
43777 ** in cache.  If the page previously located at pgno is not already
43778 ** in the rollback journal, it is not put there by by this routine.
43779 **
43780 ** References to the page pPg remain valid. Updating any
43781 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43782 ** allocated along with the page) is the responsibility of the caller.
43783 **
43784 ** A transaction must be active when this routine is called. It used to be
43785 ** required that a statement transaction was not active, but this restriction
43786 ** has been removed (CREATE INDEX needs to move a page when a statement
43787 ** transaction is active).
43788 **
43789 ** If the fourth argument, isCommit, is non-zero, then this page is being
43790 ** moved as part of a database reorganization just before the transaction
43791 ** is being committed. In this case, it is guaranteed that the database page
43792 ** pPg refers to will not be written to again within this transaction.
43793 **
43794 ** This function may return SQLITE_NOMEM or an IO error code if an error
43795 ** occurs. Otherwise, it returns SQLITE_OK.
43796 */
43797 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43798   PgHdr *pPgOld;               /* The page being overwritten. */
43799   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
43800   int rc;                      /* Return code */
43801   Pgno origPgno;               /* The original page number */
43802 
43803   assert( pPg->nRef>0 );
43804   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43805        || pPager->eState==PAGER_WRITER_DBMOD
43806   );
43807   assert( assert_pager_state(pPager) );
43808 
43809   /* In order to be able to rollback, an in-memory database must journal
43810   ** the page we are moving from.
43811   */
43812   if( MEMDB ){
43813     rc = sqlite3PagerWrite(pPg);
43814     if( rc ) return rc;
43815   }
43816 
43817   /* If the page being moved is dirty and has not been saved by the latest
43818   ** savepoint, then save the current contents of the page into the
43819   ** sub-journal now. This is required to handle the following scenario:
43820   **
43821   **   BEGIN;
43822   **     <journal page X, then modify it in memory>
43823   **     SAVEPOINT one;
43824   **       <Move page X to location Y>
43825   **     ROLLBACK TO one;
43826   **
43827   ** If page X were not written to the sub-journal here, it would not
43828   ** be possible to restore its contents when the "ROLLBACK TO one"
43829   ** statement were is processed.
43830   **
43831   ** subjournalPage() may need to allocate space to store pPg->pgno into
43832   ** one or more savepoint bitvecs. This is the reason this function
43833   ** may return SQLITE_NOMEM.
43834   */
43835   if( pPg->flags&PGHDR_DIRTY
43836    && subjRequiresPage(pPg)
43837    && SQLITE_OK!=(rc = subjournalPage(pPg))
43838   ){
43839     return rc;
43840   }
43841 
43842   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
43843       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43844   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43845 
43846   /* If the journal needs to be sync()ed before page pPg->pgno can
43847   ** be written to, store pPg->pgno in local variable needSyncPgno.
43848   **
43849   ** If the isCommit flag is set, there is no need to remember that
43850   ** the journal needs to be sync()ed before database page pPg->pgno
43851   ** can be written to. The caller has already promised not to write to it.
43852   */
43853   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43854     needSyncPgno = pPg->pgno;
43855     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
43856             pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43857     assert( pPg->flags&PGHDR_DIRTY );
43858   }
43859 
43860   /* If the cache contains a page with page-number pgno, remove it
43861   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
43862   ** page pgno before the 'move' operation, it needs to be retained
43863   ** for the page moved there.
43864   */
43865   pPg->flags &= ~PGHDR_NEED_SYNC;
43866   pPgOld = pager_lookup(pPager, pgno);
43867   assert( !pPgOld || pPgOld->nRef==1 );
43868   if( pPgOld ){
43869     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43870     if( MEMDB ){
43871       /* Do not discard pages from an in-memory database since we might
43872       ** need to rollback later.  Just move the page out of the way. */
43873       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43874     }else{
43875       sqlite3PcacheDrop(pPgOld);
43876     }
43877   }
43878 
43879   origPgno = pPg->pgno;
43880   sqlite3PcacheMove(pPg, pgno);
43881   sqlite3PcacheMakeDirty(pPg);
43882 
43883   /* For an in-memory database, make sure the original page continues
43884   ** to exist, in case the transaction needs to roll back.  Use pPgOld
43885   ** as the original page since it has already been allocated.
43886   */
43887   if( MEMDB ){
43888     assert( pPgOld );
43889     sqlite3PcacheMove(pPgOld, origPgno);
43890     sqlite3PagerUnref(pPgOld);
43891   }
43892 
43893   if( needSyncPgno ){
43894     /* If needSyncPgno is non-zero, then the journal file needs to be
43895     ** sync()ed before any data is written to database file page needSyncPgno.
43896     ** Currently, no such page exists in the page-cache and the
43897     ** "is journaled" bitvec flag has been set. This needs to be remedied by
43898     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43899     ** flag.
43900     **
43901     ** If the attempt to load the page into the page-cache fails, (due
43902     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43903     ** array. Otherwise, if the page is loaded and written again in
43904     ** this transaction, it may be written to the database file before
43905     ** it is synced into the journal file. This way, it may end up in
43906     ** the journal file twice, but that is not a problem.
43907     */
43908     PgHdr *pPgHdr;
43909     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43910     if( rc!=SQLITE_OK ){
43911       if( needSyncPgno<=pPager->dbOrigSize ){
43912         assert( pPager->pTmpSpace!=0 );
43913         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43914       }
43915       return rc;
43916     }
43917     pPgHdr->flags |= PGHDR_NEED_SYNC;
43918     sqlite3PcacheMakeDirty(pPgHdr);
43919     sqlite3PagerUnref(pPgHdr);
43920   }
43921 
43922   return SQLITE_OK;
43923 }
43924 #endif
43925 
43926 /*
43927 ** Return a pointer to the data for the specified page.
43928 */
43929 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43930   assert( pPg->nRef>0 || pPg->pPager->memDb );
43931   return pPg->pData;
43932 }
43933 
43934 /*
43935 ** Return a pointer to the Pager.nExtra bytes of "extra" space
43936 ** allocated along with the specified page.
43937 */
43938 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43939   return pPg->pExtra;
43940 }
43941 
43942 /*
43943 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43944 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
43945 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43946 ** the locking-mode is set to the value specified.
43947 **
43948 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43949 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43950 ** locking-mode.
43951 */
43952 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43953   assert( eMode==PAGER_LOCKINGMODE_QUERY
43954             || eMode==PAGER_LOCKINGMODE_NORMAL
43955             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43956   assert( PAGER_LOCKINGMODE_QUERY<0 );
43957   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43958   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43959   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43960     pPager->exclusiveMode = (u8)eMode;
43961   }
43962   return (int)pPager->exclusiveMode;
43963 }
43964 
43965 /*
43966 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43967 **
43968 **    PAGER_JOURNALMODE_DELETE
43969 **    PAGER_JOURNALMODE_TRUNCATE
43970 **    PAGER_JOURNALMODE_PERSIST
43971 **    PAGER_JOURNALMODE_OFF
43972 **    PAGER_JOURNALMODE_MEMORY
43973 **    PAGER_JOURNALMODE_WAL
43974 **
43975 ** The journalmode is set to the value specified if the change is allowed.
43976 ** The change may be disallowed for the following reasons:
43977 **
43978 **   *  An in-memory database can only have its journal_mode set to _OFF
43979 **      or _MEMORY.
43980 **
43981 **   *  Temporary databases cannot have _WAL journalmode.
43982 **
43983 ** The returned indicate the current (possibly updated) journal-mode.
43984 */
43985 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43986   u8 eOld = pPager->journalMode;    /* Prior journalmode */
43987 
43988 #ifdef SQLITE_DEBUG
43989   /* The print_pager_state() routine is intended to be used by the debugger
43990   ** only.  We invoke it once here to suppress a compiler warning. */
43991   print_pager_state(pPager);
43992 #endif
43993 
43994 
43995   /* The eMode parameter is always valid */
43996   assert(      eMode==PAGER_JOURNALMODE_DELETE
43997             || eMode==PAGER_JOURNALMODE_TRUNCATE
43998             || eMode==PAGER_JOURNALMODE_PERSIST
43999             || eMode==PAGER_JOURNALMODE_OFF
44000             || eMode==PAGER_JOURNALMODE_WAL
44001             || eMode==PAGER_JOURNALMODE_MEMORY );
44002 
44003   /* This routine is only called from the OP_JournalMode opcode, and
44004   ** the logic there will never allow a temporary file to be changed
44005   ** to WAL mode.
44006   */
44007   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
44008 
44009   /* Do allow the journalmode of an in-memory database to be set to
44010   ** anything other than MEMORY or OFF
44011   */
44012   if( MEMDB ){
44013     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
44014     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
44015       eMode = eOld;
44016     }
44017   }
44018 
44019   if( eMode!=eOld ){
44020 
44021     /* Change the journal mode. */
44022     assert( pPager->eState!=PAGER_ERROR );
44023     pPager->journalMode = (u8)eMode;
44024 
44025     /* When transistioning from TRUNCATE or PERSIST to any other journal
44026     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
44027     ** delete the journal file.
44028     */
44029     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
44030     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
44031     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
44032     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
44033     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
44034     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
44035 
44036     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
44037     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
44038 
44039       /* In this case we would like to delete the journal file. If it is
44040       ** not possible, then that is not a problem. Deleting the journal file
44041       ** here is an optimization only.
44042       **
44043       ** Before deleting the journal file, obtain a RESERVED lock on the
44044       ** database file. This ensures that the journal file is not deleted
44045       ** while it is in use by some other client.
44046       */
44047       sqlite3OsClose(pPager->jfd);
44048       if( pPager->eLock>=RESERVED_LOCK ){
44049         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44050       }else{
44051         int rc = SQLITE_OK;
44052         int state = pPager->eState;
44053         assert( state==PAGER_OPEN || state==PAGER_READER );
44054         if( state==PAGER_OPEN ){
44055           rc = sqlite3PagerSharedLock(pPager);
44056         }
44057         if( pPager->eState==PAGER_READER ){
44058           assert( rc==SQLITE_OK );
44059           rc = pagerLockDb(pPager, RESERVED_LOCK);
44060         }
44061         if( rc==SQLITE_OK ){
44062           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44063         }
44064         if( rc==SQLITE_OK && state==PAGER_READER ){
44065           pagerUnlockDb(pPager, SHARED_LOCK);
44066         }else if( state==PAGER_OPEN ){
44067           pager_unlock(pPager);
44068         }
44069         assert( state==pPager->eState );
44070       }
44071     }
44072   }
44073 
44074   /* Return the new journal mode */
44075   return (int)pPager->journalMode;
44076 }
44077 
44078 /*
44079 ** Return the current journal mode.
44080 */
44081 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
44082   return (int)pPager->journalMode;
44083 }
44084 
44085 /*
44086 ** Return TRUE if the pager is in a state where it is OK to change the
44087 ** journalmode.  Journalmode changes can only happen when the database
44088 ** is unmodified.
44089 */
44090 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
44091   assert( assert_pager_state(pPager) );
44092   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
44093   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
44094   return 1;
44095 }
44096 
44097 /*
44098 ** Get/set the size-limit used for persistent journal files.
44099 **
44100 ** Setting the size limit to -1 means no limit is enforced.
44101 ** An attempt to set a limit smaller than -1 is a no-op.
44102 */
44103 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
44104   if( iLimit>=-1 ){
44105     pPager->journalSizeLimit = iLimit;
44106     sqlite3WalLimit(pPager->pWal, iLimit);
44107   }
44108   return pPager->journalSizeLimit;
44109 }
44110 
44111 /*
44112 ** Return a pointer to the pPager->pBackup variable. The backup module
44113 ** in backup.c maintains the content of this variable. This module
44114 ** uses it opaquely as an argument to sqlite3BackupRestart() and
44115 ** sqlite3BackupUpdate() only.
44116 */
44117 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
44118   return &pPager->pBackup;
44119 }
44120 
44121 #ifndef SQLITE_OMIT_VACUUM
44122 /*
44123 ** Unless this is an in-memory or temporary database, clear the pager cache.
44124 */
44125 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
44126   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
44127 }
44128 #endif
44129 
44130 #ifndef SQLITE_OMIT_WAL
44131 /*
44132 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
44133 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
44134 ** or wal_blocking_checkpoint() API functions.
44135 **
44136 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
44137 */
44138 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
44139   int rc = SQLITE_OK;
44140   if( pPager->pWal ){
44141     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
44142         pPager->xBusyHandler, pPager->pBusyHandlerArg,
44143         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
44144         pnLog, pnCkpt
44145     );
44146   }
44147   return rc;
44148 }
44149 
44150 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
44151   return sqlite3WalCallback(pPager->pWal);
44152 }
44153 
44154 /*
44155 ** Return true if the underlying VFS for the given pager supports the
44156 ** primitives necessary for write-ahead logging.
44157 */
44158 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
44159   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
44160   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
44161 }
44162 
44163 /*
44164 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
44165 ** is obtained instead, immediately release it.
44166 */
44167 static int pagerExclusiveLock(Pager *pPager){
44168   int rc;                         /* Return code */
44169 
44170   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44171   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44172   if( rc!=SQLITE_OK ){
44173     /* If the attempt to grab the exclusive lock failed, release the
44174     ** pending lock that may have been obtained instead.  */
44175     pagerUnlockDb(pPager, SHARED_LOCK);
44176   }
44177 
44178   return rc;
44179 }
44180 
44181 /*
44182 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
44183 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
44184 ** lock on the database file and use heap-memory to store the wal-index
44185 ** in. Otherwise, use the normal shared-memory.
44186 */
44187 static int pagerOpenWal(Pager *pPager){
44188   int rc = SQLITE_OK;
44189 
44190   assert( pPager->pWal==0 && pPager->tempFile==0 );
44191   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44192 
44193   /* If the pager is already in exclusive-mode, the WAL module will use
44194   ** heap-memory for the wal-index instead of the VFS shared-memory
44195   ** implementation. Take the exclusive lock now, before opening the WAL
44196   ** file, to make sure this is safe.
44197   */
44198   if( pPager->exclusiveMode ){
44199     rc = pagerExclusiveLock(pPager);
44200   }
44201 
44202   /* Open the connection to the log file. If this operation fails,
44203   ** (e.g. due to malloc() failure), return an error code.
44204   */
44205   if( rc==SQLITE_OK ){
44206     rc = sqlite3WalOpen(pPager->pVfs,
44207         pPager->fd, pPager->zWal, pPager->exclusiveMode,
44208         pPager->journalSizeLimit, &pPager->pWal
44209     );
44210   }
44211 
44212   return rc;
44213 }
44214 
44215 
44216 /*
44217 ** The caller must be holding a SHARED lock on the database file to call
44218 ** this function.
44219 **
44220 ** If the pager passed as the first argument is open on a real database
44221 ** file (not a temp file or an in-memory database), and the WAL file
44222 ** is not already open, make an attempt to open it now. If successful,
44223 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
44224 ** not support the xShmXXX() methods, return an error code. *pbOpen is
44225 ** not modified in either case.
44226 **
44227 ** If the pager is open on a temp-file (or in-memory database), or if
44228 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
44229 ** without doing anything.
44230 */
44231 SQLITE_PRIVATE int sqlite3PagerOpenWal(
44232   Pager *pPager,                  /* Pager object */
44233   int *pbOpen                     /* OUT: Set to true if call is a no-op */
44234 ){
44235   int rc = SQLITE_OK;             /* Return code */
44236 
44237   assert( assert_pager_state(pPager) );
44238   assert( pPager->eState==PAGER_OPEN   || pbOpen );
44239   assert( pPager->eState==PAGER_READER || !pbOpen );
44240   assert( pbOpen==0 || *pbOpen==0 );
44241   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
44242 
44243   if( !pPager->tempFile && !pPager->pWal ){
44244     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
44245 
44246     /* Close any rollback journal previously open */
44247     sqlite3OsClose(pPager->jfd);
44248 
44249     rc = pagerOpenWal(pPager);
44250     if( rc==SQLITE_OK ){
44251       pPager->journalMode = PAGER_JOURNALMODE_WAL;
44252       pPager->eState = PAGER_OPEN;
44253     }
44254   }else{
44255     *pbOpen = 1;
44256   }
44257 
44258   return rc;
44259 }
44260 
44261 /*
44262 ** This function is called to close the connection to the log file prior
44263 ** to switching from WAL to rollback mode.
44264 **
44265 ** Before closing the log file, this function attempts to take an
44266 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
44267 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
44268 ** If successful, the EXCLUSIVE lock is not released before returning.
44269 */
44270 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
44271   int rc = SQLITE_OK;
44272 
44273   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
44274 
44275   /* If the log file is not already open, but does exist in the file-system,
44276   ** it may need to be checkpointed before the connection can switch to
44277   ** rollback mode. Open it now so this can happen.
44278   */
44279   if( !pPager->pWal ){
44280     int logexists = 0;
44281     rc = pagerLockDb(pPager, SHARED_LOCK);
44282     if( rc==SQLITE_OK ){
44283       rc = sqlite3OsAccess(
44284           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
44285       );
44286     }
44287     if( rc==SQLITE_OK && logexists ){
44288       rc = pagerOpenWal(pPager);
44289     }
44290   }
44291 
44292   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
44293   ** the database file, the log and log-summary files will be deleted.
44294   */
44295   if( rc==SQLITE_OK && pPager->pWal ){
44296     rc = pagerExclusiveLock(pPager);
44297     if( rc==SQLITE_OK ){
44298       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
44299                            pPager->pageSize, (u8*)pPager->pTmpSpace);
44300       pPager->pWal = 0;
44301     }
44302   }
44303   return rc;
44304 }
44305 
44306 #endif /* !SQLITE_OMIT_WAL */
44307 
44308 #ifdef SQLITE_ENABLE_ZIPVFS
44309 /*
44310 ** A read-lock must be held on the pager when this function is called. If
44311 ** the pager is in WAL mode and the WAL file currently contains one or more
44312 ** frames, return the size in bytes of the page images stored within the
44313 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
44314 ** is empty, return 0.
44315 */
44316 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
44317   assert( pPager->eState==PAGER_READER );
44318   return sqlite3WalFramesize(pPager->pWal);
44319 }
44320 #endif
44321 
44322 #ifdef SQLITE_HAS_CODEC
44323 /*
44324 ** This function is called by the wal module when writing page content
44325 ** into the log file.
44326 **
44327 ** This function returns a pointer to a buffer containing the encrypted
44328 ** page content. If a malloc fails, this function may return NULL.
44329 */
44330 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44331   void *aData = 0;
44332   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44333   return aData;
44334 }
44335 #endif /* SQLITE_HAS_CODEC */
44336 
44337 #endif /* SQLITE_OMIT_DISKIO */
44338 
44339 /************** End of pager.c ***********************************************/
44340 /************** Begin file wal.c *********************************************/
44341 /*
44342 ** 2010 February 1
44343 **
44344 ** The author disclaims copyright to this source code.  In place of
44345 ** a legal notice, here is a blessing:
44346 **
44347 **    May you do good and not evil.
44348 **    May you find forgiveness for yourself and forgive others.
44349 **    May you share freely, never taking more than you give.
44350 **
44351 *************************************************************************
44352 **
44353 ** This file contains the implementation of a write-ahead log (WAL) used in
44354 ** "journal_mode=WAL" mode.
44355 **
44356 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
44357 **
44358 ** A WAL file consists of a header followed by zero or more "frames".
44359 ** Each frame records the revised content of a single page from the
44360 ** database file.  All changes to the database are recorded by writing
44361 ** frames into the WAL.  Transactions commit when a frame is written that
44362 ** contains a commit marker.  A single WAL can and usually does record
44363 ** multiple transactions.  Periodically, the content of the WAL is
44364 ** transferred back into the database file in an operation called a
44365 ** "checkpoint".
44366 **
44367 ** A single WAL file can be used multiple times.  In other words, the
44368 ** WAL can fill up with frames and then be checkpointed and then new
44369 ** frames can overwrite the old ones.  A WAL always grows from beginning
44370 ** toward the end.  Checksums and counters attached to each frame are
44371 ** used to determine which frames within the WAL are valid and which
44372 ** are leftovers from prior checkpoints.
44373 **
44374 ** The WAL header is 32 bytes in size and consists of the following eight
44375 ** big-endian 32-bit unsigned integer values:
44376 **
44377 **     0: Magic number.  0x377f0682 or 0x377f0683
44378 **     4: File format version.  Currently 3007000
44379 **     8: Database page size.  Example: 1024
44380 **    12: Checkpoint sequence number
44381 **    16: Salt-1, random integer incremented with each checkpoint
44382 **    20: Salt-2, a different random integer changing with each ckpt
44383 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
44384 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
44385 **
44386 ** Immediately following the wal-header are zero or more frames. Each
44387 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
44388 ** of page data. The frame-header is six big-endian 32-bit unsigned
44389 ** integer values, as follows:
44390 **
44391 **     0: Page number.
44392 **     4: For commit records, the size of the database image in pages
44393 **        after the commit. For all other records, zero.
44394 **     8: Salt-1 (copied from the header)
44395 **    12: Salt-2 (copied from the header)
44396 **    16: Checksum-1.
44397 **    20: Checksum-2.
44398 **
44399 ** A frame is considered valid if and only if the following conditions are
44400 ** true:
44401 **
44402 **    (1) The salt-1 and salt-2 values in the frame-header match
44403 **        salt values in the wal-header
44404 **
44405 **    (2) The checksum values in the final 8 bytes of the frame-header
44406 **        exactly match the checksum computed consecutively on the
44407 **        WAL header and the first 8 bytes and the content of all frames
44408 **        up to and including the current frame.
44409 **
44410 ** The checksum is computed using 32-bit big-endian integers if the
44411 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
44412 ** is computed using little-endian if the magic number is 0x377f0682.
44413 ** The checksum values are always stored in the frame header in a
44414 ** big-endian format regardless of which byte order is used to compute
44415 ** the checksum.  The checksum is computed by interpreting the input as
44416 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
44417 ** algorithm used for the checksum is as follows:
44418 **
44419 **   for i from 0 to n-1 step 2:
44420 **     s0 += x[i] + s1;
44421 **     s1 += x[i+1] + s0;
44422 **   endfor
44423 **
44424 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
44425 ** in reverse order (the largest fibonacci weight occurs on the first element
44426 ** of the sequence being summed.)  The s1 value spans all 32-bit
44427 ** terms of the sequence whereas s0 omits the final term.
44428 **
44429 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
44430 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
44431 ** The VFS.xSync operations serve as write barriers - all writes launched
44432 ** before the xSync must complete before any write that launches after the
44433 ** xSync begins.
44434 **
44435 ** After each checkpoint, the salt-1 value is incremented and the salt-2
44436 ** value is randomized.  This prevents old and new frames in the WAL from
44437 ** being considered valid at the same time and being checkpointing together
44438 ** following a crash.
44439 **
44440 ** READER ALGORITHM
44441 **
44442 ** To read a page from the database (call it page number P), a reader
44443 ** first checks the WAL to see if it contains page P.  If so, then the
44444 ** last valid instance of page P that is a followed by a commit frame
44445 ** or is a commit frame itself becomes the value read.  If the WAL
44446 ** contains no copies of page P that are valid and which are a commit
44447 ** frame or are followed by a commit frame, then page P is read from
44448 ** the database file.
44449 **
44450 ** To start a read transaction, the reader records the index of the last
44451 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
44452 ** for all subsequent read operations.  New transactions can be appended
44453 ** to the WAL, but as long as the reader uses its original mxFrame value
44454 ** and ignores the newly appended content, it will see a consistent snapshot
44455 ** of the database from a single point in time.  This technique allows
44456 ** multiple concurrent readers to view different versions of the database
44457 ** content simultaneously.
44458 **
44459 ** The reader algorithm in the previous paragraphs works correctly, but
44460 ** because frames for page P can appear anywhere within the WAL, the
44461 ** reader has to scan the entire WAL looking for page P frames.  If the
44462 ** WAL is large (multiple megabytes is typical) that scan can be slow,
44463 ** and read performance suffers.  To overcome this problem, a separate
44464 ** data structure called the wal-index is maintained to expedite the
44465 ** search for frames of a particular page.
44466 **
44467 ** WAL-INDEX FORMAT
44468 **
44469 ** Conceptually, the wal-index is shared memory, though VFS implementations
44470 ** might choose to implement the wal-index using a mmapped file.  Because
44471 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
44472 ** on a network filesystem.  All users of the database must be able to
44473 ** share memory.
44474 **
44475 ** The wal-index is transient.  After a crash, the wal-index can (and should
44476 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
44477 ** to either truncate or zero the header of the wal-index when the last
44478 ** connection to it closes.  Because the wal-index is transient, it can
44479 ** use an architecture-specific format; it does not have to be cross-platform.
44480 ** Hence, unlike the database and WAL file formats which store all values
44481 ** as big endian, the wal-index can store multi-byte values in the native
44482 ** byte order of the host computer.
44483 **
44484 ** The purpose of the wal-index is to answer this question quickly:  Given
44485 ** a page number P and a maximum frame index M, return the index of the
44486 ** last frame in the wal before frame M for page P in the WAL, or return
44487 ** NULL if there are no frames for page P in the WAL prior to M.
44488 **
44489 ** The wal-index consists of a header region, followed by an one or
44490 ** more index blocks.
44491 **
44492 ** The wal-index header contains the total number of frames within the WAL
44493 ** in the mxFrame field.
44494 **
44495 ** Each index block except for the first contains information on
44496 ** HASHTABLE_NPAGE frames. The first index block contains information on
44497 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
44498 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
44499 ** first index block are the same size as all other index blocks in the
44500 ** wal-index.
44501 **
44502 ** Each index block contains two sections, a page-mapping that contains the
44503 ** database page number associated with each wal frame, and a hash-table
44504 ** that allows readers to query an index block for a specific page number.
44505 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
44506 ** for the first index block) 32-bit page numbers. The first entry in the
44507 ** first index-block contains the database page number corresponding to the
44508 ** first frame in the WAL file. The first entry in the second index block
44509 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
44510 ** the log, and so on.
44511 **
44512 ** The last index block in a wal-index usually contains less than the full
44513 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
44514 ** depending on the contents of the WAL file. This does not change the
44515 ** allocated size of the page-mapping array - the page-mapping array merely
44516 ** contains unused entries.
44517 **
44518 ** Even without using the hash table, the last frame for page P
44519 ** can be found by scanning the page-mapping sections of each index block
44520 ** starting with the last index block and moving toward the first, and
44521 ** within each index block, starting at the end and moving toward the
44522 ** beginning.  The first entry that equals P corresponds to the frame
44523 ** holding the content for that page.
44524 **
44525 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
44526 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
44527 ** hash table for each page number in the mapping section, so the hash
44528 ** table is never more than half full.  The expected number of collisions
44529 ** prior to finding a match is 1.  Each entry of the hash table is an
44530 ** 1-based index of an entry in the mapping section of the same
44531 ** index block.   Let K be the 1-based index of the largest entry in
44532 ** the mapping section.  (For index blocks other than the last, K will
44533 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
44534 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
44535 ** contain a value of 0.
44536 **
44537 ** To look for page P in the hash table, first compute a hash iKey on
44538 ** P as follows:
44539 **
44540 **      iKey = (P * 383) % HASHTABLE_NSLOT
44541 **
44542 ** Then start scanning entries of the hash table, starting with iKey
44543 ** (wrapping around to the beginning when the end of the hash table is
44544 ** reached) until an unused hash slot is found. Let the first unused slot
44545 ** be at index iUnused.  (iUnused might be less than iKey if there was
44546 ** wrap-around.) Because the hash table is never more than half full,
44547 ** the search is guaranteed to eventually hit an unused entry.  Let
44548 ** iMax be the value between iKey and iUnused, closest to iUnused,
44549 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
44550 ** no hash slot such that aHash[i]==p) then page P is not in the
44551 ** current index block.  Otherwise the iMax-th mapping entry of the
44552 ** current index block corresponds to the last entry that references
44553 ** page P.
44554 **
44555 ** A hash search begins with the last index block and moves toward the
44556 ** first index block, looking for entries corresponding to page P.  On
44557 ** average, only two or three slots in each index block need to be
44558 ** examined in order to either find the last entry for page P, or to
44559 ** establish that no such entry exists in the block.  Each index block
44560 ** holds over 4000 entries.  So two or three index blocks are sufficient
44561 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
44562 ** comparisons (on average) suffice to either locate a frame in the
44563 ** WAL or to establish that the frame does not exist in the WAL.  This
44564 ** is much faster than scanning the entire 10MB WAL.
44565 **
44566 ** Note that entries are added in order of increasing K.  Hence, one
44567 ** reader might be using some value K0 and a second reader that started
44568 ** at a later time (after additional transactions were added to the WAL
44569 ** and to the wal-index) might be using a different value K1, where K1>K0.
44570 ** Both readers can use the same hash table and mapping section to get
44571 ** the correct result.  There may be entries in the hash table with
44572 ** K>K0 but to the first reader, those entries will appear to be unused
44573 ** slots in the hash table and so the first reader will get an answer as
44574 ** if no values greater than K0 had ever been inserted into the hash table
44575 ** in the first place - which is what reader one wants.  Meanwhile, the
44576 ** second reader using K1 will see additional values that were inserted
44577 ** later, which is exactly what reader two wants.
44578 **
44579 ** When a rollback occurs, the value of K is decreased. Hash table entries
44580 ** that correspond to frames greater than the new K value are removed
44581 ** from the hash table at this point.
44582 */
44583 #ifndef SQLITE_OMIT_WAL
44584 
44585 
44586 /*
44587 ** Trace output macros
44588 */
44589 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44590 SQLITE_PRIVATE int sqlite3WalTrace = 0;
44591 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
44592 #else
44593 # define WALTRACE(X)
44594 #endif
44595 
44596 /*
44597 ** The maximum (and only) versions of the wal and wal-index formats
44598 ** that may be interpreted by this version of SQLite.
44599 **
44600 ** If a client begins recovering a WAL file and finds that (a) the checksum
44601 ** values in the wal-header are correct and (b) the version field is not
44602 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
44603 **
44604 ** Similarly, if a client successfully reads a wal-index header (i.e. the
44605 ** checksum test is successful) and finds that the version field is not
44606 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
44607 ** returns SQLITE_CANTOPEN.
44608 */
44609 #define WAL_MAX_VERSION      3007000
44610 #define WALINDEX_MAX_VERSION 3007000
44611 
44612 /*
44613 ** Indices of various locking bytes.   WAL_NREADER is the number
44614 ** of available reader locks and should be at least 3.
44615 */
44616 #define WAL_WRITE_LOCK         0
44617 #define WAL_ALL_BUT_WRITE      1
44618 #define WAL_CKPT_LOCK          1
44619 #define WAL_RECOVER_LOCK       2
44620 #define WAL_READ_LOCK(I)       (3+(I))
44621 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
44622 
44623 
44624 /* Object declarations */
44625 typedef struct WalIndexHdr WalIndexHdr;
44626 typedef struct WalIterator WalIterator;
44627 typedef struct WalCkptInfo WalCkptInfo;
44628 
44629 
44630 /*
44631 ** The following object holds a copy of the wal-index header content.
44632 **
44633 ** The actual header in the wal-index consists of two copies of this
44634 ** object.
44635 **
44636 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
44637 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
44638 ** added in 3.7.1 when support for 64K pages was added.
44639 */
44640 struct WalIndexHdr {
44641   u32 iVersion;                   /* Wal-index version */
44642   u32 unused;                     /* Unused (padding) field */
44643   u32 iChange;                    /* Counter incremented each transaction */
44644   u8 isInit;                      /* 1 when initialized */
44645   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
44646   u16 szPage;                     /* Database page size in bytes. 1==64K */
44647   u32 mxFrame;                    /* Index of last valid frame in the WAL */
44648   u32 nPage;                      /* Size of database in pages */
44649   u32 aFrameCksum[2];             /* Checksum of last frame in log */
44650   u32 aSalt[2];                   /* Two salt values copied from WAL header */
44651   u32 aCksum[2];                  /* Checksum over all prior fields */
44652 };
44653 
44654 /*
44655 ** A copy of the following object occurs in the wal-index immediately
44656 ** following the second copy of the WalIndexHdr.  This object stores
44657 ** information used by checkpoint.
44658 **
44659 ** nBackfill is the number of frames in the WAL that have been written
44660 ** back into the database. (We call the act of moving content from WAL to
44661 ** database "backfilling".)  The nBackfill number is never greater than
44662 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
44663 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
44664 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
44665 ** mxFrame back to zero when the WAL is reset.
44666 **
44667 ** There is one entry in aReadMark[] for each reader lock.  If a reader
44668 ** holds read-lock K, then the value in aReadMark[K] is no greater than
44669 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
44670 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
44671 ** a special case; its value is never used and it exists as a place-holder
44672 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
44673 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
44674 ** directly from the database.
44675 **
44676 ** The value of aReadMark[K] may only be changed by a thread that
44677 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
44678 ** aReadMark[K] cannot changed while there is a reader is using that mark
44679 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
44680 **
44681 ** The checkpointer may only transfer frames from WAL to database where
44682 ** the frame numbers are less than or equal to every aReadMark[] that is
44683 ** in use (that is, every aReadMark[j] for which there is a corresponding
44684 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
44685 ** largest value and will increase an unused aReadMark[] to mxFrame if there
44686 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
44687 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
44688 ** in the WAL has been backfilled into the database) then new readers
44689 ** will choose aReadMark[0] which has value 0 and hence such reader will
44690 ** get all their all content directly from the database file and ignore
44691 ** the WAL.
44692 **
44693 ** Writers normally append new frames to the end of the WAL.  However,
44694 ** if nBackfill equals mxFrame (meaning that all WAL content has been
44695 ** written back into the database) and if no readers are using the WAL
44696 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
44697 ** the writer will first "reset" the WAL back to the beginning and start
44698 ** writing new content beginning at frame 1.
44699 **
44700 ** We assume that 32-bit loads are atomic and so no locks are needed in
44701 ** order to read from any aReadMark[] entries.
44702 */
44703 struct WalCkptInfo {
44704   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
44705   u32 aReadMark[WAL_NREADER];     /* Reader marks */
44706 };
44707 #define READMARK_NOT_USED  0xffffffff
44708 
44709 
44710 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
44711 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
44712 ** only support mandatory file-locks, we do not read or write data
44713 ** from the region of the file on which locks are applied.
44714 */
44715 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
44716 #define WALINDEX_LOCK_RESERVED 16
44717 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44718 
44719 /* Size of header before each frame in wal */
44720 #define WAL_FRAME_HDRSIZE 24
44721 
44722 /* Size of write ahead log header, including checksum. */
44723 /* #define WAL_HDRSIZE 24 */
44724 #define WAL_HDRSIZE 32
44725 
44726 /* WAL magic value. Either this value, or the same value with the least
44727 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44728 ** big-endian format in the first 4 bytes of a WAL file.
44729 **
44730 ** If the LSB is set, then the checksums for each frame within the WAL
44731 ** file are calculated by treating all data as an array of 32-bit
44732 ** big-endian words. Otherwise, they are calculated by interpreting
44733 ** all data as 32-bit little-endian words.
44734 */
44735 #define WAL_MAGIC 0x377f0682
44736 
44737 /*
44738 ** Return the offset of frame iFrame in the write-ahead log file,
44739 ** assuming a database page size of szPage bytes. The offset returned
44740 ** is to the start of the write-ahead log frame-header.
44741 */
44742 #define walFrameOffset(iFrame, szPage) (                               \
44743   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
44744 )
44745 
44746 /*
44747 ** An open write-ahead log file is represented by an instance of the
44748 ** following object.
44749 */
44750 struct Wal {
44751   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
44752   sqlite3_file *pDbFd;       /* File handle for the database file */
44753   sqlite3_file *pWalFd;      /* File handle for WAL file */
44754   u32 iCallback;             /* Value to pass to log callback (or 0) */
44755   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
44756   int nWiData;               /* Size of array apWiData */
44757   int szFirstBlock;          /* Size of first block written to WAL file */
44758   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
44759   u32 szPage;                /* Database page size */
44760   i16 readLock;              /* Which read lock is being held.  -1 for none */
44761   u8 syncFlags;              /* Flags to use to sync header writes */
44762   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
44763   u8 writeLock;              /* True if in a write transaction */
44764   u8 ckptLock;               /* True if holding a checkpoint lock */
44765   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44766   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
44767   u8 syncHeader;             /* Fsync the WAL header if true */
44768   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
44769   WalIndexHdr hdr;           /* Wal-index header for current transaction */
44770   const char *zWalName;      /* Name of WAL file */
44771   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
44772 #ifdef SQLITE_DEBUG
44773   u8 lockError;              /* True if a locking error has occurred */
44774 #endif
44775 };
44776 
44777 /*
44778 ** Candidate values for Wal.exclusiveMode.
44779 */
44780 #define WAL_NORMAL_MODE     0
44781 #define WAL_EXCLUSIVE_MODE  1
44782 #define WAL_HEAPMEMORY_MODE 2
44783 
44784 /*
44785 ** Possible values for WAL.readOnly
44786 */
44787 #define WAL_RDWR        0    /* Normal read/write connection */
44788 #define WAL_RDONLY      1    /* The WAL file is readonly */
44789 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
44790 
44791 /*
44792 ** Each page of the wal-index mapping contains a hash-table made up of
44793 ** an array of HASHTABLE_NSLOT elements of the following type.
44794 */
44795 typedef u16 ht_slot;
44796 
44797 /*
44798 ** This structure is used to implement an iterator that loops through
44799 ** all frames in the WAL in database page order. Where two or more frames
44800 ** correspond to the same database page, the iterator visits only the
44801 ** frame most recently written to the WAL (in other words, the frame with
44802 ** the largest index).
44803 **
44804 ** The internals of this structure are only accessed by:
44805 **
44806 **   walIteratorInit() - Create a new iterator,
44807 **   walIteratorNext() - Step an iterator,
44808 **   walIteratorFree() - Free an iterator.
44809 **
44810 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44811 */
44812 struct WalIterator {
44813   int iPrior;                     /* Last result returned from the iterator */
44814   int nSegment;                   /* Number of entries in aSegment[] */
44815   struct WalSegment {
44816     int iNext;                    /* Next slot in aIndex[] not yet returned */
44817     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
44818     u32 *aPgno;                   /* Array of page numbers. */
44819     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
44820     int iZero;                    /* Frame number associated with aPgno[0] */
44821   } aSegment[1];                  /* One for every 32KB page in the wal-index */
44822 };
44823 
44824 /*
44825 ** Define the parameters of the hash tables in the wal-index file. There
44826 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44827 ** wal-index.
44828 **
44829 ** Changing any of these constants will alter the wal-index format and
44830 ** create incompatibilities.
44831 */
44832 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
44833 #define HASHTABLE_HASH_1     383                  /* Should be prime */
44834 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
44835 
44836 /*
44837 ** The block of page numbers associated with the first hash-table in a
44838 ** wal-index is smaller than usual. This is so that there is a complete
44839 ** hash-table on each aligned 32KB page of the wal-index.
44840 */
44841 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44842 
44843 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44844 #define WALINDEX_PGSZ   (                                         \
44845     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44846 )
44847 
44848 /*
44849 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44850 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44851 ** numbered from zero.
44852 **
44853 ** If this call is successful, *ppPage is set to point to the wal-index
44854 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44855 ** then an SQLite error code is returned and *ppPage is set to 0.
44856 */
44857 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44858   int rc = SQLITE_OK;
44859 
44860   /* Enlarge the pWal->apWiData[] array if required */
44861   if( pWal->nWiData<=iPage ){
44862     int nByte = sizeof(u32*)*(iPage+1);
44863     volatile u32 **apNew;
44864     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44865     if( !apNew ){
44866       *ppPage = 0;
44867       return SQLITE_NOMEM;
44868     }
44869     memset((void*)&apNew[pWal->nWiData], 0,
44870            sizeof(u32*)*(iPage+1-pWal->nWiData));
44871     pWal->apWiData = apNew;
44872     pWal->nWiData = iPage+1;
44873   }
44874 
44875   /* Request a pointer to the required page from the VFS */
44876   if( pWal->apWiData[iPage]==0 ){
44877     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44878       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44879       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44880     }else{
44881       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
44882           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44883       );
44884       if( rc==SQLITE_READONLY ){
44885         pWal->readOnly |= WAL_SHM_RDONLY;
44886         rc = SQLITE_OK;
44887       }
44888     }
44889   }
44890 
44891   *ppPage = pWal->apWiData[iPage];
44892   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44893   return rc;
44894 }
44895 
44896 /*
44897 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44898 */
44899 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44900   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44901   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44902 }
44903 
44904 /*
44905 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44906 */
44907 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44908   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44909   return (volatile WalIndexHdr*)pWal->apWiData[0];
44910 }
44911 
44912 /*
44913 ** The argument to this macro must be of type u32. On a little-endian
44914 ** architecture, it returns the u32 value that results from interpreting
44915 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44916 ** returns the value that would be produced by intepreting the 4 bytes
44917 ** of the input value as a little-endian integer.
44918 */
44919 #define BYTESWAP32(x) ( \
44920     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
44921   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
44922 )
44923 
44924 /*
44925 ** Generate or extend an 8 byte checksum based on the data in
44926 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44927 ** initial values of 0 and 0 if aIn==NULL).
44928 **
44929 ** The checksum is written back into aOut[] before returning.
44930 **
44931 ** nByte must be a positive multiple of 8.
44932 */
44933 static void walChecksumBytes(
44934   int nativeCksum, /* True for native byte-order, false for non-native */
44935   u8 *a,           /* Content to be checksummed */
44936   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
44937   const u32 *aIn,  /* Initial checksum value input */
44938   u32 *aOut        /* OUT: Final checksum value output */
44939 ){
44940   u32 s1, s2;
44941   u32 *aData = (u32 *)a;
44942   u32 *aEnd = (u32 *)&a[nByte];
44943 
44944   if( aIn ){
44945     s1 = aIn[0];
44946     s2 = aIn[1];
44947   }else{
44948     s1 = s2 = 0;
44949   }
44950 
44951   assert( nByte>=8 );
44952   assert( (nByte&0x00000007)==0 );
44953 
44954   if( nativeCksum ){
44955     do {
44956       s1 += *aData++ + s2;
44957       s2 += *aData++ + s1;
44958     }while( aData<aEnd );
44959   }else{
44960     do {
44961       s1 += BYTESWAP32(aData[0]) + s2;
44962       s2 += BYTESWAP32(aData[1]) + s1;
44963       aData += 2;
44964     }while( aData<aEnd );
44965   }
44966 
44967   aOut[0] = s1;
44968   aOut[1] = s2;
44969 }
44970 
44971 static void walShmBarrier(Wal *pWal){
44972   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44973     sqlite3OsShmBarrier(pWal->pDbFd);
44974   }
44975 }
44976 
44977 /*
44978 ** Write the header information in pWal->hdr into the wal-index.
44979 **
44980 ** The checksum on pWal->hdr is updated before it is written.
44981 */
44982 static void walIndexWriteHdr(Wal *pWal){
44983   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44984   const int nCksum = offsetof(WalIndexHdr, aCksum);
44985 
44986   assert( pWal->writeLock );
44987   pWal->hdr.isInit = 1;
44988   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44989   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44990   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44991   walShmBarrier(pWal);
44992   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44993 }
44994 
44995 /*
44996 ** This function encodes a single frame header and writes it to a buffer
44997 ** supplied by the caller. A frame-header is made up of a series of
44998 ** 4-byte big-endian integers, as follows:
44999 **
45000 **     0: Page number.
45001 **     4: For commit records, the size of the database image in pages
45002 **        after the commit. For all other records, zero.
45003 **     8: Salt-1 (copied from the wal-header)
45004 **    12: Salt-2 (copied from the wal-header)
45005 **    16: Checksum-1.
45006 **    20: Checksum-2.
45007 */
45008 static void walEncodeFrame(
45009   Wal *pWal,                      /* The write-ahead log */
45010   u32 iPage,                      /* Database page number for frame */
45011   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
45012   u8 *aData,                      /* Pointer to page data */
45013   u8 *aFrame                      /* OUT: Write encoded frame here */
45014 ){
45015   int nativeCksum;                /* True for native byte-order checksums */
45016   u32 *aCksum = pWal->hdr.aFrameCksum;
45017   assert( WAL_FRAME_HDRSIZE==24 );
45018   sqlite3Put4byte(&aFrame[0], iPage);
45019   sqlite3Put4byte(&aFrame[4], nTruncate);
45020   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
45021 
45022   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45023   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45024   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45025 
45026   sqlite3Put4byte(&aFrame[16], aCksum[0]);
45027   sqlite3Put4byte(&aFrame[20], aCksum[1]);
45028 }
45029 
45030 /*
45031 ** Check to see if the frame with header in aFrame[] and content
45032 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
45033 ** *pnTruncate and return true.  Return if the frame is not valid.
45034 */
45035 static int walDecodeFrame(
45036   Wal *pWal,                      /* The write-ahead log */
45037   u32 *piPage,                    /* OUT: Database page number for frame */
45038   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
45039   u8 *aData,                      /* Pointer to page data (for checksum) */
45040   u8 *aFrame                      /* Frame data */
45041 ){
45042   int nativeCksum;                /* True for native byte-order checksums */
45043   u32 *aCksum = pWal->hdr.aFrameCksum;
45044   u32 pgno;                       /* Page number of the frame */
45045   assert( WAL_FRAME_HDRSIZE==24 );
45046 
45047   /* A frame is only valid if the salt values in the frame-header
45048   ** match the salt values in the wal-header.
45049   */
45050   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
45051     return 0;
45052   }
45053 
45054   /* A frame is only valid if the page number is creater than zero.
45055   */
45056   pgno = sqlite3Get4byte(&aFrame[0]);
45057   if( pgno==0 ){
45058     return 0;
45059   }
45060 
45061   /* A frame is only valid if a checksum of the WAL header,
45062   ** all prior frams, the first 16 bytes of this frame-header,
45063   ** and the frame-data matches the checksum in the last 8
45064   ** bytes of this frame-header.
45065   */
45066   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45067   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45068   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45069   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
45070    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
45071   ){
45072     /* Checksum failed. */
45073     return 0;
45074   }
45075 
45076   /* If we reach this point, the frame is valid.  Return the page number
45077   ** and the new database size.
45078   */
45079   *piPage = pgno;
45080   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
45081   return 1;
45082 }
45083 
45084 
45085 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45086 /*
45087 ** Names of locks.  This routine is used to provide debugging output and is not
45088 ** a part of an ordinary build.
45089 */
45090 static const char *walLockName(int lockIdx){
45091   if( lockIdx==WAL_WRITE_LOCK ){
45092     return "WRITE-LOCK";
45093   }else if( lockIdx==WAL_CKPT_LOCK ){
45094     return "CKPT-LOCK";
45095   }else if( lockIdx==WAL_RECOVER_LOCK ){
45096     return "RECOVER-LOCK";
45097   }else{
45098     static char zName[15];
45099     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
45100                      lockIdx-WAL_READ_LOCK(0));
45101     return zName;
45102   }
45103 }
45104 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
45105 
45106 
45107 /*
45108 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
45109 ** A lock cannot be moved directly between shared and exclusive - it must go
45110 ** through the unlocked state first.
45111 **
45112 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
45113 */
45114 static int walLockShared(Wal *pWal, int lockIdx){
45115   int rc;
45116   if( pWal->exclusiveMode ) return SQLITE_OK;
45117   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45118                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
45119   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
45120             walLockName(lockIdx), rc ? "failed" : "ok"));
45121   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45122   return rc;
45123 }
45124 static void walUnlockShared(Wal *pWal, int lockIdx){
45125   if( pWal->exclusiveMode ) return;
45126   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45127                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
45128   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
45129 }
45130 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
45131   int rc;
45132   if( pWal->exclusiveMode ) return SQLITE_OK;
45133   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45134                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
45135   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
45136             walLockName(lockIdx), n, rc ? "failed" : "ok"));
45137   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45138   return rc;
45139 }
45140 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
45141   if( pWal->exclusiveMode ) return;
45142   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45143                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
45144   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
45145              walLockName(lockIdx), n));
45146 }
45147 
45148 /*
45149 ** Compute a hash on a page number.  The resulting hash value must land
45150 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
45151 ** the hash to the next value in the event of a collision.
45152 */
45153 static int walHash(u32 iPage){
45154   assert( iPage>0 );
45155   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
45156   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
45157 }
45158 static int walNextHash(int iPriorHash){
45159   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
45160 }
45161 
45162 /*
45163 ** Return pointers to the hash table and page number array stored on
45164 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
45165 ** numbered starting from 0.
45166 **
45167 ** Set output variable *paHash to point to the start of the hash table
45168 ** in the wal-index file. Set *piZero to one less than the frame
45169 ** number of the first frame indexed by this hash table. If a
45170 ** slot in the hash table is set to N, it refers to frame number
45171 ** (*piZero+N) in the log.
45172 **
45173 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
45174 ** first frame indexed by the hash table, frame (*piZero+1).
45175 */
45176 static int walHashGet(
45177   Wal *pWal,                      /* WAL handle */
45178   int iHash,                      /* Find the iHash'th table */
45179   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
45180   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
45181   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
45182 ){
45183   int rc;                         /* Return code */
45184   volatile u32 *aPgno;
45185 
45186   rc = walIndexPage(pWal, iHash, &aPgno);
45187   assert( rc==SQLITE_OK || iHash>0 );
45188 
45189   if( rc==SQLITE_OK ){
45190     u32 iZero;
45191     volatile ht_slot *aHash;
45192 
45193     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
45194     if( iHash==0 ){
45195       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
45196       iZero = 0;
45197     }else{
45198       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
45199     }
45200 
45201     *paPgno = &aPgno[-1];
45202     *paHash = aHash;
45203     *piZero = iZero;
45204   }
45205   return rc;
45206 }
45207 
45208 /*
45209 ** Return the number of the wal-index page that contains the hash-table
45210 ** and page-number array that contain entries corresponding to WAL frame
45211 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
45212 ** are numbered starting from 0.
45213 */
45214 static int walFramePage(u32 iFrame){
45215   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
45216   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
45217        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
45218        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
45219        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
45220        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
45221   );
45222   return iHash;
45223 }
45224 
45225 /*
45226 ** Return the page number associated with frame iFrame in this WAL.
45227 */
45228 static u32 walFramePgno(Wal *pWal, u32 iFrame){
45229   int iHash = walFramePage(iFrame);
45230   if( iHash==0 ){
45231     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
45232   }
45233   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
45234 }
45235 
45236 /*
45237 ** Remove entries from the hash table that point to WAL slots greater
45238 ** than pWal->hdr.mxFrame.
45239 **
45240 ** This function is called whenever pWal->hdr.mxFrame is decreased due
45241 ** to a rollback or savepoint.
45242 **
45243 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
45244 ** updated.  Any later hash tables will be automatically cleared when
45245 ** pWal->hdr.mxFrame advances to the point where those hash tables are
45246 ** actually needed.
45247 */
45248 static void walCleanupHash(Wal *pWal){
45249   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
45250   volatile u32 *aPgno = 0;        /* Page number array for hash table */
45251   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
45252   int iLimit = 0;                 /* Zero values greater than this */
45253   int nByte;                      /* Number of bytes to zero in aPgno[] */
45254   int i;                          /* Used to iterate through aHash[] */
45255 
45256   assert( pWal->writeLock );
45257   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
45258   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
45259   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
45260 
45261   if( pWal->hdr.mxFrame==0 ) return;
45262 
45263   /* Obtain pointers to the hash-table and page-number array containing
45264   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
45265   ** that the page said hash-table and array reside on is already mapped.
45266   */
45267   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
45268   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
45269   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
45270 
45271   /* Zero all hash-table entries that correspond to frame numbers greater
45272   ** than pWal->hdr.mxFrame.
45273   */
45274   iLimit = pWal->hdr.mxFrame - iZero;
45275   assert( iLimit>0 );
45276   for(i=0; i<HASHTABLE_NSLOT; i++){
45277     if( aHash[i]>iLimit ){
45278       aHash[i] = 0;
45279     }
45280   }
45281 
45282   /* Zero the entries in the aPgno array that correspond to frames with
45283   ** frame numbers greater than pWal->hdr.mxFrame.
45284   */
45285   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
45286   memset((void *)&aPgno[iLimit+1], 0, nByte);
45287 
45288 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45289   /* Verify that the every entry in the mapping region is still reachable
45290   ** via the hash table even after the cleanup.
45291   */
45292   if( iLimit ){
45293     int i;           /* Loop counter */
45294     int iKey;        /* Hash key */
45295     for(i=1; i<=iLimit; i++){
45296       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45297         if( aHash[iKey]==i ) break;
45298       }
45299       assert( aHash[iKey]==i );
45300     }
45301   }
45302 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45303 }
45304 
45305 
45306 /*
45307 ** Set an entry in the wal-index that will map database page number
45308 ** pPage into WAL frame iFrame.
45309 */
45310 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
45311   int rc;                         /* Return code */
45312   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
45313   volatile u32 *aPgno = 0;        /* Page number array */
45314   volatile ht_slot *aHash = 0;    /* Hash table */
45315 
45316   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
45317 
45318   /* Assuming the wal-index file was successfully mapped, populate the
45319   ** page number array and hash table entry.
45320   */
45321   if( rc==SQLITE_OK ){
45322     int iKey;                     /* Hash table key */
45323     int idx;                      /* Value to write to hash-table slot */
45324     int nCollide;                 /* Number of hash collisions */
45325 
45326     idx = iFrame - iZero;
45327     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
45328 
45329     /* If this is the first entry to be added to this hash-table, zero the
45330     ** entire hash table and aPgno[] array before proceding.
45331     */
45332     if( idx==1 ){
45333       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
45334       memset((void*)&aPgno[1], 0, nByte);
45335     }
45336 
45337     /* If the entry in aPgno[] is already set, then the previous writer
45338     ** must have exited unexpectedly in the middle of a transaction (after
45339     ** writing one or more dirty pages to the WAL to free up memory).
45340     ** Remove the remnants of that writers uncommitted transaction from
45341     ** the hash-table before writing any new entries.
45342     */
45343     if( aPgno[idx] ){
45344       walCleanupHash(pWal);
45345       assert( !aPgno[idx] );
45346     }
45347 
45348     /* Write the aPgno[] array entry and the hash-table slot. */
45349     nCollide = idx;
45350     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
45351       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
45352     }
45353     aPgno[idx] = iPage;
45354     aHash[iKey] = (ht_slot)idx;
45355 
45356 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45357     /* Verify that the number of entries in the hash table exactly equals
45358     ** the number of entries in the mapping region.
45359     */
45360     {
45361       int i;           /* Loop counter */
45362       int nEntry = 0;  /* Number of entries in the hash table */
45363       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
45364       assert( nEntry==idx );
45365     }
45366 
45367     /* Verify that the every entry in the mapping region is reachable
45368     ** via the hash table.  This turns out to be a really, really expensive
45369     ** thing to check, so only do this occasionally - not on every
45370     ** iteration.
45371     */
45372     if( (idx&0x3ff)==0 ){
45373       int i;           /* Loop counter */
45374       for(i=1; i<=idx; i++){
45375         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45376           if( aHash[iKey]==i ) break;
45377         }
45378         assert( aHash[iKey]==i );
45379       }
45380     }
45381 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45382   }
45383 
45384 
45385   return rc;
45386 }
45387 
45388 
45389 /*
45390 ** Recover the wal-index by reading the write-ahead log file.
45391 **
45392 ** This routine first tries to establish an exclusive lock on the
45393 ** wal-index to prevent other threads/processes from doing anything
45394 ** with the WAL or wal-index while recovery is running.  The
45395 ** WAL_RECOVER_LOCK is also held so that other threads will know
45396 ** that this thread is running recovery.  If unable to establish
45397 ** the necessary locks, this routine returns SQLITE_BUSY.
45398 */
45399 static int walIndexRecover(Wal *pWal){
45400   int rc;                         /* Return Code */
45401   i64 nSize;                      /* Size of log file */
45402   u32 aFrameCksum[2] = {0, 0};
45403   int iLock;                      /* Lock offset to lock for checkpoint */
45404   int nLock;                      /* Number of locks to hold */
45405 
45406   /* Obtain an exclusive lock on all byte in the locking range not already
45407   ** locked by the caller. The caller is guaranteed to have locked the
45408   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
45409   ** If successful, the same bytes that are locked here are unlocked before
45410   ** this function returns.
45411   */
45412   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
45413   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
45414   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
45415   assert( pWal->writeLock );
45416   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
45417   nLock = SQLITE_SHM_NLOCK - iLock;
45418   rc = walLockExclusive(pWal, iLock, nLock);
45419   if( rc ){
45420     return rc;
45421   }
45422   WALTRACE(("WAL%p: recovery begin...\n", pWal));
45423 
45424   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45425 
45426   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
45427   if( rc!=SQLITE_OK ){
45428     goto recovery_error;
45429   }
45430 
45431   if( nSize>WAL_HDRSIZE ){
45432     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
45433     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
45434     int szFrame;                  /* Number of bytes in buffer aFrame[] */
45435     u8 *aData;                    /* Pointer to data part of aFrame buffer */
45436     int iFrame;                   /* Index of last frame read */
45437     i64 iOffset;                  /* Next offset to read from log file */
45438     int szPage;                   /* Page size according to the log */
45439     u32 magic;                    /* Magic value read from WAL header */
45440     u32 version;                  /* Magic value read from WAL header */
45441     int isValid;                  /* True if this frame is valid */
45442 
45443     /* Read in the WAL header. */
45444     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
45445     if( rc!=SQLITE_OK ){
45446       goto recovery_error;
45447     }
45448 
45449     /* If the database page size is not a power of two, or is greater than
45450     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
45451     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
45452     ** WAL file.
45453     */
45454     magic = sqlite3Get4byte(&aBuf[0]);
45455     szPage = sqlite3Get4byte(&aBuf[8]);
45456     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
45457      || szPage&(szPage-1)
45458      || szPage>SQLITE_MAX_PAGE_SIZE
45459      || szPage<512
45460     ){
45461       goto finished;
45462     }
45463     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
45464     pWal->szPage = szPage;
45465     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
45466     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
45467 
45468     /* Verify that the WAL header checksum is correct */
45469     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
45470         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
45471     );
45472     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
45473      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
45474     ){
45475       goto finished;
45476     }
45477 
45478     /* Verify that the version number on the WAL format is one that
45479     ** are able to understand */
45480     version = sqlite3Get4byte(&aBuf[4]);
45481     if( version!=WAL_MAX_VERSION ){
45482       rc = SQLITE_CANTOPEN_BKPT;
45483       goto finished;
45484     }
45485 
45486     /* Malloc a buffer to read frames into. */
45487     szFrame = szPage + WAL_FRAME_HDRSIZE;
45488     aFrame = (u8 *)sqlite3_malloc(szFrame);
45489     if( !aFrame ){
45490       rc = SQLITE_NOMEM;
45491       goto recovery_error;
45492     }
45493     aData = &aFrame[WAL_FRAME_HDRSIZE];
45494 
45495     /* Read all frames from the log file. */
45496     iFrame = 0;
45497     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
45498       u32 pgno;                   /* Database page number for frame */
45499       u32 nTruncate;              /* dbsize field from frame header */
45500 
45501       /* Read and decode the next log frame. */
45502       iFrame++;
45503       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
45504       if( rc!=SQLITE_OK ) break;
45505       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
45506       if( !isValid ) break;
45507       rc = walIndexAppend(pWal, iFrame, pgno);
45508       if( rc!=SQLITE_OK ) break;
45509 
45510       /* If nTruncate is non-zero, this is a commit record. */
45511       if( nTruncate ){
45512         pWal->hdr.mxFrame = iFrame;
45513         pWal->hdr.nPage = nTruncate;
45514         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45515         testcase( szPage<=32768 );
45516         testcase( szPage>=65536 );
45517         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
45518         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
45519       }
45520     }
45521 
45522     sqlite3_free(aFrame);
45523   }
45524 
45525 finished:
45526   if( rc==SQLITE_OK ){
45527     volatile WalCkptInfo *pInfo;
45528     int i;
45529     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
45530     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
45531     walIndexWriteHdr(pWal);
45532 
45533     /* Reset the checkpoint-header. This is safe because this thread is
45534     ** currently holding locks that exclude all other readers, writers and
45535     ** checkpointers.
45536     */
45537     pInfo = walCkptInfo(pWal);
45538     pInfo->nBackfill = 0;
45539     pInfo->aReadMark[0] = 0;
45540     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45541     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
45542 
45543     /* If more than one frame was recovered from the log file, report an
45544     ** event via sqlite3_log(). This is to help with identifying performance
45545     ** problems caused by applications routinely shutting down without
45546     ** checkpointing the log file.
45547     */
45548     if( pWal->hdr.nPage ){
45549       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
45550           pWal->hdr.nPage, pWal->zWalName
45551       );
45552     }
45553   }
45554 
45555 recovery_error:
45556   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
45557   walUnlockExclusive(pWal, iLock, nLock);
45558   return rc;
45559 }
45560 
45561 /*
45562 ** Close an open wal-index.
45563 */
45564 static void walIndexClose(Wal *pWal, int isDelete){
45565   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45566     int i;
45567     for(i=0; i<pWal->nWiData; i++){
45568       sqlite3_free((void *)pWal->apWiData[i]);
45569       pWal->apWiData[i] = 0;
45570     }
45571   }else{
45572     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
45573   }
45574 }
45575 
45576 /*
45577 ** Open a connection to the WAL file zWalName. The database file must
45578 ** already be opened on connection pDbFd. The buffer that zWalName points
45579 ** to must remain valid for the lifetime of the returned Wal* handle.
45580 **
45581 ** A SHARED lock should be held on the database file when this function
45582 ** is called. The purpose of this SHARED lock is to prevent any other
45583 ** client from unlinking the WAL or wal-index file. If another process
45584 ** were to do this just after this client opened one of these files, the
45585 ** system would be badly broken.
45586 **
45587 ** If the log file is successfully opened, SQLITE_OK is returned and
45588 ** *ppWal is set to point to a new WAL handle. If an error occurs,
45589 ** an SQLite error code is returned and *ppWal is left unmodified.
45590 */
45591 SQLITE_PRIVATE int sqlite3WalOpen(
45592   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
45593   sqlite3_file *pDbFd,            /* The open database file */
45594   const char *zWalName,           /* Name of the WAL file */
45595   int bNoShm,                     /* True to run in heap-memory mode */
45596   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
45597   Wal **ppWal                     /* OUT: Allocated Wal handle */
45598 ){
45599   int rc;                         /* Return Code */
45600   Wal *pRet;                      /* Object to allocate and return */
45601   int flags;                      /* Flags passed to OsOpen() */
45602 
45603   assert( zWalName && zWalName[0] );
45604   assert( pDbFd );
45605 
45606   /* In the amalgamation, the os_unix.c and os_win.c source files come before
45607   ** this source file.  Verify that the #defines of the locking byte offsets
45608   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
45609   */
45610 #ifdef WIN_SHM_BASE
45611   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
45612 #endif
45613 #ifdef UNIX_SHM_BASE
45614   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
45615 #endif
45616 
45617 
45618   /* Allocate an instance of struct Wal to return. */
45619   *ppWal = 0;
45620   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
45621   if( !pRet ){
45622     return SQLITE_NOMEM;
45623   }
45624 
45625   pRet->pVfs = pVfs;
45626   pRet->pWalFd = (sqlite3_file *)&pRet[1];
45627   pRet->pDbFd = pDbFd;
45628   pRet->readLock = -1;
45629   pRet->mxWalSize = mxWalSize;
45630   pRet->zWalName = zWalName;
45631   pRet->syncHeader = 1;
45632   pRet->padToSectorBoundary = 1;
45633   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
45634 
45635   /* Open file handle on the write-ahead log file. */
45636   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
45637   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
45638   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
45639     pRet->readOnly = WAL_RDONLY;
45640   }
45641 
45642   if( rc!=SQLITE_OK ){
45643     walIndexClose(pRet, 0);
45644     sqlite3OsClose(pRet->pWalFd);
45645     sqlite3_free(pRet);
45646   }else{
45647     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
45648     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
45649     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
45650       pRet->padToSectorBoundary = 0;
45651     }
45652     *ppWal = pRet;
45653     WALTRACE(("WAL%d: opened\n", pRet));
45654   }
45655   return rc;
45656 }
45657 
45658 /*
45659 ** Change the size to which the WAL file is trucated on each reset.
45660 */
45661 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
45662   if( pWal ) pWal->mxWalSize = iLimit;
45663 }
45664 
45665 /*
45666 ** Find the smallest page number out of all pages held in the WAL that
45667 ** has not been returned by any prior invocation of this method on the
45668 ** same WalIterator object.   Write into *piFrame the frame index where
45669 ** that page was last written into the WAL.  Write into *piPage the page
45670 ** number.
45671 **
45672 ** Return 0 on success.  If there are no pages in the WAL with a page
45673 ** number larger than *piPage, then return 1.
45674 */
45675 static int walIteratorNext(
45676   WalIterator *p,               /* Iterator */
45677   u32 *piPage,                  /* OUT: The page number of the next page */
45678   u32 *piFrame                  /* OUT: Wal frame index of next page */
45679 ){
45680   u32 iMin;                     /* Result pgno must be greater than iMin */
45681   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
45682   int i;                        /* For looping through segments */
45683 
45684   iMin = p->iPrior;
45685   assert( iMin<0xffffffff );
45686   for(i=p->nSegment-1; i>=0; i--){
45687     struct WalSegment *pSegment = &p->aSegment[i];
45688     while( pSegment->iNext<pSegment->nEntry ){
45689       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
45690       if( iPg>iMin ){
45691         if( iPg<iRet ){
45692           iRet = iPg;
45693           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
45694         }
45695         break;
45696       }
45697       pSegment->iNext++;
45698     }
45699   }
45700 
45701   *piPage = p->iPrior = iRet;
45702   return (iRet==0xFFFFFFFF);
45703 }
45704 
45705 /*
45706 ** This function merges two sorted lists into a single sorted list.
45707 **
45708 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
45709 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
45710 ** is guaranteed for all J<K:
45711 **
45712 **        aContent[aLeft[J]] < aContent[aLeft[K]]
45713 **        aContent[aRight[J]] < aContent[aRight[K]]
45714 **
45715 ** This routine overwrites aRight[] with a new (probably longer) sequence
45716 ** of indices such that the aRight[] contains every index that appears in
45717 ** either aLeft[] or the old aRight[] and such that the second condition
45718 ** above is still met.
45719 **
45720 ** The aContent[aLeft[X]] values will be unique for all X.  And the
45721 ** aContent[aRight[X]] values will be unique too.  But there might be
45722 ** one or more combinations of X and Y such that
45723 **
45724 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
45725 **
45726 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
45727 */
45728 static void walMerge(
45729   const u32 *aContent,            /* Pages in wal - keys for the sort */
45730   ht_slot *aLeft,                 /* IN: Left hand input list */
45731   int nLeft,                      /* IN: Elements in array *paLeft */
45732   ht_slot **paRight,              /* IN/OUT: Right hand input list */
45733   int *pnRight,                   /* IN/OUT: Elements in *paRight */
45734   ht_slot *aTmp                   /* Temporary buffer */
45735 ){
45736   int iLeft = 0;                  /* Current index in aLeft */
45737   int iRight = 0;                 /* Current index in aRight */
45738   int iOut = 0;                   /* Current index in output buffer */
45739   int nRight = *pnRight;
45740   ht_slot *aRight = *paRight;
45741 
45742   assert( nLeft>0 && nRight>0 );
45743   while( iRight<nRight || iLeft<nLeft ){
45744     ht_slot logpage;
45745     Pgno dbpage;
45746 
45747     if( (iLeft<nLeft)
45748      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45749     ){
45750       logpage = aLeft[iLeft++];
45751     }else{
45752       logpage = aRight[iRight++];
45753     }
45754     dbpage = aContent[logpage];
45755 
45756     aTmp[iOut++] = logpage;
45757     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45758 
45759     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45760     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45761   }
45762 
45763   *paRight = aLeft;
45764   *pnRight = iOut;
45765   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45766 }
45767 
45768 /*
45769 ** Sort the elements in list aList using aContent[] as the sort key.
45770 ** Remove elements with duplicate keys, preferring to keep the
45771 ** larger aList[] values.
45772 **
45773 ** The aList[] entries are indices into aContent[].  The values in
45774 ** aList[] are to be sorted so that for all J<K:
45775 **
45776 **      aContent[aList[J]] < aContent[aList[K]]
45777 **
45778 ** For any X and Y such that
45779 **
45780 **      aContent[aList[X]] == aContent[aList[Y]]
45781 **
45782 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45783 ** the smaller.
45784 */
45785 static void walMergesort(
45786   const u32 *aContent,            /* Pages in wal */
45787   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
45788   ht_slot *aList,                 /* IN/OUT: List to sort */
45789   int *pnList                     /* IN/OUT: Number of elements in aList[] */
45790 ){
45791   struct Sublist {
45792     int nList;                    /* Number of elements in aList */
45793     ht_slot *aList;               /* Pointer to sub-list content */
45794   };
45795 
45796   const int nList = *pnList;      /* Size of input list */
45797   int nMerge = 0;                 /* Number of elements in list aMerge */
45798   ht_slot *aMerge = 0;            /* List to be merged */
45799   int iList;                      /* Index into input list */
45800   int iSub = 0;                   /* Index into aSub array */
45801   struct Sublist aSub[13];        /* Array of sub-lists */
45802 
45803   memset(aSub, 0, sizeof(aSub));
45804   assert( nList<=HASHTABLE_NPAGE && nList>0 );
45805   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45806 
45807   for(iList=0; iList<nList; iList++){
45808     nMerge = 1;
45809     aMerge = &aList[iList];
45810     for(iSub=0; iList & (1<<iSub); iSub++){
45811       struct Sublist *p = &aSub[iSub];
45812       assert( p->aList && p->nList<=(1<<iSub) );
45813       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45814       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45815     }
45816     aSub[iSub].aList = aMerge;
45817     aSub[iSub].nList = nMerge;
45818   }
45819 
45820   for(iSub++; iSub<ArraySize(aSub); iSub++){
45821     if( nList & (1<<iSub) ){
45822       struct Sublist *p = &aSub[iSub];
45823       assert( p->nList<=(1<<iSub) );
45824       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45825       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45826     }
45827   }
45828   assert( aMerge==aList );
45829   *pnList = nMerge;
45830 
45831 #ifdef SQLITE_DEBUG
45832   {
45833     int i;
45834     for(i=1; i<*pnList; i++){
45835       assert( aContent[aList[i]] > aContent[aList[i-1]] );
45836     }
45837   }
45838 #endif
45839 }
45840 
45841 /*
45842 ** Free an iterator allocated by walIteratorInit().
45843 */
45844 static void walIteratorFree(WalIterator *p){
45845   sqlite3ScratchFree(p);
45846 }
45847 
45848 /*
45849 ** Construct a WalInterator object that can be used to loop over all
45850 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45851 ** lock.
45852 **
45853 ** On success, make *pp point to the newly allocated WalInterator object
45854 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45855 ** returns an error, the value of *pp is undefined.
45856 **
45857 ** The calling routine should invoke walIteratorFree() to destroy the
45858 ** WalIterator object when it has finished with it.
45859 */
45860 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45861   WalIterator *p;                 /* Return value */
45862   int nSegment;                   /* Number of segments to merge */
45863   u32 iLast;                      /* Last frame in log */
45864   int nByte;                      /* Number of bytes to allocate */
45865   int i;                          /* Iterator variable */
45866   ht_slot *aTmp;                  /* Temp space used by merge-sort */
45867   int rc = SQLITE_OK;             /* Return Code */
45868 
45869   /* This routine only runs while holding the checkpoint lock. And
45870   ** it only runs if there is actually content in the log (mxFrame>0).
45871   */
45872   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45873   iLast = pWal->hdr.mxFrame;
45874 
45875   /* Allocate space for the WalIterator object. */
45876   nSegment = walFramePage(iLast) + 1;
45877   nByte = sizeof(WalIterator)
45878         + (nSegment-1)*sizeof(struct WalSegment)
45879         + iLast*sizeof(ht_slot);
45880   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45881   if( !p ){
45882     return SQLITE_NOMEM;
45883   }
45884   memset(p, 0, nByte);
45885   p->nSegment = nSegment;
45886 
45887   /* Allocate temporary space used by the merge-sort routine. This block
45888   ** of memory will be freed before this function returns.
45889   */
45890   aTmp = (ht_slot *)sqlite3ScratchMalloc(
45891       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45892   );
45893   if( !aTmp ){
45894     rc = SQLITE_NOMEM;
45895   }
45896 
45897   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45898     volatile ht_slot *aHash;
45899     u32 iZero;
45900     volatile u32 *aPgno;
45901 
45902     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45903     if( rc==SQLITE_OK ){
45904       int j;                      /* Counter variable */
45905       int nEntry;                 /* Number of entries in this segment */
45906       ht_slot *aIndex;            /* Sorted index for this segment */
45907 
45908       aPgno++;
45909       if( (i+1)==nSegment ){
45910         nEntry = (int)(iLast - iZero);
45911       }else{
45912         nEntry = (int)((u32*)aHash - (u32*)aPgno);
45913       }
45914       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45915       iZero++;
45916 
45917       for(j=0; j<nEntry; j++){
45918         aIndex[j] = (ht_slot)j;
45919       }
45920       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45921       p->aSegment[i].iZero = iZero;
45922       p->aSegment[i].nEntry = nEntry;
45923       p->aSegment[i].aIndex = aIndex;
45924       p->aSegment[i].aPgno = (u32 *)aPgno;
45925     }
45926   }
45927   sqlite3ScratchFree(aTmp);
45928 
45929   if( rc!=SQLITE_OK ){
45930     walIteratorFree(p);
45931   }
45932   *pp = p;
45933   return rc;
45934 }
45935 
45936 /*
45937 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45938 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45939 ** busy-handler function. Invoke it and retry the lock until either the
45940 ** lock is successfully obtained or the busy-handler returns 0.
45941 */
45942 static int walBusyLock(
45943   Wal *pWal,                      /* WAL connection */
45944   int (*xBusy)(void*),            /* Function to call when busy */
45945   void *pBusyArg,                 /* Context argument for xBusyHandler */
45946   int lockIdx,                    /* Offset of first byte to lock */
45947   int n                           /* Number of bytes to lock */
45948 ){
45949   int rc;
45950   do {
45951     rc = walLockExclusive(pWal, lockIdx, n);
45952   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45953   return rc;
45954 }
45955 
45956 /*
45957 ** The cache of the wal-index header must be valid to call this function.
45958 ** Return the page-size in bytes used by the database.
45959 */
45960 static int walPagesize(Wal *pWal){
45961   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45962 }
45963 
45964 /*
45965 ** Copy as much content as we can from the WAL back into the database file
45966 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45967 **
45968 ** The amount of information copies from WAL to database might be limited
45969 ** by active readers.  This routine will never overwrite a database page
45970 ** that a concurrent reader might be using.
45971 **
45972 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45973 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
45974 ** checkpoints are always run by a background thread or background
45975 ** process, foreground threads will never block on a lengthy fsync call.
45976 **
45977 ** Fsync is called on the WAL before writing content out of the WAL and
45978 ** into the database.  This ensures that if the new content is persistent
45979 ** in the WAL and can be recovered following a power-loss or hard reset.
45980 **
45981 ** Fsync is also called on the database file if (and only if) the entire
45982 ** WAL content is copied into the database file.  This second fsync makes
45983 ** it safe to delete the WAL since the new content will persist in the
45984 ** database file.
45985 **
45986 ** This routine uses and updates the nBackfill field of the wal-index header.
45987 ** This is the only routine tha will increase the value of nBackfill.
45988 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45989 ** its value.)
45990 **
45991 ** The caller must be holding sufficient locks to ensure that no other
45992 ** checkpoint is running (in any other thread or process) at the same
45993 ** time.
45994 */
45995 static int walCheckpoint(
45996   Wal *pWal,                      /* Wal connection */
45997   int eMode,                      /* One of PASSIVE, FULL or RESTART */
45998   int (*xBusyCall)(void*),        /* Function to call when busy */
45999   void *pBusyArg,                 /* Context argument for xBusyHandler */
46000   int sync_flags,                 /* Flags for OsSync() (or 0) */
46001   u8 *zBuf                        /* Temporary buffer to use */
46002 ){
46003   int rc;                         /* Return code */
46004   int szPage;                     /* Database page-size */
46005   WalIterator *pIter = 0;         /* Wal iterator context */
46006   u32 iDbpage = 0;                /* Next database page to write */
46007   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
46008   u32 mxSafeFrame;                /* Max frame that can be backfilled */
46009   u32 mxPage;                     /* Max database page to write */
46010   int i;                          /* Loop counter */
46011   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
46012   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
46013 
46014   szPage = walPagesize(pWal);
46015   testcase( szPage<=32768 );
46016   testcase( szPage>=65536 );
46017   pInfo = walCkptInfo(pWal);
46018   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
46019 
46020   /* Allocate the iterator */
46021   rc = walIteratorInit(pWal, &pIter);
46022   if( rc!=SQLITE_OK ){
46023     return rc;
46024   }
46025   assert( pIter );
46026 
46027   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
46028 
46029   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
46030   ** safe to write into the database.  Frames beyond mxSafeFrame might
46031   ** overwrite database pages that are in use by active readers and thus
46032   ** cannot be backfilled from the WAL.
46033   */
46034   mxSafeFrame = pWal->hdr.mxFrame;
46035   mxPage = pWal->hdr.nPage;
46036   for(i=1; i<WAL_NREADER; i++){
46037     u32 y = pInfo->aReadMark[i];
46038     if( mxSafeFrame>y ){
46039       assert( y<=pWal->hdr.mxFrame );
46040       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
46041       if( rc==SQLITE_OK ){
46042         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
46043         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46044       }else if( rc==SQLITE_BUSY ){
46045         mxSafeFrame = y;
46046         xBusy = 0;
46047       }else{
46048         goto walcheckpoint_out;
46049       }
46050     }
46051   }
46052 
46053   if( pInfo->nBackfill<mxSafeFrame
46054    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
46055   ){
46056     i64 nSize;                    /* Current size of database file */
46057     u32 nBackfill = pInfo->nBackfill;
46058 
46059     /* Sync the WAL to disk */
46060     if( sync_flags ){
46061       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46062     }
46063 
46064     /* If the database file may grow as a result of this checkpoint, hint
46065     ** about the eventual size of the db file to the VFS layer.
46066     */
46067     if( rc==SQLITE_OK ){
46068       i64 nReq = ((i64)mxPage * szPage);
46069       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
46070       if( rc==SQLITE_OK && nSize<nReq ){
46071         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
46072       }
46073     }
46074 
46075     /* Iterate through the contents of the WAL, copying data to the db file. */
46076     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
46077       i64 iOffset;
46078       assert( walFramePgno(pWal, iFrame)==iDbpage );
46079       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
46080       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
46081       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
46082       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
46083       if( rc!=SQLITE_OK ) break;
46084       iOffset = (iDbpage-1)*(i64)szPage;
46085       testcase( IS_BIG_INT(iOffset) );
46086       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
46087       if( rc!=SQLITE_OK ) break;
46088     }
46089 
46090     /* If work was actually accomplished... */
46091     if( rc==SQLITE_OK ){
46092       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
46093         i64 szDb = pWal->hdr.nPage*(i64)szPage;
46094         testcase( IS_BIG_INT(szDb) );
46095         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
46096         if( rc==SQLITE_OK && sync_flags ){
46097           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
46098         }
46099       }
46100       if( rc==SQLITE_OK ){
46101         pInfo->nBackfill = mxSafeFrame;
46102       }
46103     }
46104 
46105     /* Release the reader lock held while backfilling */
46106     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
46107   }
46108 
46109   if( rc==SQLITE_BUSY ){
46110     /* Reset the return code so as not to report a checkpoint failure
46111     ** just because there are active readers.  */
46112     rc = SQLITE_OK;
46113   }
46114 
46115   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
46116   ** file has been copied into the database file, then block until all
46117   ** readers have finished using the wal file. This ensures that the next
46118   ** process to write to the database restarts the wal file.
46119   */
46120   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46121     assert( pWal->writeLock );
46122     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
46123       rc = SQLITE_BUSY;
46124     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
46125       assert( mxSafeFrame==pWal->hdr.mxFrame );
46126       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
46127       if( rc==SQLITE_OK ){
46128         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46129       }
46130     }
46131   }
46132 
46133  walcheckpoint_out:
46134   walIteratorFree(pIter);
46135   return rc;
46136 }
46137 
46138 /*
46139 ** If the WAL file is currently larger than nMax bytes in size, truncate
46140 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
46141 */
46142 static void walLimitSize(Wal *pWal, i64 nMax){
46143   i64 sz;
46144   int rx;
46145   sqlite3BeginBenignMalloc();
46146   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
46147   if( rx==SQLITE_OK && (sz > nMax ) ){
46148     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
46149   }
46150   sqlite3EndBenignMalloc();
46151   if( rx ){
46152     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
46153   }
46154 }
46155 
46156 /*
46157 ** Close a connection to a log file.
46158 */
46159 SQLITE_PRIVATE int sqlite3WalClose(
46160   Wal *pWal,                      /* Wal to close */
46161   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
46162   int nBuf,
46163   u8 *zBuf                        /* Buffer of at least nBuf bytes */
46164 ){
46165   int rc = SQLITE_OK;
46166   if( pWal ){
46167     int isDelete = 0;             /* True to unlink wal and wal-index files */
46168 
46169     /* If an EXCLUSIVE lock can be obtained on the database file (using the
46170     ** ordinary, rollback-mode locking methods, this guarantees that the
46171     ** connection associated with this log file is the only connection to
46172     ** the database. In this case checkpoint the database and unlink both
46173     ** the wal and wal-index files.
46174     **
46175     ** The EXCLUSIVE lock is not released before returning.
46176     */
46177     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
46178     if( rc==SQLITE_OK ){
46179       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
46180         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
46181       }
46182       rc = sqlite3WalCheckpoint(
46183           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
46184       );
46185       if( rc==SQLITE_OK ){
46186         int bPersist = -1;
46187         sqlite3OsFileControlHint(
46188             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
46189         );
46190         if( bPersist!=1 ){
46191           /* Try to delete the WAL file if the checkpoint completed and
46192           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
46193           ** mode (!bPersist) */
46194           isDelete = 1;
46195         }else if( pWal->mxWalSize>=0 ){
46196           /* Try to truncate the WAL file to zero bytes if the checkpoint
46197           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
46198           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
46199           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
46200           ** to zero bytes as truncating to the journal_size_limit might
46201           ** leave a corrupt WAL file on disk. */
46202           walLimitSize(pWal, 0);
46203         }
46204       }
46205     }
46206 
46207     walIndexClose(pWal, isDelete);
46208     sqlite3OsClose(pWal->pWalFd);
46209     if( isDelete ){
46210       sqlite3BeginBenignMalloc();
46211       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
46212       sqlite3EndBenignMalloc();
46213     }
46214     WALTRACE(("WAL%p: closed\n", pWal));
46215     sqlite3_free((void *)pWal->apWiData);
46216     sqlite3_free(pWal);
46217   }
46218   return rc;
46219 }
46220 
46221 /*
46222 ** Try to read the wal-index header.  Return 0 on success and 1 if
46223 ** there is a problem.
46224 **
46225 ** The wal-index is in shared memory.  Another thread or process might
46226 ** be writing the header at the same time this procedure is trying to
46227 ** read it, which might result in inconsistency.  A dirty read is detected
46228 ** by verifying that both copies of the header are the same and also by
46229 ** a checksum on the header.
46230 **
46231 ** If and only if the read is consistent and the header is different from
46232 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
46233 ** and *pChanged is set to 1.
46234 **
46235 ** If the checksum cannot be verified return non-zero. If the header
46236 ** is read successfully and the checksum verified, return zero.
46237 */
46238 static int walIndexTryHdr(Wal *pWal, int *pChanged){
46239   u32 aCksum[2];                  /* Checksum on the header content */
46240   WalIndexHdr h1, h2;             /* Two copies of the header content */
46241   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
46242 
46243   /* The first page of the wal-index must be mapped at this point. */
46244   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46245 
46246   /* Read the header. This might happen concurrently with a write to the
46247   ** same area of shared memory on a different CPU in a SMP,
46248   ** meaning it is possible that an inconsistent snapshot is read
46249   ** from the file. If this happens, return non-zero.
46250   **
46251   ** There are two copies of the header at the beginning of the wal-index.
46252   ** When reading, read [0] first then [1].  Writes are in the reverse order.
46253   ** Memory barriers are used to prevent the compiler or the hardware from
46254   ** reordering the reads and writes.
46255   */
46256   aHdr = walIndexHdr(pWal);
46257   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
46258   walShmBarrier(pWal);
46259   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
46260 
46261   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
46262     return 1;   /* Dirty read */
46263   }
46264   if( h1.isInit==0 ){
46265     return 1;   /* Malformed header - probably all zeros */
46266   }
46267   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
46268   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
46269     return 1;   /* Checksum does not match */
46270   }
46271 
46272   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
46273     *pChanged = 1;
46274     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
46275     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46276     testcase( pWal->szPage<=32768 );
46277     testcase( pWal->szPage>=65536 );
46278   }
46279 
46280   /* The header was successfully read. Return zero. */
46281   return 0;
46282 }
46283 
46284 /*
46285 ** Read the wal-index header from the wal-index and into pWal->hdr.
46286 ** If the wal-header appears to be corrupt, try to reconstruct the
46287 ** wal-index from the WAL before returning.
46288 **
46289 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
46290 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
46291 ** to 0.
46292 **
46293 ** If the wal-index header is successfully read, return SQLITE_OK.
46294 ** Otherwise an SQLite error code.
46295 */
46296 static int walIndexReadHdr(Wal *pWal, int *pChanged){
46297   int rc;                         /* Return code */
46298   int badHdr;                     /* True if a header read failed */
46299   volatile u32 *page0;            /* Chunk of wal-index containing header */
46300 
46301   /* Ensure that page 0 of the wal-index (the page that contains the
46302   ** wal-index header) is mapped. Return early if an error occurs here.
46303   */
46304   assert( pChanged );
46305   rc = walIndexPage(pWal, 0, &page0);
46306   if( rc!=SQLITE_OK ){
46307     return rc;
46308   };
46309   assert( page0 || pWal->writeLock==0 );
46310 
46311   /* If the first page of the wal-index has been mapped, try to read the
46312   ** wal-index header immediately, without holding any lock. This usually
46313   ** works, but may fail if the wal-index header is corrupt or currently
46314   ** being modified by another thread or process.
46315   */
46316   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
46317 
46318   /* If the first attempt failed, it might have been due to a race
46319   ** with a writer.  So get a WRITE lock and try again.
46320   */
46321   assert( badHdr==0 || pWal->writeLock==0 );
46322   if( badHdr ){
46323     if( pWal->readOnly & WAL_SHM_RDONLY ){
46324       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
46325         walUnlockShared(pWal, WAL_WRITE_LOCK);
46326         rc = SQLITE_READONLY_RECOVERY;
46327       }
46328     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
46329       pWal->writeLock = 1;
46330       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
46331         badHdr = walIndexTryHdr(pWal, pChanged);
46332         if( badHdr ){
46333           /* If the wal-index header is still malformed even while holding
46334           ** a WRITE lock, it can only mean that the header is corrupted and
46335           ** needs to be reconstructed.  So run recovery to do exactly that.
46336           */
46337           rc = walIndexRecover(pWal);
46338           *pChanged = 1;
46339         }
46340       }
46341       pWal->writeLock = 0;
46342       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46343     }
46344   }
46345 
46346   /* If the header is read successfully, check the version number to make
46347   ** sure the wal-index was not constructed with some future format that
46348   ** this version of SQLite cannot understand.
46349   */
46350   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
46351     rc = SQLITE_CANTOPEN_BKPT;
46352   }
46353 
46354   return rc;
46355 }
46356 
46357 /*
46358 ** This is the value that walTryBeginRead returns when it needs to
46359 ** be retried.
46360 */
46361 #define WAL_RETRY  (-1)
46362 
46363 /*
46364 ** Attempt to start a read transaction.  This might fail due to a race or
46365 ** other transient condition.  When that happens, it returns WAL_RETRY to
46366 ** indicate to the caller that it is safe to retry immediately.
46367 **
46368 ** On success return SQLITE_OK.  On a permanent failure (such an
46369 ** I/O error or an SQLITE_BUSY because another process is running
46370 ** recovery) return a positive error code.
46371 **
46372 ** The useWal parameter is true to force the use of the WAL and disable
46373 ** the case where the WAL is bypassed because it has been completely
46374 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
46375 ** to make a copy of the wal-index header into pWal->hdr.  If the
46376 ** wal-index header has changed, *pChanged is set to 1 (as an indication
46377 ** to the caller that the local paget cache is obsolete and needs to be
46378 ** flushed.)  When useWal==1, the wal-index header is assumed to already
46379 ** be loaded and the pChanged parameter is unused.
46380 **
46381 ** The caller must set the cnt parameter to the number of prior calls to
46382 ** this routine during the current read attempt that returned WAL_RETRY.
46383 ** This routine will start taking more aggressive measures to clear the
46384 ** race conditions after multiple WAL_RETRY returns, and after an excessive
46385 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
46386 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
46387 ** and is not honoring the locking protocol.  There is a vanishingly small
46388 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
46389 ** bad luck when there is lots of contention for the wal-index, but that
46390 ** possibility is so small that it can be safely neglected, we believe.
46391 **
46392 ** On success, this routine obtains a read lock on
46393 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
46394 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
46395 ** that means the Wal does not hold any read lock.  The reader must not
46396 ** access any database page that is modified by a WAL frame up to and
46397 ** including frame number aReadMark[pWal->readLock].  The reader will
46398 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
46399 ** Or if pWal->readLock==0, then the reader will ignore the WAL
46400 ** completely and get all content directly from the database file.
46401 ** If the useWal parameter is 1 then the WAL will never be ignored and
46402 ** this routine will always set pWal->readLock>0 on success.
46403 ** When the read transaction is completed, the caller must release the
46404 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
46405 **
46406 ** This routine uses the nBackfill and aReadMark[] fields of the header
46407 ** to select a particular WAL_READ_LOCK() that strives to let the
46408 ** checkpoint process do as much work as possible.  This routine might
46409 ** update values of the aReadMark[] array in the header, but if it does
46410 ** so it takes care to hold an exclusive lock on the corresponding
46411 ** WAL_READ_LOCK() while changing values.
46412 */
46413 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
46414   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
46415   u32 mxReadMark;                 /* Largest aReadMark[] value */
46416   int mxI;                        /* Index of largest aReadMark[] value */
46417   int i;                          /* Loop counter */
46418   int rc = SQLITE_OK;             /* Return code  */
46419 
46420   assert( pWal->readLock<0 );     /* Not currently locked */
46421 
46422   /* Take steps to avoid spinning forever if there is a protocol error.
46423   **
46424   ** Circumstances that cause a RETRY should only last for the briefest
46425   ** instances of time.  No I/O or other system calls are done while the
46426   ** locks are held, so the locks should not be held for very long. But
46427   ** if we are unlucky, another process that is holding a lock might get
46428   ** paged out or take a page-fault that is time-consuming to resolve,
46429   ** during the few nanoseconds that it is holding the lock.  In that case,
46430   ** it might take longer than normal for the lock to free.
46431   **
46432   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
46433   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
46434   ** is more of a scheduler yield than an actual delay.  But on the 10th
46435   ** an subsequent retries, the delays start becoming longer and longer,
46436   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
46437   ** The total delay time before giving up is less than 1 second.
46438   */
46439   if( cnt>5 ){
46440     int nDelay = 1;                      /* Pause time in microseconds */
46441     if( cnt>100 ){
46442       VVA_ONLY( pWal->lockError = 1; )
46443       return SQLITE_PROTOCOL;
46444     }
46445     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
46446     sqlite3OsSleep(pWal->pVfs, nDelay);
46447   }
46448 
46449   if( !useWal ){
46450     rc = walIndexReadHdr(pWal, pChanged);
46451     if( rc==SQLITE_BUSY ){
46452       /* If there is not a recovery running in another thread or process
46453       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
46454       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
46455       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
46456       ** would be technically correct.  But the race is benign since with
46457       ** WAL_RETRY this routine will be called again and will probably be
46458       ** right on the second iteration.
46459       */
46460       if( pWal->apWiData[0]==0 ){
46461         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
46462         ** We assume this is a transient condition, so return WAL_RETRY. The
46463         ** xShmMap() implementation used by the default unix and win32 VFS
46464         ** modules may return SQLITE_BUSY due to a race condition in the
46465         ** code that determines whether or not the shared-memory region
46466         ** must be zeroed before the requested page is returned.
46467         */
46468         rc = WAL_RETRY;
46469       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
46470         walUnlockShared(pWal, WAL_RECOVER_LOCK);
46471         rc = WAL_RETRY;
46472       }else if( rc==SQLITE_BUSY ){
46473         rc = SQLITE_BUSY_RECOVERY;
46474       }
46475     }
46476     if( rc!=SQLITE_OK ){
46477       return rc;
46478     }
46479   }
46480 
46481   pInfo = walCkptInfo(pWal);
46482   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
46483     /* The WAL has been completely backfilled (or it is empty).
46484     ** and can be safely ignored.
46485     */
46486     rc = walLockShared(pWal, WAL_READ_LOCK(0));
46487     walShmBarrier(pWal);
46488     if( rc==SQLITE_OK ){
46489       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
46490         /* It is not safe to allow the reader to continue here if frames
46491         ** may have been appended to the log before READ_LOCK(0) was obtained.
46492         ** When holding READ_LOCK(0), the reader ignores the entire log file,
46493         ** which implies that the database file contains a trustworthy
46494         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
46495         ** happening, this is usually correct.
46496         **
46497         ** However, if frames have been appended to the log (or if the log
46498         ** is wrapped and written for that matter) before the READ_LOCK(0)
46499         ** is obtained, that is not necessarily true. A checkpointer may
46500         ** have started to backfill the appended frames but crashed before
46501         ** it finished. Leaving a corrupt image in the database file.
46502         */
46503         walUnlockShared(pWal, WAL_READ_LOCK(0));
46504         return WAL_RETRY;
46505       }
46506       pWal->readLock = 0;
46507       return SQLITE_OK;
46508     }else if( rc!=SQLITE_BUSY ){
46509       return rc;
46510     }
46511   }
46512 
46513   /* If we get this far, it means that the reader will want to use
46514   ** the WAL to get at content from recent commits.  The job now is
46515   ** to select one of the aReadMark[] entries that is closest to
46516   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
46517   */
46518   mxReadMark = 0;
46519   mxI = 0;
46520   for(i=1; i<WAL_NREADER; i++){
46521     u32 thisMark = pInfo->aReadMark[i];
46522     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
46523       assert( thisMark!=READMARK_NOT_USED );
46524       mxReadMark = thisMark;
46525       mxI = i;
46526     }
46527   }
46528   /* There was once an "if" here. The extra "{" is to preserve indentation. */
46529   {
46530     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
46531      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
46532     ){
46533       for(i=1; i<WAL_NREADER; i++){
46534         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
46535         if( rc==SQLITE_OK ){
46536           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
46537           mxI = i;
46538           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46539           break;
46540         }else if( rc!=SQLITE_BUSY ){
46541           return rc;
46542         }
46543       }
46544     }
46545     if( mxI==0 ){
46546       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
46547       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
46548     }
46549 
46550     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
46551     if( rc ){
46552       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
46553     }
46554     /* Now that the read-lock has been obtained, check that neither the
46555     ** value in the aReadMark[] array or the contents of the wal-index
46556     ** header have changed.
46557     **
46558     ** It is necessary to check that the wal-index header did not change
46559     ** between the time it was read and when the shared-lock was obtained
46560     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
46561     ** that the log file may have been wrapped by a writer, or that frames
46562     ** that occur later in the log than pWal->hdr.mxFrame may have been
46563     ** copied into the database by a checkpointer. If either of these things
46564     ** happened, then reading the database with the current value of
46565     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
46566     ** instead.
46567     **
46568     ** This does not guarantee that the copy of the wal-index header is up to
46569     ** date before proceeding. That would not be possible without somehow
46570     ** blocking writers. It only guarantees that a dangerous checkpoint or
46571     ** log-wrap (either of which would require an exclusive lock on
46572     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
46573     */
46574     walShmBarrier(pWal);
46575     if( pInfo->aReadMark[mxI]!=mxReadMark
46576      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
46577     ){
46578       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
46579       return WAL_RETRY;
46580     }else{
46581       assert( mxReadMark<=pWal->hdr.mxFrame );
46582       pWal->readLock = (i16)mxI;
46583     }
46584   }
46585   return rc;
46586 }
46587 
46588 /*
46589 ** Begin a read transaction on the database.
46590 **
46591 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
46592 ** it takes a snapshot of the state of the WAL and wal-index for the current
46593 ** instant in time.  The current thread will continue to use this snapshot.
46594 ** Other threads might append new content to the WAL and wal-index but
46595 ** that extra content is ignored by the current thread.
46596 **
46597 ** If the database contents have changes since the previous read
46598 ** transaction, then *pChanged is set to 1 before returning.  The
46599 ** Pager layer will use this to know that is cache is stale and
46600 ** needs to be flushed.
46601 */
46602 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
46603   int rc;                         /* Return code */
46604   int cnt = 0;                    /* Number of TryBeginRead attempts */
46605 
46606   do{
46607     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
46608   }while( rc==WAL_RETRY );
46609   testcase( (rc&0xff)==SQLITE_BUSY );
46610   testcase( (rc&0xff)==SQLITE_IOERR );
46611   testcase( rc==SQLITE_PROTOCOL );
46612   testcase( rc==SQLITE_OK );
46613   return rc;
46614 }
46615 
46616 /*
46617 ** Finish with a read transaction.  All this does is release the
46618 ** read-lock.
46619 */
46620 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
46621   sqlite3WalEndWriteTransaction(pWal);
46622   if( pWal->readLock>=0 ){
46623     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46624     pWal->readLock = -1;
46625   }
46626 }
46627 
46628 /*
46629 ** Read a page from the WAL, if it is present in the WAL and if the
46630 ** current read transaction is configured to use the WAL.
46631 **
46632 ** The *pInWal is set to 1 if the requested page is in the WAL and
46633 ** has been loaded.  Or *pInWal is set to 0 if the page was not in
46634 ** the WAL and needs to be read out of the database.
46635 */
46636 SQLITE_PRIVATE int sqlite3WalRead(
46637   Wal *pWal,                      /* WAL handle */
46638   Pgno pgno,                      /* Database page number to read data for */
46639   int *pInWal,                    /* OUT: True if data is read from WAL */
46640   int nOut,                       /* Size of buffer pOut in bytes */
46641   u8 *pOut                        /* Buffer to write page data to */
46642 ){
46643   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
46644   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
46645   int iHash;                      /* Used to loop through N hash tables */
46646 
46647   /* This routine is only be called from within a read transaction. */
46648   assert( pWal->readLock>=0 || pWal->lockError );
46649 
46650   /* If the "last page" field of the wal-index header snapshot is 0, then
46651   ** no data will be read from the wal under any circumstances. Return early
46652   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
46653   ** then the WAL is ignored by the reader so return early, as if the
46654   ** WAL were empty.
46655   */
46656   if( iLast==0 || pWal->readLock==0 ){
46657     *pInWal = 0;
46658     return SQLITE_OK;
46659   }
46660 
46661   /* Search the hash table or tables for an entry matching page number
46662   ** pgno. Each iteration of the following for() loop searches one
46663   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
46664   **
46665   ** This code might run concurrently to the code in walIndexAppend()
46666   ** that adds entries to the wal-index (and possibly to this hash
46667   ** table). This means the value just read from the hash
46668   ** slot (aHash[iKey]) may have been added before or after the
46669   ** current read transaction was opened. Values added after the
46670   ** read transaction was opened may have been written incorrectly -
46671   ** i.e. these slots may contain garbage data. However, we assume
46672   ** that any slots written before the current read transaction was
46673   ** opened remain unmodified.
46674   **
46675   ** For the reasons above, the if(...) condition featured in the inner
46676   ** loop of the following block is more stringent that would be required
46677   ** if we had exclusive access to the hash-table:
46678   **
46679   **   (aPgno[iFrame]==pgno):
46680   **     This condition filters out normal hash-table collisions.
46681   **
46682   **   (iFrame<=iLast):
46683   **     This condition filters out entries that were added to the hash
46684   **     table after the current read-transaction had started.
46685   */
46686   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
46687     volatile ht_slot *aHash;      /* Pointer to hash table */
46688     volatile u32 *aPgno;          /* Pointer to array of page numbers */
46689     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
46690     int iKey;                     /* Hash slot index */
46691     int nCollide;                 /* Number of hash collisions remaining */
46692     int rc;                       /* Error code */
46693 
46694     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
46695     if( rc!=SQLITE_OK ){
46696       return rc;
46697     }
46698     nCollide = HASHTABLE_NSLOT;
46699     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
46700       u32 iFrame = aHash[iKey] + iZero;
46701       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
46702         /* assert( iFrame>iRead ); -- not true if there is corruption */
46703         iRead = iFrame;
46704       }
46705       if( (nCollide--)==0 ){
46706         return SQLITE_CORRUPT_BKPT;
46707       }
46708     }
46709   }
46710 
46711 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46712   /* If expensive assert() statements are available, do a linear search
46713   ** of the wal-index file content. Make sure the results agree with the
46714   ** result obtained using the hash indexes above.  */
46715   {
46716     u32 iRead2 = 0;
46717     u32 iTest;
46718     for(iTest=iLast; iTest>0; iTest--){
46719       if( walFramePgno(pWal, iTest)==pgno ){
46720         iRead2 = iTest;
46721         break;
46722       }
46723     }
46724     assert( iRead==iRead2 );
46725   }
46726 #endif
46727 
46728   /* If iRead is non-zero, then it is the log frame number that contains the
46729   ** required page. Read and return data from the log file.
46730   */
46731   if( iRead ){
46732     int sz;
46733     i64 iOffset;
46734     sz = pWal->hdr.szPage;
46735     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
46736     testcase( sz<=32768 );
46737     testcase( sz>=65536 );
46738     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
46739     *pInWal = 1;
46740     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46741     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
46742   }
46743 
46744   *pInWal = 0;
46745   return SQLITE_OK;
46746 }
46747 
46748 
46749 /*
46750 ** Return the size of the database in pages (or zero, if unknown).
46751 */
46752 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
46753   if( pWal && ALWAYS(pWal->readLock>=0) ){
46754     return pWal->hdr.nPage;
46755   }
46756   return 0;
46757 }
46758 
46759 
46760 /*
46761 ** This function starts a write transaction on the WAL.
46762 **
46763 ** A read transaction must have already been started by a prior call
46764 ** to sqlite3WalBeginReadTransaction().
46765 **
46766 ** If another thread or process has written into the database since
46767 ** the read transaction was started, then it is not possible for this
46768 ** thread to write as doing so would cause a fork.  So this routine
46769 ** returns SQLITE_BUSY in that case and no write transaction is started.
46770 **
46771 ** There can only be a single writer active at a time.
46772 */
46773 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46774   int rc;
46775 
46776   /* Cannot start a write transaction without first holding a read
46777   ** transaction. */
46778   assert( pWal->readLock>=0 );
46779 
46780   if( pWal->readOnly ){
46781     return SQLITE_READONLY;
46782   }
46783 
46784   /* Only one writer allowed at a time.  Get the write lock.  Return
46785   ** SQLITE_BUSY if unable.
46786   */
46787   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46788   if( rc ){
46789     return rc;
46790   }
46791   pWal->writeLock = 1;
46792 
46793   /* If another connection has written to the database file since the
46794   ** time the read transaction on this connection was started, then
46795   ** the write is disallowed.
46796   */
46797   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46798     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46799     pWal->writeLock = 0;
46800     rc = SQLITE_BUSY;
46801   }
46802 
46803   return rc;
46804 }
46805 
46806 /*
46807 ** End a write transaction.  The commit has already been done.  This
46808 ** routine merely releases the lock.
46809 */
46810 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46811   if( pWal->writeLock ){
46812     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46813     pWal->writeLock = 0;
46814     pWal->truncateOnCommit = 0;
46815   }
46816   return SQLITE_OK;
46817 }
46818 
46819 /*
46820 ** If any data has been written (but not committed) to the log file, this
46821 ** function moves the write-pointer back to the start of the transaction.
46822 **
46823 ** Additionally, the callback function is invoked for each frame written
46824 ** to the WAL since the start of the transaction. If the callback returns
46825 ** other than SQLITE_OK, it is not invoked again and the error code is
46826 ** returned to the caller.
46827 **
46828 ** Otherwise, if the callback function does not return an error, this
46829 ** function returns SQLITE_OK.
46830 */
46831 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46832   int rc = SQLITE_OK;
46833   if( ALWAYS(pWal->writeLock) ){
46834     Pgno iMax = pWal->hdr.mxFrame;
46835     Pgno iFrame;
46836 
46837     /* Restore the clients cache of the wal-index header to the state it
46838     ** was in before the client began writing to the database.
46839     */
46840     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46841 
46842     for(iFrame=pWal->hdr.mxFrame+1;
46843         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
46844         iFrame++
46845     ){
46846       /* This call cannot fail. Unless the page for which the page number
46847       ** is passed as the second argument is (a) in the cache and
46848       ** (b) has an outstanding reference, then xUndo is either a no-op
46849       ** (if (a) is false) or simply expels the page from the cache (if (b)
46850       ** is false).
46851       **
46852       ** If the upper layer is doing a rollback, it is guaranteed that there
46853       ** are no outstanding references to any page other than page 1. And
46854       ** page 1 is never written to the log until the transaction is
46855       ** committed. As a result, the call to xUndo may not fail.
46856       */
46857       assert( walFramePgno(pWal, iFrame)!=1 );
46858       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46859     }
46860     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
46861   }
46862   assert( rc==SQLITE_OK );
46863   return rc;
46864 }
46865 
46866 /*
46867 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
46868 ** values. This function populates the array with values required to
46869 ** "rollback" the write position of the WAL handle back to the current
46870 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46871 */
46872 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46873   assert( pWal->writeLock );
46874   aWalData[0] = pWal->hdr.mxFrame;
46875   aWalData[1] = pWal->hdr.aFrameCksum[0];
46876   aWalData[2] = pWal->hdr.aFrameCksum[1];
46877   aWalData[3] = pWal->nCkpt;
46878 }
46879 
46880 /*
46881 ** Move the write position of the WAL back to the point identified by
46882 ** the values in the aWalData[] array. aWalData must point to an array
46883 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46884 ** by a call to WalSavepoint().
46885 */
46886 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46887   int rc = SQLITE_OK;
46888 
46889   assert( pWal->writeLock );
46890   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46891 
46892   if( aWalData[3]!=pWal->nCkpt ){
46893     /* This savepoint was opened immediately after the write-transaction
46894     ** was started. Right after that, the writer decided to wrap around
46895     ** to the start of the log. Update the savepoint values to match.
46896     */
46897     aWalData[0] = 0;
46898     aWalData[3] = pWal->nCkpt;
46899   }
46900 
46901   if( aWalData[0]<pWal->hdr.mxFrame ){
46902     pWal->hdr.mxFrame = aWalData[0];
46903     pWal->hdr.aFrameCksum[0] = aWalData[1];
46904     pWal->hdr.aFrameCksum[1] = aWalData[2];
46905     walCleanupHash(pWal);
46906   }
46907 
46908   return rc;
46909 }
46910 
46911 
46912 /*
46913 ** This function is called just before writing a set of frames to the log
46914 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46915 ** to the current log file, it is possible to overwrite the start of the
46916 ** existing log file with the new frames (i.e. "reset" the log). If so,
46917 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46918 ** unchanged.
46919 **
46920 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46921 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46922 ** if an error occurs.
46923 */
46924 static int walRestartLog(Wal *pWal){
46925   int rc = SQLITE_OK;
46926   int cnt;
46927 
46928   if( pWal->readLock==0 ){
46929     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46930     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46931     if( pInfo->nBackfill>0 ){
46932       u32 salt1;
46933       sqlite3_randomness(4, &salt1);
46934       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46935       if( rc==SQLITE_OK ){
46936         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46937         ** readers are currently using the WAL), then the transactions
46938         ** frames will overwrite the start of the existing log. Update the
46939         ** wal-index header to reflect this.
46940         **
46941         ** In theory it would be Ok to update the cache of the header only
46942         ** at this point. But updating the actual wal-index header is also
46943         ** safe and means there is no special case for sqlite3WalUndo()
46944         ** to handle if this transaction is rolled back.
46945         */
46946         int i;                    /* Loop counter */
46947         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
46948 
46949         pWal->nCkpt++;
46950         pWal->hdr.mxFrame = 0;
46951         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46952         aSalt[1] = salt1;
46953         walIndexWriteHdr(pWal);
46954         pInfo->nBackfill = 0;
46955         pInfo->aReadMark[1] = 0;
46956         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46957         assert( pInfo->aReadMark[0]==0 );
46958         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46959       }else if( rc!=SQLITE_BUSY ){
46960         return rc;
46961       }
46962     }
46963     walUnlockShared(pWal, WAL_READ_LOCK(0));
46964     pWal->readLock = -1;
46965     cnt = 0;
46966     do{
46967       int notUsed;
46968       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46969     }while( rc==WAL_RETRY );
46970     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46971     testcase( (rc&0xff)==SQLITE_IOERR );
46972     testcase( rc==SQLITE_PROTOCOL );
46973     testcase( rc==SQLITE_OK );
46974   }
46975   return rc;
46976 }
46977 
46978 /*
46979 ** Information about the current state of the WAL file and where
46980 ** the next fsync should occur - passed from sqlite3WalFrames() into
46981 ** walWriteToLog().
46982 */
46983 typedef struct WalWriter {
46984   Wal *pWal;                   /* The complete WAL information */
46985   sqlite3_file *pFd;           /* The WAL file to which we write */
46986   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
46987   int syncFlags;               /* Flags for the fsync */
46988   int szPage;                  /* Size of one page */
46989 } WalWriter;
46990 
46991 /*
46992 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
46993 ** Do a sync when crossing the p->iSyncPoint boundary.
46994 **
46995 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
46996 ** first write the part before iSyncPoint, then sync, then write the
46997 ** rest.
46998 */
46999 static int walWriteToLog(
47000   WalWriter *p,              /* WAL to write to */
47001   void *pContent,            /* Content to be written */
47002   int iAmt,                  /* Number of bytes to write */
47003   sqlite3_int64 iOffset      /* Start writing at this offset */
47004 ){
47005   int rc;
47006   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
47007     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
47008     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
47009     if( rc ) return rc;
47010     iOffset += iFirstAmt;
47011     iAmt -= iFirstAmt;
47012     pContent = (void*)(iFirstAmt + (char*)pContent);
47013     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
47014     rc = sqlite3OsSync(p->pFd, p->syncFlags);
47015     if( iAmt==0 || rc ) return rc;
47016   }
47017   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
47018   return rc;
47019 }
47020 
47021 /*
47022 ** Write out a single frame of the WAL
47023 */
47024 static int walWriteOneFrame(
47025   WalWriter *p,               /* Where to write the frame */
47026   PgHdr *pPage,               /* The page of the frame to be written */
47027   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
47028   sqlite3_int64 iOffset       /* Byte offset at which to write */
47029 ){
47030   int rc;                         /* Result code from subfunctions */
47031   void *pData;                    /* Data actually written */
47032   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
47033 #if defined(SQLITE_HAS_CODEC)
47034   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
47035 #else
47036   pData = pPage->pData;
47037 #endif
47038   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
47039   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
47040   if( rc ) return rc;
47041   /* Write the page data */
47042   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
47043   return rc;
47044 }
47045 
47046 /*
47047 ** Write a set of frames to the log. The caller must hold the write-lock
47048 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
47049 */
47050 SQLITE_PRIVATE int sqlite3WalFrames(
47051   Wal *pWal,                      /* Wal handle to write to */
47052   int szPage,                     /* Database page-size in bytes */
47053   PgHdr *pList,                   /* List of dirty pages to write */
47054   Pgno nTruncate,                 /* Database size after this commit */
47055   int isCommit,                   /* True if this is a commit */
47056   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
47057 ){
47058   int rc;                         /* Used to catch return codes */
47059   u32 iFrame;                     /* Next frame address */
47060   PgHdr *p;                       /* Iterator to run through pList with. */
47061   PgHdr *pLast = 0;               /* Last frame in list */
47062   int nExtra = 0;                 /* Number of extra copies of last page */
47063   int szFrame;                    /* The size of a single frame */
47064   i64 iOffset;                    /* Next byte to write in WAL file */
47065   WalWriter w;                    /* The writer */
47066 
47067   assert( pList );
47068   assert( pWal->writeLock );
47069 
47070   /* If this frame set completes a transaction, then nTruncate>0.  If
47071   ** nTruncate==0 then this frame set does not complete the transaction. */
47072   assert( (isCommit!=0)==(nTruncate!=0) );
47073 
47074 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47075   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
47076     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
47077               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
47078   }
47079 #endif
47080 
47081   /* See if it is possible to write these frames into the start of the
47082   ** log file, instead of appending to it at pWal->hdr.mxFrame.
47083   */
47084   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
47085     return rc;
47086   }
47087 
47088   /* If this is the first frame written into the log, write the WAL
47089   ** header to the start of the WAL file. See comments at the top of
47090   ** this source file for a description of the WAL header format.
47091   */
47092   iFrame = pWal->hdr.mxFrame;
47093   if( iFrame==0 ){
47094     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
47095     u32 aCksum[2];                /* Checksum for wal-header */
47096 
47097     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
47098     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
47099     sqlite3Put4byte(&aWalHdr[8], szPage);
47100     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
47101     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
47102     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
47103     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
47104     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
47105     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
47106 
47107     pWal->szPage = szPage;
47108     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
47109     pWal->hdr.aFrameCksum[0] = aCksum[0];
47110     pWal->hdr.aFrameCksum[1] = aCksum[1];
47111     pWal->truncateOnCommit = 1;
47112 
47113     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
47114     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
47115     if( rc!=SQLITE_OK ){
47116       return rc;
47117     }
47118 
47119     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
47120     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
47121     ** an out-of-order write following a WAL restart could result in
47122     ** database corruption.  See the ticket:
47123     **
47124     **     http://localhost:591/sqlite/info/ff5be73dee
47125     */
47126     if( pWal->syncHeader && sync_flags ){
47127       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
47128       if( rc ) return rc;
47129     }
47130   }
47131   assert( (int)pWal->szPage==szPage );
47132 
47133   /* Setup information needed to write frames into the WAL */
47134   w.pWal = pWal;
47135   w.pFd = pWal->pWalFd;
47136   w.iSyncPoint = 0;
47137   w.syncFlags = sync_flags;
47138   w.szPage = szPage;
47139   iOffset = walFrameOffset(iFrame+1, szPage);
47140   szFrame = szPage + WAL_FRAME_HDRSIZE;
47141 
47142   /* Write all frames into the log file exactly once */
47143   for(p=pList; p; p=p->pDirty){
47144     int nDbSize;   /* 0 normally.  Positive == commit flag */
47145     iFrame++;
47146     assert( iOffset==walFrameOffset(iFrame, szPage) );
47147     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
47148     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
47149     if( rc ) return rc;
47150     pLast = p;
47151     iOffset += szFrame;
47152   }
47153 
47154   /* If this is the end of a transaction, then we might need to pad
47155   ** the transaction and/or sync the WAL file.
47156   **
47157   ** Padding and syncing only occur if this set of frames complete a
47158   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
47159   ** or synchonous==OFF, then no padding or syncing are needed.
47160   **
47161   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
47162   ** needed and only the sync is done.  If padding is needed, then the
47163   ** final frame is repeated (with its commit mark) until the next sector
47164   ** boundary is crossed.  Only the part of the WAL prior to the last
47165   ** sector boundary is synced; the part of the last frame that extends
47166   ** past the sector boundary is written after the sync.
47167   */
47168   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
47169     if( pWal->padToSectorBoundary ){
47170       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
47171       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
47172       while( iOffset<w.iSyncPoint ){
47173         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
47174         if( rc ) return rc;
47175         iOffset += szFrame;
47176         nExtra++;
47177       }
47178     }else{
47179       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
47180     }
47181   }
47182 
47183   /* If this frame set completes the first transaction in the WAL and
47184   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
47185   ** journal size limit, if possible.
47186   */
47187   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
47188     i64 sz = pWal->mxWalSize;
47189     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
47190       sz = walFrameOffset(iFrame+nExtra+1, szPage);
47191     }
47192     walLimitSize(pWal, sz);
47193     pWal->truncateOnCommit = 0;
47194   }
47195 
47196   /* Append data to the wal-index. It is not necessary to lock the
47197   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
47198   ** guarantees that there are no other writers, and no data that may
47199   ** be in use by existing readers is being overwritten.
47200   */
47201   iFrame = pWal->hdr.mxFrame;
47202   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
47203     iFrame++;
47204     rc = walIndexAppend(pWal, iFrame, p->pgno);
47205   }
47206   while( rc==SQLITE_OK && nExtra>0 ){
47207     iFrame++;
47208     nExtra--;
47209     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
47210   }
47211 
47212   if( rc==SQLITE_OK ){
47213     /* Update the private copy of the header. */
47214     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47215     testcase( szPage<=32768 );
47216     testcase( szPage>=65536 );
47217     pWal->hdr.mxFrame = iFrame;
47218     if( isCommit ){
47219       pWal->hdr.iChange++;
47220       pWal->hdr.nPage = nTruncate;
47221     }
47222     /* If this is a commit, update the wal-index header too. */
47223     if( isCommit ){
47224       walIndexWriteHdr(pWal);
47225       pWal->iCallback = iFrame;
47226     }
47227   }
47228 
47229   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
47230   return rc;
47231 }
47232 
47233 /*
47234 ** This routine is called to implement sqlite3_wal_checkpoint() and
47235 ** related interfaces.
47236 **
47237 ** Obtain a CHECKPOINT lock and then backfill as much information as
47238 ** we can from WAL into the database.
47239 **
47240 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
47241 ** callback. In this case this function runs a blocking checkpoint.
47242 */
47243 SQLITE_PRIVATE int sqlite3WalCheckpoint(
47244   Wal *pWal,                      /* Wal connection */
47245   int eMode,                      /* PASSIVE, FULL or RESTART */
47246   int (*xBusy)(void*),            /* Function to call when busy */
47247   void *pBusyArg,                 /* Context argument for xBusyHandler */
47248   int sync_flags,                 /* Flags to sync db file with (or 0) */
47249   int nBuf,                       /* Size of temporary buffer */
47250   u8 *zBuf,                       /* Temporary buffer to use */
47251   int *pnLog,                     /* OUT: Number of frames in WAL */
47252   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
47253 ){
47254   int rc;                         /* Return code */
47255   int isChanged = 0;              /* True if a new wal-index header is loaded */
47256   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
47257 
47258   assert( pWal->ckptLock==0 );
47259   assert( pWal->writeLock==0 );
47260 
47261   if( pWal->readOnly ) return SQLITE_READONLY;
47262   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
47263   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
47264   if( rc ){
47265     /* Usually this is SQLITE_BUSY meaning that another thread or process
47266     ** is already running a checkpoint, or maybe a recovery.  But it might
47267     ** also be SQLITE_IOERR. */
47268     return rc;
47269   }
47270   pWal->ckptLock = 1;
47271 
47272   /* If this is a blocking-checkpoint, then obtain the write-lock as well
47273   ** to prevent any writers from running while the checkpoint is underway.
47274   ** This has to be done before the call to walIndexReadHdr() below.
47275   **
47276   ** If the writer lock cannot be obtained, then a passive checkpoint is
47277   ** run instead. Since the checkpointer is not holding the writer lock,
47278   ** there is no point in blocking waiting for any readers. Assuming no
47279   ** other error occurs, this function will return SQLITE_BUSY to the caller.
47280   */
47281   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47282     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
47283     if( rc==SQLITE_OK ){
47284       pWal->writeLock = 1;
47285     }else if( rc==SQLITE_BUSY ){
47286       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
47287       rc = SQLITE_OK;
47288     }
47289   }
47290 
47291   /* Read the wal-index header. */
47292   if( rc==SQLITE_OK ){
47293     rc = walIndexReadHdr(pWal, &isChanged);
47294   }
47295 
47296   /* Copy data from the log to the database file. */
47297   if( rc==SQLITE_OK ){
47298     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
47299       rc = SQLITE_CORRUPT_BKPT;
47300     }else{
47301       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
47302     }
47303 
47304     /* If no error occurred, set the output variables. */
47305     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
47306       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
47307       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
47308     }
47309   }
47310 
47311   if( isChanged ){
47312     /* If a new wal-index header was loaded before the checkpoint was
47313     ** performed, then the pager-cache associated with pWal is now
47314     ** out of date. So zero the cached wal-index header to ensure that
47315     ** next time the pager opens a snapshot on this database it knows that
47316     ** the cache needs to be reset.
47317     */
47318     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47319   }
47320 
47321   /* Release the locks. */
47322   sqlite3WalEndWriteTransaction(pWal);
47323   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
47324   pWal->ckptLock = 0;
47325   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
47326   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
47327 }
47328 
47329 /* Return the value to pass to a sqlite3_wal_hook callback, the
47330 ** number of frames in the WAL at the point of the last commit since
47331 ** sqlite3WalCallback() was called.  If no commits have occurred since
47332 ** the last call, then return 0.
47333 */
47334 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
47335   u32 ret = 0;
47336   if( pWal ){
47337     ret = pWal->iCallback;
47338     pWal->iCallback = 0;
47339   }
47340   return (int)ret;
47341 }
47342 
47343 /*
47344 ** This function is called to change the WAL subsystem into or out
47345 ** of locking_mode=EXCLUSIVE.
47346 **
47347 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
47348 ** into locking_mode=NORMAL.  This means that we must acquire a lock
47349 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
47350 ** or if the acquisition of the lock fails, then return 0.  If the
47351 ** transition out of exclusive-mode is successful, return 1.  This
47352 ** operation must occur while the pager is still holding the exclusive
47353 ** lock on the main database file.
47354 **
47355 ** If op is one, then change from locking_mode=NORMAL into
47356 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
47357 ** be released.  Return 1 if the transition is made and 0 if the
47358 ** WAL is already in exclusive-locking mode - meaning that this
47359 ** routine is a no-op.  The pager must already hold the exclusive lock
47360 ** on the main database file before invoking this operation.
47361 **
47362 ** If op is negative, then do a dry-run of the op==1 case but do
47363 ** not actually change anything. The pager uses this to see if it
47364 ** should acquire the database exclusive lock prior to invoking
47365 ** the op==1 case.
47366 */
47367 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
47368   int rc;
47369   assert( pWal->writeLock==0 );
47370   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
47371 
47372   /* pWal->readLock is usually set, but might be -1 if there was a
47373   ** prior error while attempting to acquire are read-lock. This cannot
47374   ** happen if the connection is actually in exclusive mode (as no xShmLock
47375   ** locks are taken in this case). Nor should the pager attempt to
47376   ** upgrade to exclusive-mode following such an error.
47377   */
47378   assert( pWal->readLock>=0 || pWal->lockError );
47379   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
47380 
47381   if( op==0 ){
47382     if( pWal->exclusiveMode ){
47383       pWal->exclusiveMode = 0;
47384       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
47385         pWal->exclusiveMode = 1;
47386       }
47387       rc = pWal->exclusiveMode==0;
47388     }else{
47389       /* Already in locking_mode=NORMAL */
47390       rc = 0;
47391     }
47392   }else if( op>0 ){
47393     assert( pWal->exclusiveMode==0 );
47394     assert( pWal->readLock>=0 );
47395     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47396     pWal->exclusiveMode = 1;
47397     rc = 1;
47398   }else{
47399     rc = pWal->exclusiveMode==0;
47400   }
47401   return rc;
47402 }
47403 
47404 /*
47405 ** Return true if the argument is non-NULL and the WAL module is using
47406 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47407 ** WAL module is using shared-memory, return false.
47408 */
47409 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
47410   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
47411 }
47412 
47413 #ifdef SQLITE_ENABLE_ZIPVFS
47414 /*
47415 ** If the argument is not NULL, it points to a Wal object that holds a
47416 ** read-lock. This function returns the database page-size if it is known,
47417 ** or zero if it is not (or if pWal is NULL).
47418 */
47419 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
47420   assert( pWal==0 || pWal->readLock>=0 );
47421   return (pWal ? pWal->szPage : 0);
47422 }
47423 #endif
47424 
47425 #endif /* #ifndef SQLITE_OMIT_WAL */
47426 
47427 /************** End of wal.c *************************************************/
47428 /************** Begin file btmutex.c *****************************************/
47429 /*
47430 ** 2007 August 27
47431 **
47432 ** The author disclaims copyright to this source code.  In place of
47433 ** a legal notice, here is a blessing:
47434 **
47435 **    May you do good and not evil.
47436 **    May you find forgiveness for yourself and forgive others.
47437 **    May you share freely, never taking more than you give.
47438 **
47439 *************************************************************************
47440 **
47441 ** This file contains code used to implement mutexes on Btree objects.
47442 ** This code really belongs in btree.c.  But btree.c is getting too
47443 ** big and we want to break it down some.  This packaged seemed like
47444 ** a good breakout.
47445 */
47446 /************** Include btreeInt.h in the middle of btmutex.c ****************/
47447 /************** Begin file btreeInt.h ****************************************/
47448 /*
47449 ** 2004 April 6
47450 **
47451 ** The author disclaims copyright to this source code.  In place of
47452 ** a legal notice, here is a blessing:
47453 **
47454 **    May you do good and not evil.
47455 **    May you find forgiveness for yourself and forgive others.
47456 **    May you share freely, never taking more than you give.
47457 **
47458 *************************************************************************
47459 ** This file implements a external (disk-based) database using BTrees.
47460 ** For a detailed discussion of BTrees, refer to
47461 **
47462 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
47463 **     "Sorting And Searching", pages 473-480. Addison-Wesley
47464 **     Publishing Company, Reading, Massachusetts.
47465 **
47466 ** The basic idea is that each page of the file contains N database
47467 ** entries and N+1 pointers to subpages.
47468 **
47469 **   ----------------------------------------------------------------
47470 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
47471 **   ----------------------------------------------------------------
47472 **
47473 ** All of the keys on the page that Ptr(0) points to have values less
47474 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
47475 ** values greater than Key(0) and less than Key(1).  All of the keys
47476 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
47477 ** so forth.
47478 **
47479 ** Finding a particular key requires reading O(log(M)) pages from the
47480 ** disk where M is the number of entries in the tree.
47481 **
47482 ** In this implementation, a single file can hold one or more separate
47483 ** BTrees.  Each BTree is identified by the index of its root page.  The
47484 ** key and data for any entry are combined to form the "payload".  A
47485 ** fixed amount of payload can be carried directly on the database
47486 ** page.  If the payload is larger than the preset amount then surplus
47487 ** bytes are stored on overflow pages.  The payload for an entry
47488 ** and the preceding pointer are combined to form a "Cell".  Each
47489 ** page has a small header which contains the Ptr(N) pointer and other
47490 ** information such as the size of key and data.
47491 **
47492 ** FORMAT DETAILS
47493 **
47494 ** The file is divided into pages.  The first page is called page 1,
47495 ** the second is page 2, and so forth.  A page number of zero indicates
47496 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
47497 ** Each page can be either a btree page, a freelist page, an overflow
47498 ** page, or a pointer-map page.
47499 **
47500 ** The first page is always a btree page.  The first 100 bytes of the first
47501 ** page contain a special header (the "file header") that describes the file.
47502 ** The format of the file header is as follows:
47503 **
47504 **   OFFSET   SIZE    DESCRIPTION
47505 **      0      16     Header string: "SQLite format 3\000"
47506 **     16       2     Page size in bytes.
47507 **     18       1     File format write version
47508 **     19       1     File format read version
47509 **     20       1     Bytes of unused space at the end of each page
47510 **     21       1     Max embedded payload fraction
47511 **     22       1     Min embedded payload fraction
47512 **     23       1     Min leaf payload fraction
47513 **     24       4     File change counter
47514 **     28       4     Reserved for future use
47515 **     32       4     First freelist page
47516 **     36       4     Number of freelist pages in the file
47517 **     40      60     15 4-byte meta values passed to higher layers
47518 **
47519 **     40       4     Schema cookie
47520 **     44       4     File format of schema layer
47521 **     48       4     Size of page cache
47522 **     52       4     Largest root-page (auto/incr_vacuum)
47523 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
47524 **     60       4     User version
47525 **     64       4     Incremental vacuum mode
47526 **     68       4     unused
47527 **     72       4     unused
47528 **     76       4     unused
47529 **
47530 ** All of the integer values are big-endian (most significant byte first).
47531 **
47532 ** The file change counter is incremented when the database is changed
47533 ** This counter allows other processes to know when the file has changed
47534 ** and thus when they need to flush their cache.
47535 **
47536 ** The max embedded payload fraction is the amount of the total usable
47537 ** space in a page that can be consumed by a single cell for standard
47538 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
47539 ** is to limit the maximum cell size so that at least 4 cells will fit
47540 ** on one page.  Thus the default max embedded payload fraction is 64.
47541 **
47542 ** If the payload for a cell is larger than the max payload, then extra
47543 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
47544 ** as many bytes as possible are moved into the overflow pages without letting
47545 ** the cell size drop below the min embedded payload fraction.
47546 **
47547 ** The min leaf payload fraction is like the min embedded payload fraction
47548 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
47549 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
47550 ** not specified in the header.
47551 **
47552 ** Each btree pages is divided into three sections:  The header, the
47553 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
47554 ** file header that occurs before the page header.
47555 **
47556 **      |----------------|
47557 **      | file header    |   100 bytes.  Page 1 only.
47558 **      |----------------|
47559 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
47560 **      |----------------|
47561 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
47562 **      | array          |   |  Grows downward
47563 **      |                |   v
47564 **      |----------------|
47565 **      | unallocated    |
47566 **      | space          |
47567 **      |----------------|   ^  Grows upwards
47568 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
47569 **      | area           |   |  and free space fragments.
47570 **      |----------------|
47571 **
47572 ** The page headers looks like this:
47573 **
47574 **   OFFSET   SIZE     DESCRIPTION
47575 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
47576 **      1       2      byte offset to the first freeblock
47577 **      3       2      number of cells on this page
47578 **      5       2      first byte of the cell content area
47579 **      7       1      number of fragmented free bytes
47580 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
47581 **
47582 ** The flags define the format of this btree page.  The leaf flag means that
47583 ** this page has no children.  The zerodata flag means that this page carries
47584 ** only keys and no data.  The intkey flag means that the key is a integer
47585 ** which is stored in the key size entry of the cell header rather than in
47586 ** the payload area.
47587 **
47588 ** The cell pointer array begins on the first byte after the page header.
47589 ** The cell pointer array contains zero or more 2-byte numbers which are
47590 ** offsets from the beginning of the page to the cell content in the cell
47591 ** content area.  The cell pointers occur in sorted order.  The system strives
47592 ** to keep free space after the last cell pointer so that new cells can
47593 ** be easily added without having to defragment the page.
47594 **
47595 ** Cell content is stored at the very end of the page and grows toward the
47596 ** beginning of the page.
47597 **
47598 ** Unused space within the cell content area is collected into a linked list of
47599 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
47600 ** to the first freeblock is given in the header.  Freeblocks occur in
47601 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
47602 ** any group of 3 or fewer unused bytes in the cell content area cannot
47603 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
47604 ** a fragment.  The total number of bytes in all fragments is recorded.
47605 ** in the page header at offset 7.
47606 **
47607 **    SIZE    DESCRIPTION
47608 **      2     Byte offset of the next freeblock
47609 **      2     Bytes in this freeblock
47610 **
47611 ** Cells are of variable length.  Cells are stored in the cell content area at
47612 ** the end of the page.  Pointers to the cells are in the cell pointer array
47613 ** that immediately follows the page header.  Cells is not necessarily
47614 ** contiguous or in order, but cell pointers are contiguous and in order.
47615 **
47616 ** Cell content makes use of variable length integers.  A variable
47617 ** length integer is 1 to 9 bytes where the lower 7 bits of each
47618 ** byte are used.  The integer consists of all bytes that have bit 8 set and
47619 ** the first byte with bit 8 clear.  The most significant byte of the integer
47620 ** appears first.  A variable-length integer may not be more than 9 bytes long.
47621 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
47622 ** allows a 64-bit integer to be encoded in 9 bytes.
47623 **
47624 **    0x00                      becomes  0x00000000
47625 **    0x7f                      becomes  0x0000007f
47626 **    0x81 0x00                 becomes  0x00000080
47627 **    0x82 0x00                 becomes  0x00000100
47628 **    0x80 0x7f                 becomes  0x0000007f
47629 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
47630 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
47631 **
47632 ** Variable length integers are used for rowids and to hold the number of
47633 ** bytes of key and data in a btree cell.
47634 **
47635 ** The content of a cell looks like this:
47636 **
47637 **    SIZE    DESCRIPTION
47638 **      4     Page number of the left child. Omitted if leaf flag is set.
47639 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
47640 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
47641 **      *     Payload
47642 **      4     First page of the overflow chain.  Omitted if no overflow
47643 **
47644 ** Overflow pages form a linked list.  Each page except the last is completely
47645 ** filled with data (pagesize - 4 bytes).  The last page can have as little
47646 ** as 1 byte of data.
47647 **
47648 **    SIZE    DESCRIPTION
47649 **      4     Page number of next overflow page
47650 **      *     Data
47651 **
47652 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
47653 ** file header points to the first in a linked list of trunk page.  Each trunk
47654 ** page points to multiple leaf pages.  The content of a leaf page is
47655 ** unspecified.  A trunk page looks like this:
47656 **
47657 **    SIZE    DESCRIPTION
47658 **      4     Page number of next trunk page
47659 **      4     Number of leaf pointers on this page
47660 **      *     zero or more pages numbers of leaves
47661 */
47662 
47663 
47664 /* The following value is the maximum cell size assuming a maximum page
47665 ** size give above.
47666 */
47667 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
47668 
47669 /* The maximum number of cells on a single page of the database.  This
47670 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
47671 ** plus 2 bytes for the index to the cell in the page header).  Such
47672 ** small cells will be rare, but they are possible.
47673 */
47674 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
47675 
47676 /* Forward declarations */
47677 typedef struct MemPage MemPage;
47678 typedef struct BtLock BtLock;
47679 
47680 /*
47681 ** This is a magic string that appears at the beginning of every
47682 ** SQLite database in order to identify the file as a real database.
47683 **
47684 ** You can change this value at compile-time by specifying a
47685 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
47686 ** header must be exactly 16 bytes including the zero-terminator so
47687 ** the string itself should be 15 characters long.  If you change
47688 ** the header, then your custom library will not be able to read
47689 ** databases generated by the standard tools and the standard tools
47690 ** will not be able to read databases created by your custom library.
47691 */
47692 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
47693 #  define SQLITE_FILE_HEADER "SQLite format 3"
47694 #endif
47695 
47696 /*
47697 ** Page type flags.  An ORed combination of these flags appear as the
47698 ** first byte of on-disk image of every BTree page.
47699 */
47700 #define PTF_INTKEY    0x01
47701 #define PTF_ZERODATA  0x02
47702 #define PTF_LEAFDATA  0x04
47703 #define PTF_LEAF      0x08
47704 
47705 /*
47706 ** As each page of the file is loaded into memory, an instance of the following
47707 ** structure is appended and initialized to zero.  This structure stores
47708 ** information about the page that is decoded from the raw file page.
47709 **
47710 ** The pParent field points back to the parent page.  This allows us to
47711 ** walk up the BTree from any leaf to the root.  Care must be taken to
47712 ** unref() the parent page pointer when this page is no longer referenced.
47713 ** The pageDestructor() routine handles that chore.
47714 **
47715 ** Access to all fields of this structure is controlled by the mutex
47716 ** stored in MemPage.pBt->mutex.
47717 */
47718 struct MemPage {
47719   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
47720   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
47721   u8 intKey;           /* True if intkey flag is set */
47722   u8 leaf;             /* True if leaf flag is set */
47723   u8 hasData;          /* True if this page stores data */
47724   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
47725   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
47726   u8 max1bytePayload;  /* min(maxLocal,127) */
47727   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
47728   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
47729   u16 cellOffset;      /* Index in aData of first cell pointer */
47730   u16 nFree;           /* Number of free bytes on the page */
47731   u16 nCell;           /* Number of cells on this page, local and ovfl */
47732   u16 maskPage;        /* Mask for page offset */
47733   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
47734                        ** non-overflow cell */
47735   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
47736   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
47737   u8 *aData;           /* Pointer to disk image of the page data */
47738   u8 *aDataEnd;        /* One byte past the end of usable data */
47739   u8 *aCellIdx;        /* The cell index area */
47740   DbPage *pDbPage;     /* Pager page handle */
47741   Pgno pgno;           /* Page number for this page */
47742 };
47743 
47744 /*
47745 ** The in-memory image of a disk page has the auxiliary information appended
47746 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
47747 ** that extra information.
47748 */
47749 #define EXTRA_SIZE sizeof(MemPage)
47750 
47751 /*
47752 ** A linked list of the following structures is stored at BtShared.pLock.
47753 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
47754 ** is opened on the table with root page BtShared.iTable. Locks are removed
47755 ** from this list when a transaction is committed or rolled back, or when
47756 ** a btree handle is closed.
47757 */
47758 struct BtLock {
47759   Btree *pBtree;        /* Btree handle holding this lock */
47760   Pgno iTable;          /* Root page of table */
47761   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
47762   BtLock *pNext;        /* Next in BtShared.pLock list */
47763 };
47764 
47765 /* Candidate values for BtLock.eLock */
47766 #define READ_LOCK     1
47767 #define WRITE_LOCK    2
47768 
47769 /* A Btree handle
47770 **
47771 ** A database connection contains a pointer to an instance of
47772 ** this object for every database file that it has open.  This structure
47773 ** is opaque to the database connection.  The database connection cannot
47774 ** see the internals of this structure and only deals with pointers to
47775 ** this structure.
47776 **
47777 ** For some database files, the same underlying database cache might be
47778 ** shared between multiple connections.  In that case, each connection
47779 ** has it own instance of this object.  But each instance of this object
47780 ** points to the same BtShared object.  The database cache and the
47781 ** schema associated with the database file are all contained within
47782 ** the BtShared object.
47783 **
47784 ** All fields in this structure are accessed under sqlite3.mutex.
47785 ** The pBt pointer itself may not be changed while there exists cursors
47786 ** in the referenced BtShared that point back to this Btree since those
47787 ** cursors have to go through this Btree to find their BtShared and
47788 ** they often do so without holding sqlite3.mutex.
47789 */
47790 struct Btree {
47791   sqlite3 *db;       /* The database connection holding this btree */
47792   BtShared *pBt;     /* Sharable content of this btree */
47793   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
47794   u8 sharable;       /* True if we can share pBt with another db */
47795   u8 locked;         /* True if db currently has pBt locked */
47796   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
47797   int nBackup;       /* Number of backup operations reading this btree */
47798   Btree *pNext;      /* List of other sharable Btrees from the same db */
47799   Btree *pPrev;      /* Back pointer of the same list */
47800 #ifndef SQLITE_OMIT_SHARED_CACHE
47801   BtLock lock;       /* Object used to lock page 1 */
47802 #endif
47803 };
47804 
47805 /*
47806 ** Btree.inTrans may take one of the following values.
47807 **
47808 ** If the shared-data extension is enabled, there may be multiple users
47809 ** of the Btree structure. At most one of these may open a write transaction,
47810 ** but any number may have active read transactions.
47811 */
47812 #define TRANS_NONE  0
47813 #define TRANS_READ  1
47814 #define TRANS_WRITE 2
47815 
47816 /*
47817 ** An instance of this object represents a single database file.
47818 **
47819 ** A single database file can be in use at the same time by two
47820 ** or more database connections.  When two or more connections are
47821 ** sharing the same database file, each connection has it own
47822 ** private Btree object for the file and each of those Btrees points
47823 ** to this one BtShared object.  BtShared.nRef is the number of
47824 ** connections currently sharing this database file.
47825 **
47826 ** Fields in this structure are accessed under the BtShared.mutex
47827 ** mutex, except for nRef and pNext which are accessed under the
47828 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
47829 ** may not be modified once it is initially set as long as nRef>0.
47830 ** The pSchema field may be set once under BtShared.mutex and
47831 ** thereafter is unchanged as long as nRef>0.
47832 **
47833 ** isPending:
47834 **
47835 **   If a BtShared client fails to obtain a write-lock on a database
47836 **   table (because there exists one or more read-locks on the table),
47837 **   the shared-cache enters 'pending-lock' state and isPending is
47838 **   set to true.
47839 **
47840 **   The shared-cache leaves the 'pending lock' state when either of
47841 **   the following occur:
47842 **
47843 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
47844 **     2) The number of locks held by other connections drops to zero.
47845 **
47846 **   while in the 'pending-lock' state, no connection may start a new
47847 **   transaction.
47848 **
47849 **   This feature is included to help prevent writer-starvation.
47850 */
47851 struct BtShared {
47852   Pager *pPager;        /* The page cache */
47853   sqlite3 *db;          /* Database connection currently using this Btree */
47854   BtCursor *pCursor;    /* A list of all open cursors */
47855   MemPage *pPage1;      /* First page of the database */
47856   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
47857 #ifndef SQLITE_OMIT_AUTOVACUUM
47858   u8 autoVacuum;        /* True if auto-vacuum is enabled */
47859   u8 incrVacuum;        /* True if incr-vacuum is enabled */
47860   u8 bDoTruncate;       /* True to truncate db on commit */
47861 #endif
47862   u8 inTransaction;     /* Transaction state */
47863   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
47864   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
47865   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
47866   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
47867   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
47868   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
47869   u32 pageSize;         /* Total number of bytes on a page */
47870   u32 usableSize;       /* Number of usable bytes on each page */
47871   int nTransaction;     /* Number of open transactions (read + write) */
47872   u32 nPage;            /* Number of pages in the database */
47873   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
47874   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
47875   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47876   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
47877 #ifndef SQLITE_OMIT_SHARED_CACHE
47878   int nRef;             /* Number of references to this structure */
47879   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
47880   BtLock *pLock;        /* List of locks held on this shared-btree struct */
47881   Btree *pWriter;       /* Btree with currently open write transaction */
47882 #endif
47883   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
47884 };
47885 
47886 /*
47887 ** Allowed values for BtShared.btsFlags
47888 */
47889 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
47890 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
47891 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
47892 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
47893 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
47894 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
47895 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
47896 
47897 /*
47898 ** An instance of the following structure is used to hold information
47899 ** about a cell.  The parseCellPtr() function fills in this structure
47900 ** based on information extract from the raw disk page.
47901 */
47902 typedef struct CellInfo CellInfo;
47903 struct CellInfo {
47904   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
47905   u8 *pCell;     /* Pointer to the start of cell content */
47906   u32 nData;     /* Number of bytes of data */
47907   u32 nPayload;  /* Total amount of payload */
47908   u16 nHeader;   /* Size of the cell content header in bytes */
47909   u16 nLocal;    /* Amount of payload held locally */
47910   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
47911   u16 nSize;     /* Size of the cell content on the main b-tree page */
47912 };
47913 
47914 /*
47915 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47916 ** this will be declared corrupt. This value is calculated based on a
47917 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47918 ** root-node and 3 for all other internal nodes.
47919 **
47920 ** If a tree that appears to be taller than this is encountered, it is
47921 ** assumed that the database is corrupt.
47922 */
47923 #define BTCURSOR_MAX_DEPTH 20
47924 
47925 /*
47926 ** A cursor is a pointer to a particular entry within a particular
47927 ** b-tree within a database file.
47928 **
47929 ** The entry is identified by its MemPage and the index in
47930 ** MemPage.aCell[] of the entry.
47931 **
47932 ** A single database file can be shared by two more database connections,
47933 ** but cursors cannot be shared.  Each cursor is associated with a
47934 ** particular database connection identified BtCursor.pBtree.db.
47935 **
47936 ** Fields in this structure are accessed under the BtShared.mutex
47937 ** found at self->pBt->mutex.
47938 */
47939 struct BtCursor {
47940   Btree *pBtree;            /* The Btree to which this cursor belongs */
47941   BtShared *pBt;            /* The BtShared this cursor points to */
47942   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
47943   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47944 #ifndef SQLITE_OMIT_INCRBLOB
47945   Pgno *aOverflow;          /* Cache of overflow page locations */
47946 #endif
47947   Pgno pgnoRoot;            /* The root page of this tree */
47948   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
47949   CellInfo info;            /* A parse of the cell we are pointing at */
47950   i64 nKey;        /* Size of pKey, or last integer key */
47951   void *pKey;      /* Saved key that was cursor's last known position */
47952   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
47953   u8 wrFlag;                /* True if writable */
47954   u8 atLast;                /* Cursor pointing to the last entry */
47955   u8 validNKey;             /* True if info.nKey is valid */
47956   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
47957 #ifndef SQLITE_OMIT_INCRBLOB
47958   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
47959 #endif
47960   u8 hints;                             /* As configured by CursorSetHints() */
47961   i16 iPage;                            /* Index of current page in apPage */
47962   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
47963   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
47964 };
47965 
47966 /*
47967 ** Potential values for BtCursor.eState.
47968 **
47969 ** CURSOR_VALID:
47970 **   Cursor points to a valid entry. getPayload() etc. may be called.
47971 **
47972 ** CURSOR_INVALID:
47973 **   Cursor does not point to a valid entry. This can happen (for example)
47974 **   because the table is empty or because BtreeCursorFirst() has not been
47975 **   called.
47976 **
47977 ** CURSOR_REQUIRESEEK:
47978 **   The table that this cursor was opened on still exists, but has been
47979 **   modified since the cursor was last used. The cursor position is saved
47980 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
47981 **   this state, restoreCursorPosition() can be called to attempt to
47982 **   seek the cursor to the saved position.
47983 **
47984 ** CURSOR_FAULT:
47985 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
47986 **   on a different connection that shares the BtShared cache with this
47987 **   cursor.  The error has left the cache in an inconsistent state.
47988 **   Do nothing else with this cursor.  Any attempt to use the cursor
47989 **   should return the error code stored in BtCursor.skip
47990 */
47991 #define CURSOR_INVALID           0
47992 #define CURSOR_VALID             1
47993 #define CURSOR_REQUIRESEEK       2
47994 #define CURSOR_FAULT             3
47995 
47996 /*
47997 ** The database page the PENDING_BYTE occupies. This page is never used.
47998 */
47999 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
48000 
48001 /*
48002 ** These macros define the location of the pointer-map entry for a
48003 ** database page. The first argument to each is the number of usable
48004 ** bytes on each page of the database (often 1024). The second is the
48005 ** page number to look up in the pointer map.
48006 **
48007 ** PTRMAP_PAGENO returns the database page number of the pointer-map
48008 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
48009 ** the offset of the requested map entry.
48010 **
48011 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
48012 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
48013 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
48014 ** this test.
48015 */
48016 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
48017 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
48018 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
48019 
48020 /*
48021 ** The pointer map is a lookup table that identifies the parent page for
48022 ** each child page in the database file.  The parent page is the page that
48023 ** contains a pointer to the child.  Every page in the database contains
48024 ** 0 or 1 parent pages.  (In this context 'database page' refers
48025 ** to any page that is not part of the pointer map itself.)  Each pointer map
48026 ** entry consists of a single byte 'type' and a 4 byte parent page number.
48027 ** The PTRMAP_XXX identifiers below are the valid types.
48028 **
48029 ** The purpose of the pointer map is to facility moving pages from one
48030 ** position in the file to another as part of autovacuum.  When a page
48031 ** is moved, the pointer in its parent must be updated to point to the
48032 ** new location.  The pointer map is used to locate the parent page quickly.
48033 **
48034 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
48035 **                  used in this case.
48036 **
48037 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
48038 **                  is not used in this case.
48039 **
48040 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
48041 **                   overflow pages. The page number identifies the page that
48042 **                   contains the cell with a pointer to this overflow page.
48043 **
48044 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
48045 **                   overflow pages. The page-number identifies the previous
48046 **                   page in the overflow page list.
48047 **
48048 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
48049 **               identifies the parent page in the btree.
48050 */
48051 #define PTRMAP_ROOTPAGE 1
48052 #define PTRMAP_FREEPAGE 2
48053 #define PTRMAP_OVERFLOW1 3
48054 #define PTRMAP_OVERFLOW2 4
48055 #define PTRMAP_BTREE 5
48056 
48057 /* A bunch of assert() statements to check the transaction state variables
48058 ** of handle p (type Btree*) are internally consistent.
48059 */
48060 #define btreeIntegrity(p) \
48061   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
48062   assert( p->pBt->inTransaction>=p->inTrans );
48063 
48064 
48065 /*
48066 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
48067 ** if the database supports auto-vacuum or not. Because it is used
48068 ** within an expression that is an argument to another macro
48069 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
48070 ** So, this macro is defined instead.
48071 */
48072 #ifndef SQLITE_OMIT_AUTOVACUUM
48073 #define ISAUTOVACUUM (pBt->autoVacuum)
48074 #else
48075 #define ISAUTOVACUUM 0
48076 #endif
48077 
48078 
48079 /*
48080 ** This structure is passed around through all the sanity checking routines
48081 ** in order to keep track of some global state information.
48082 **
48083 ** The aRef[] array is allocated so that there is 1 bit for each page in
48084 ** the database. As the integrity-check proceeds, for each page used in
48085 ** the database the corresponding bit is set. This allows integrity-check to
48086 ** detect pages that are used twice and orphaned pages (both of which
48087 ** indicate corruption).
48088 */
48089 typedef struct IntegrityCk IntegrityCk;
48090 struct IntegrityCk {
48091   BtShared *pBt;    /* The tree being checked out */
48092   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
48093   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
48094   Pgno nPage;       /* Number of pages in the database */
48095   int mxErr;        /* Stop accumulating errors when this reaches zero */
48096   int nErr;         /* Number of messages written to zErrMsg so far */
48097   int mallocFailed; /* A memory allocation error has occurred */
48098   StrAccum errMsg;  /* Accumulate the error message text here */
48099 };
48100 
48101 /*
48102 ** Routines to read or write a two- and four-byte big-endian integer values.
48103 */
48104 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
48105 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
48106 #define get4byte sqlite3Get4byte
48107 #define put4byte sqlite3Put4byte
48108 
48109 /************** End of btreeInt.h ********************************************/
48110 /************** Continuing where we left off in btmutex.c ********************/
48111 #ifndef SQLITE_OMIT_SHARED_CACHE
48112 #if SQLITE_THREADSAFE
48113 
48114 /*
48115 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
48116 ** set BtShared.db to the database handle associated with p and the
48117 ** p->locked boolean to true.
48118 */
48119 static void lockBtreeMutex(Btree *p){
48120   assert( p->locked==0 );
48121   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
48122   assert( sqlite3_mutex_held(p->db->mutex) );
48123 
48124   sqlite3_mutex_enter(p->pBt->mutex);
48125   p->pBt->db = p->db;
48126   p->locked = 1;
48127 }
48128 
48129 /*
48130 ** Release the BtShared mutex associated with B-Tree handle p and
48131 ** clear the p->locked boolean.
48132 */
48133 static void unlockBtreeMutex(Btree *p){
48134   BtShared *pBt = p->pBt;
48135   assert( p->locked==1 );
48136   assert( sqlite3_mutex_held(pBt->mutex) );
48137   assert( sqlite3_mutex_held(p->db->mutex) );
48138   assert( p->db==pBt->db );
48139 
48140   sqlite3_mutex_leave(pBt->mutex);
48141   p->locked = 0;
48142 }
48143 
48144 /*
48145 ** Enter a mutex on the given BTree object.
48146 **
48147 ** If the object is not sharable, then no mutex is ever required
48148 ** and this routine is a no-op.  The underlying mutex is non-recursive.
48149 ** But we keep a reference count in Btree.wantToLock so the behavior
48150 ** of this interface is recursive.
48151 **
48152 ** To avoid deadlocks, multiple Btrees are locked in the same order
48153 ** by all database connections.  The p->pNext is a list of other
48154 ** Btrees belonging to the same database connection as the p Btree
48155 ** which need to be locked after p.  If we cannot get a lock on
48156 ** p, then first unlock all of the others on p->pNext, then wait
48157 ** for the lock to become available on p, then relock all of the
48158 ** subsequent Btrees that desire a lock.
48159 */
48160 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48161   Btree *pLater;
48162 
48163   /* Some basic sanity checking on the Btree.  The list of Btrees
48164   ** connected by pNext and pPrev should be in sorted order by
48165   ** Btree.pBt value. All elements of the list should belong to
48166   ** the same connection. Only shared Btrees are on the list. */
48167   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
48168   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
48169   assert( p->pNext==0 || p->pNext->db==p->db );
48170   assert( p->pPrev==0 || p->pPrev->db==p->db );
48171   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
48172 
48173   /* Check for locking consistency */
48174   assert( !p->locked || p->wantToLock>0 );
48175   assert( p->sharable || p->wantToLock==0 );
48176 
48177   /* We should already hold a lock on the database connection */
48178   assert( sqlite3_mutex_held(p->db->mutex) );
48179 
48180   /* Unless the database is sharable and unlocked, then BtShared.db
48181   ** should already be set correctly. */
48182   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
48183 
48184   if( !p->sharable ) return;
48185   p->wantToLock++;
48186   if( p->locked ) return;
48187 
48188   /* In most cases, we should be able to acquire the lock we
48189   ** want without having to go throught the ascending lock
48190   ** procedure that follows.  Just be sure not to block.
48191   */
48192   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
48193     p->pBt->db = p->db;
48194     p->locked = 1;
48195     return;
48196   }
48197 
48198   /* To avoid deadlock, first release all locks with a larger
48199   ** BtShared address.  Then acquire our lock.  Then reacquire
48200   ** the other BtShared locks that we used to hold in ascending
48201   ** order.
48202   */
48203   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48204     assert( pLater->sharable );
48205     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
48206     assert( !pLater->locked || pLater->wantToLock>0 );
48207     if( pLater->locked ){
48208       unlockBtreeMutex(pLater);
48209     }
48210   }
48211   lockBtreeMutex(p);
48212   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48213     if( pLater->wantToLock ){
48214       lockBtreeMutex(pLater);
48215     }
48216   }
48217 }
48218 
48219 /*
48220 ** Exit the recursive mutex on a Btree.
48221 */
48222 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
48223   if( p->sharable ){
48224     assert( p->wantToLock>0 );
48225     p->wantToLock--;
48226     if( p->wantToLock==0 ){
48227       unlockBtreeMutex(p);
48228     }
48229   }
48230 }
48231 
48232 #ifndef NDEBUG
48233 /*
48234 ** Return true if the BtShared mutex is held on the btree, or if the
48235 ** B-Tree is not marked as sharable.
48236 **
48237 ** This routine is used only from within assert() statements.
48238 */
48239 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
48240   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
48241   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
48242   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
48243   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
48244 
48245   return (p->sharable==0 || p->locked);
48246 }
48247 #endif
48248 
48249 
48250 #ifndef SQLITE_OMIT_INCRBLOB
48251 /*
48252 ** Enter and leave a mutex on a Btree given a cursor owned by that
48253 ** Btree.  These entry points are used by incremental I/O and can be
48254 ** omitted if that module is not used.
48255 */
48256 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
48257   sqlite3BtreeEnter(pCur->pBtree);
48258 }
48259 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
48260   sqlite3BtreeLeave(pCur->pBtree);
48261 }
48262 #endif /* SQLITE_OMIT_INCRBLOB */
48263 
48264 
48265 /*
48266 ** Enter the mutex on every Btree associated with a database
48267 ** connection.  This is needed (for example) prior to parsing
48268 ** a statement since we will be comparing table and column names
48269 ** against all schemas and we do not want those schemas being
48270 ** reset out from under us.
48271 **
48272 ** There is a corresponding leave-all procedures.
48273 **
48274 ** Enter the mutexes in accending order by BtShared pointer address
48275 ** to avoid the possibility of deadlock when two threads with
48276 ** two or more btrees in common both try to lock all their btrees
48277 ** at the same instant.
48278 */
48279 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48280   int i;
48281   Btree *p;
48282   assert( sqlite3_mutex_held(db->mutex) );
48283   for(i=0; i<db->nDb; i++){
48284     p = db->aDb[i].pBt;
48285     if( p ) sqlite3BtreeEnter(p);
48286   }
48287 }
48288 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
48289   int i;
48290   Btree *p;
48291   assert( sqlite3_mutex_held(db->mutex) );
48292   for(i=0; i<db->nDb; i++){
48293     p = db->aDb[i].pBt;
48294     if( p ) sqlite3BtreeLeave(p);
48295   }
48296 }
48297 
48298 /*
48299 ** Return true if a particular Btree requires a lock.  Return FALSE if
48300 ** no lock is ever required since it is not sharable.
48301 */
48302 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
48303   return p->sharable;
48304 }
48305 
48306 #ifndef NDEBUG
48307 /*
48308 ** Return true if the current thread holds the database connection
48309 ** mutex and all required BtShared mutexes.
48310 **
48311 ** This routine is used inside assert() statements only.
48312 */
48313 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
48314   int i;
48315   if( !sqlite3_mutex_held(db->mutex) ){
48316     return 0;
48317   }
48318   for(i=0; i<db->nDb; i++){
48319     Btree *p;
48320     p = db->aDb[i].pBt;
48321     if( p && p->sharable &&
48322          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
48323       return 0;
48324     }
48325   }
48326   return 1;
48327 }
48328 #endif /* NDEBUG */
48329 
48330 #ifndef NDEBUG
48331 /*
48332 ** Return true if the correct mutexes are held for accessing the
48333 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
48334 ** access are:
48335 **
48336 **   (1) The mutex on db
48337 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
48338 **
48339 ** If pSchema is not NULL, then iDb is computed from pSchema and
48340 ** db using sqlite3SchemaToIndex().
48341 */
48342 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
48343   Btree *p;
48344   assert( db!=0 );
48345   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
48346   assert( iDb>=0 && iDb<db->nDb );
48347   if( !sqlite3_mutex_held(db->mutex) ) return 0;
48348   if( iDb==1 ) return 1;
48349   p = db->aDb[iDb].pBt;
48350   assert( p!=0 );
48351   return p->sharable==0 || p->locked==1;
48352 }
48353 #endif /* NDEBUG */
48354 
48355 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
48356 /*
48357 ** The following are special cases for mutex enter routines for use
48358 ** in single threaded applications that use shared cache.  Except for
48359 ** these two routines, all mutex operations are no-ops in that case and
48360 ** are null #defines in btree.h.
48361 **
48362 ** If shared cache is disabled, then all btree mutex routines, including
48363 ** the ones below, are no-ops and are null #defines in btree.h.
48364 */
48365 
48366 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48367   p->pBt->db = p->db;
48368 }
48369 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48370   int i;
48371   for(i=0; i<db->nDb; i++){
48372     Btree *p = db->aDb[i].pBt;
48373     if( p ){
48374       p->pBt->db = p->db;
48375     }
48376   }
48377 }
48378 #endif /* if SQLITE_THREADSAFE */
48379 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
48380 
48381 /************** End of btmutex.c *********************************************/
48382 /************** Begin file btree.c *******************************************/
48383 /*
48384 ** 2004 April 6
48385 **
48386 ** The author disclaims copyright to this source code.  In place of
48387 ** a legal notice, here is a blessing:
48388 **
48389 **    May you do good and not evil.
48390 **    May you find forgiveness for yourself and forgive others.
48391 **    May you share freely, never taking more than you give.
48392 **
48393 *************************************************************************
48394 ** This file implements a external (disk-based) database using BTrees.
48395 ** See the header comment on "btreeInt.h" for additional information.
48396 ** Including a description of file format and an overview of operation.
48397 */
48398 
48399 /*
48400 ** The header string that appears at the beginning of every
48401 ** SQLite database.
48402 */
48403 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
48404 
48405 /*
48406 ** Set this global variable to 1 to enable tracing using the TRACE
48407 ** macro.
48408 */
48409 #if 0
48410 int sqlite3BtreeTrace=1;  /* True to enable tracing */
48411 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
48412 #else
48413 # define TRACE(X)
48414 #endif
48415 
48416 /*
48417 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
48418 ** But if the value is zero, make it 65536.
48419 **
48420 ** This routine is used to extract the "offset to cell content area" value
48421 ** from the header of a btree page.  If the page size is 65536 and the page
48422 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
48423 ** This routine makes the necessary adjustment to 65536.
48424 */
48425 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
48426 
48427 /*
48428 ** Values passed as the 5th argument to allocateBtreePage()
48429 */
48430 #define BTALLOC_ANY   0           /* Allocate any page */
48431 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
48432 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
48433 
48434 /*
48435 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
48436 ** defined, or 0 if it is. For example:
48437 **
48438 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
48439 */
48440 #ifndef SQLITE_OMIT_AUTOVACUUM
48441 #define IfNotOmitAV(expr) (expr)
48442 #else
48443 #define IfNotOmitAV(expr) 0
48444 #endif
48445 
48446 #ifndef SQLITE_OMIT_SHARED_CACHE
48447 /*
48448 ** A list of BtShared objects that are eligible for participation
48449 ** in shared cache.  This variable has file scope during normal builds,
48450 ** but the test harness needs to access it so we make it global for
48451 ** test builds.
48452 **
48453 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
48454 */
48455 #ifdef SQLITE_TEST
48456 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48457 #else
48458 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48459 #endif
48460 #endif /* SQLITE_OMIT_SHARED_CACHE */
48461 
48462 #ifndef SQLITE_OMIT_SHARED_CACHE
48463 /*
48464 ** Enable or disable the shared pager and schema features.
48465 **
48466 ** This routine has no effect on existing database connections.
48467 ** The shared cache setting effects only future calls to
48468 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
48469 */
48470 SQLITE_API int sqlite3_enable_shared_cache(int enable){
48471   sqlite3GlobalConfig.sharedCacheEnabled = enable;
48472   return SQLITE_OK;
48473 }
48474 #endif
48475 
48476 
48477 
48478 #ifdef SQLITE_OMIT_SHARED_CACHE
48479   /*
48480   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
48481   ** and clearAllSharedCacheTableLocks()
48482   ** manipulate entries in the BtShared.pLock linked list used to store
48483   ** shared-cache table level locks. If the library is compiled with the
48484   ** shared-cache feature disabled, then there is only ever one user
48485   ** of each BtShared structure and so this locking is not necessary.
48486   ** So define the lock related functions as no-ops.
48487   */
48488   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
48489   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
48490   #define clearAllSharedCacheTableLocks(a)
48491   #define downgradeAllSharedCacheTableLocks(a)
48492   #define hasSharedCacheTableLock(a,b,c,d) 1
48493   #define hasReadConflicts(a, b) 0
48494 #endif
48495 
48496 #ifndef SQLITE_OMIT_SHARED_CACHE
48497 
48498 #ifdef SQLITE_DEBUG
48499 /*
48500 **** This function is only used as part of an assert() statement. ***
48501 **
48502 ** Check to see if pBtree holds the required locks to read or write to the
48503 ** table with root page iRoot.   Return 1 if it does and 0 if not.
48504 **
48505 ** For example, when writing to a table with root-page iRoot via
48506 ** Btree connection pBtree:
48507 **
48508 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
48509 **
48510 ** When writing to an index that resides in a sharable database, the
48511 ** caller should have first obtained a lock specifying the root page of
48512 ** the corresponding table. This makes things a bit more complicated,
48513 ** as this module treats each table as a separate structure. To determine
48514 ** the table corresponding to the index being written, this
48515 ** function has to search through the database schema.
48516 **
48517 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
48518 ** hold a write-lock on the schema table (root page 1). This is also
48519 ** acceptable.
48520 */
48521 static int hasSharedCacheTableLock(
48522   Btree *pBtree,         /* Handle that must hold lock */
48523   Pgno iRoot,            /* Root page of b-tree */
48524   int isIndex,           /* True if iRoot is the root of an index b-tree */
48525   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
48526 ){
48527   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
48528   Pgno iTab = 0;
48529   BtLock *pLock;
48530 
48531   /* If this database is not shareable, or if the client is reading
48532   ** and has the read-uncommitted flag set, then no lock is required.
48533   ** Return true immediately.
48534   */
48535   if( (pBtree->sharable==0)
48536    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
48537   ){
48538     return 1;
48539   }
48540 
48541   /* If the client is reading  or writing an index and the schema is
48542   ** not loaded, then it is too difficult to actually check to see if
48543   ** the correct locks are held.  So do not bother - just return true.
48544   ** This case does not come up very often anyhow.
48545   */
48546   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
48547     return 1;
48548   }
48549 
48550   /* Figure out the root-page that the lock should be held on. For table
48551   ** b-trees, this is just the root page of the b-tree being read or
48552   ** written. For index b-trees, it is the root page of the associated
48553   ** table.  */
48554   if( isIndex ){
48555     HashElem *p;
48556     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
48557       Index *pIdx = (Index *)sqliteHashData(p);
48558       if( pIdx->tnum==(int)iRoot ){
48559         iTab = pIdx->pTable->tnum;
48560       }
48561     }
48562   }else{
48563     iTab = iRoot;
48564   }
48565 
48566   /* Search for the required lock. Either a write-lock on root-page iTab, a
48567   ** write-lock on the schema table, or (if the client is reading) a
48568   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
48569   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
48570     if( pLock->pBtree==pBtree
48571      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
48572      && pLock->eLock>=eLockType
48573     ){
48574       return 1;
48575     }
48576   }
48577 
48578   /* Failed to find the required lock. */
48579   return 0;
48580 }
48581 #endif /* SQLITE_DEBUG */
48582 
48583 #ifdef SQLITE_DEBUG
48584 /*
48585 **** This function may be used as part of assert() statements only. ****
48586 **
48587 ** Return true if it would be illegal for pBtree to write into the
48588 ** table or index rooted at iRoot because other shared connections are
48589 ** simultaneously reading that same table or index.
48590 **
48591 ** It is illegal for pBtree to write if some other Btree object that
48592 ** shares the same BtShared object is currently reading or writing
48593 ** the iRoot table.  Except, if the other Btree object has the
48594 ** read-uncommitted flag set, then it is OK for the other object to
48595 ** have a read cursor.
48596 **
48597 ** For example, before writing to any part of the table or index
48598 ** rooted at page iRoot, one should call:
48599 **
48600 **    assert( !hasReadConflicts(pBtree, iRoot) );
48601 */
48602 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
48603   BtCursor *p;
48604   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48605     if( p->pgnoRoot==iRoot
48606      && p->pBtree!=pBtree
48607      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
48608     ){
48609       return 1;
48610     }
48611   }
48612   return 0;
48613 }
48614 #endif    /* #ifdef SQLITE_DEBUG */
48615 
48616 /*
48617 ** Query to see if Btree handle p may obtain a lock of type eLock
48618 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
48619 ** SQLITE_OK if the lock may be obtained (by calling
48620 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
48621 */
48622 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
48623   BtShared *pBt = p->pBt;
48624   BtLock *pIter;
48625 
48626   assert( sqlite3BtreeHoldsMutex(p) );
48627   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48628   assert( p->db!=0 );
48629   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
48630 
48631   /* If requesting a write-lock, then the Btree must have an open write
48632   ** transaction on this file. And, obviously, for this to be so there
48633   ** must be an open write transaction on the file itself.
48634   */
48635   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
48636   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
48637 
48638   /* This routine is a no-op if the shared-cache is not enabled */
48639   if( !p->sharable ){
48640     return SQLITE_OK;
48641   }
48642 
48643   /* If some other connection is holding an exclusive lock, the
48644   ** requested lock may not be obtained.
48645   */
48646   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
48647     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
48648     return SQLITE_LOCKED_SHAREDCACHE;
48649   }
48650 
48651   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48652     /* The condition (pIter->eLock!=eLock) in the following if(...)
48653     ** statement is a simplification of:
48654     **
48655     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
48656     **
48657     ** since we know that if eLock==WRITE_LOCK, then no other connection
48658     ** may hold a WRITE_LOCK on any table in this file (since there can
48659     ** only be a single writer).
48660     */
48661     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
48662     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
48663     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
48664       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
48665       if( eLock==WRITE_LOCK ){
48666         assert( p==pBt->pWriter );
48667         pBt->btsFlags |= BTS_PENDING;
48668       }
48669       return SQLITE_LOCKED_SHAREDCACHE;
48670     }
48671   }
48672   return SQLITE_OK;
48673 }
48674 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48675 
48676 #ifndef SQLITE_OMIT_SHARED_CACHE
48677 /*
48678 ** Add a lock on the table with root-page iTable to the shared-btree used
48679 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
48680 ** WRITE_LOCK.
48681 **
48682 ** This function assumes the following:
48683 **
48684 **   (a) The specified Btree object p is connected to a sharable
48685 **       database (one with the BtShared.sharable flag set), and
48686 **
48687 **   (b) No other Btree objects hold a lock that conflicts
48688 **       with the requested lock (i.e. querySharedCacheTableLock() has
48689 **       already been called and returned SQLITE_OK).
48690 **
48691 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
48692 ** is returned if a malloc attempt fails.
48693 */
48694 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
48695   BtShared *pBt = p->pBt;
48696   BtLock *pLock = 0;
48697   BtLock *pIter;
48698 
48699   assert( sqlite3BtreeHoldsMutex(p) );
48700   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48701   assert( p->db!=0 );
48702 
48703   /* A connection with the read-uncommitted flag set will never try to
48704   ** obtain a read-lock using this function. The only read-lock obtained
48705   ** by a connection in read-uncommitted mode is on the sqlite_master
48706   ** table, and that lock is obtained in BtreeBeginTrans().  */
48707   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
48708 
48709   /* This function should only be called on a sharable b-tree after it
48710   ** has been determined that no other b-tree holds a conflicting lock.  */
48711   assert( p->sharable );
48712   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
48713 
48714   /* First search the list for an existing lock on this table. */
48715   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48716     if( pIter->iTable==iTable && pIter->pBtree==p ){
48717       pLock = pIter;
48718       break;
48719     }
48720   }
48721 
48722   /* If the above search did not find a BtLock struct associating Btree p
48723   ** with table iTable, allocate one and link it into the list.
48724   */
48725   if( !pLock ){
48726     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
48727     if( !pLock ){
48728       return SQLITE_NOMEM;
48729     }
48730     pLock->iTable = iTable;
48731     pLock->pBtree = p;
48732     pLock->pNext = pBt->pLock;
48733     pBt->pLock = pLock;
48734   }
48735 
48736   /* Set the BtLock.eLock variable to the maximum of the current lock
48737   ** and the requested lock. This means if a write-lock was already held
48738   ** and a read-lock requested, we don't incorrectly downgrade the lock.
48739   */
48740   assert( WRITE_LOCK>READ_LOCK );
48741   if( eLock>pLock->eLock ){
48742     pLock->eLock = eLock;
48743   }
48744 
48745   return SQLITE_OK;
48746 }
48747 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48748 
48749 #ifndef SQLITE_OMIT_SHARED_CACHE
48750 /*
48751 ** Release all the table locks (locks obtained via calls to
48752 ** the setSharedCacheTableLock() procedure) held by Btree object p.
48753 **
48754 ** This function assumes that Btree p has an open read or write
48755 ** transaction. If it does not, then the BTS_PENDING flag
48756 ** may be incorrectly cleared.
48757 */
48758 static void clearAllSharedCacheTableLocks(Btree *p){
48759   BtShared *pBt = p->pBt;
48760   BtLock **ppIter = &pBt->pLock;
48761 
48762   assert( sqlite3BtreeHoldsMutex(p) );
48763   assert( p->sharable || 0==*ppIter );
48764   assert( p->inTrans>0 );
48765 
48766   while( *ppIter ){
48767     BtLock *pLock = *ppIter;
48768     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
48769     assert( pLock->pBtree->inTrans>=pLock->eLock );
48770     if( pLock->pBtree==p ){
48771       *ppIter = pLock->pNext;
48772       assert( pLock->iTable!=1 || pLock==&p->lock );
48773       if( pLock->iTable!=1 ){
48774         sqlite3_free(pLock);
48775       }
48776     }else{
48777       ppIter = &pLock->pNext;
48778     }
48779   }
48780 
48781   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
48782   if( pBt->pWriter==p ){
48783     pBt->pWriter = 0;
48784     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48785   }else if( pBt->nTransaction==2 ){
48786     /* This function is called when Btree p is concluding its
48787     ** transaction. If there currently exists a writer, and p is not
48788     ** that writer, then the number of locks held by connections other
48789     ** than the writer must be about to drop to zero. In this case
48790     ** set the BTS_PENDING flag to 0.
48791     **
48792     ** If there is not currently a writer, then BTS_PENDING must
48793     ** be zero already. So this next line is harmless in that case.
48794     */
48795     pBt->btsFlags &= ~BTS_PENDING;
48796   }
48797 }
48798 
48799 /*
48800 ** This function changes all write-locks held by Btree p into read-locks.
48801 */
48802 static void downgradeAllSharedCacheTableLocks(Btree *p){
48803   BtShared *pBt = p->pBt;
48804   if( pBt->pWriter==p ){
48805     BtLock *pLock;
48806     pBt->pWriter = 0;
48807     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
48808     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
48809       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
48810       pLock->eLock = READ_LOCK;
48811     }
48812   }
48813 }
48814 
48815 #endif /* SQLITE_OMIT_SHARED_CACHE */
48816 
48817 static void releasePage(MemPage *pPage);  /* Forward reference */
48818 
48819 /*
48820 ***** This routine is used inside of assert() only ****
48821 **
48822 ** Verify that the cursor holds the mutex on its BtShared
48823 */
48824 #ifdef SQLITE_DEBUG
48825 static int cursorHoldsMutex(BtCursor *p){
48826   return sqlite3_mutex_held(p->pBt->mutex);
48827 }
48828 #endif
48829 
48830 
48831 #ifndef SQLITE_OMIT_INCRBLOB
48832 /*
48833 ** Invalidate the overflow page-list cache for cursor pCur, if any.
48834 */
48835 static void invalidateOverflowCache(BtCursor *pCur){
48836   assert( cursorHoldsMutex(pCur) );
48837   sqlite3_free(pCur->aOverflow);
48838   pCur->aOverflow = 0;
48839 }
48840 
48841 /*
48842 ** Invalidate the overflow page-list cache for all cursors opened
48843 ** on the shared btree structure pBt.
48844 */
48845 static void invalidateAllOverflowCache(BtShared *pBt){
48846   BtCursor *p;
48847   assert( sqlite3_mutex_held(pBt->mutex) );
48848   for(p=pBt->pCursor; p; p=p->pNext){
48849     invalidateOverflowCache(p);
48850   }
48851 }
48852 
48853 /*
48854 ** This function is called before modifying the contents of a table
48855 ** to invalidate any incrblob cursors that are open on the
48856 ** row or one of the rows being modified.
48857 **
48858 ** If argument isClearTable is true, then the entire contents of the
48859 ** table is about to be deleted. In this case invalidate all incrblob
48860 ** cursors open on any row within the table with root-page pgnoRoot.
48861 **
48862 ** Otherwise, if argument isClearTable is false, then the row with
48863 ** rowid iRow is being replaced or deleted. In this case invalidate
48864 ** only those incrblob cursors open on that specific row.
48865 */
48866 static void invalidateIncrblobCursors(
48867   Btree *pBtree,          /* The database file to check */
48868   i64 iRow,               /* The rowid that might be changing */
48869   int isClearTable        /* True if all rows are being deleted */
48870 ){
48871   BtCursor *p;
48872   BtShared *pBt = pBtree->pBt;
48873   assert( sqlite3BtreeHoldsMutex(pBtree) );
48874   for(p=pBt->pCursor; p; p=p->pNext){
48875     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
48876       p->eState = CURSOR_INVALID;
48877     }
48878   }
48879 }
48880 
48881 #else
48882   /* Stub functions when INCRBLOB is omitted */
48883   #define invalidateOverflowCache(x)
48884   #define invalidateAllOverflowCache(x)
48885   #define invalidateIncrblobCursors(x,y,z)
48886 #endif /* SQLITE_OMIT_INCRBLOB */
48887 
48888 /*
48889 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
48890 ** when a page that previously contained data becomes a free-list leaf
48891 ** page.
48892 **
48893 ** The BtShared.pHasContent bitvec exists to work around an obscure
48894 ** bug caused by the interaction of two useful IO optimizations surrounding
48895 ** free-list leaf pages:
48896 **
48897 **   1) When all data is deleted from a page and the page becomes
48898 **      a free-list leaf page, the page is not written to the database
48899 **      (as free-list leaf pages contain no meaningful data). Sometimes
48900 **      such a page is not even journalled (as it will not be modified,
48901 **      why bother journalling it?).
48902 **
48903 **   2) When a free-list leaf page is reused, its content is not read
48904 **      from the database or written to the journal file (why should it
48905 **      be, if it is not at all meaningful?).
48906 **
48907 ** By themselves, these optimizations work fine and provide a handy
48908 ** performance boost to bulk delete or insert operations. However, if
48909 ** a page is moved to the free-list and then reused within the same
48910 ** transaction, a problem comes up. If the page is not journalled when
48911 ** it is moved to the free-list and it is also not journalled when it
48912 ** is extracted from the free-list and reused, then the original data
48913 ** may be lost. In the event of a rollback, it may not be possible
48914 ** to restore the database to its original configuration.
48915 **
48916 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
48917 ** moved to become a free-list leaf page, the corresponding bit is
48918 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48919 ** optimization 2 above is omitted if the corresponding bit is already
48920 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48921 ** at the end of every transaction.
48922 */
48923 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48924   int rc = SQLITE_OK;
48925   if( !pBt->pHasContent ){
48926     assert( pgno<=pBt->nPage );
48927     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48928     if( !pBt->pHasContent ){
48929       rc = SQLITE_NOMEM;
48930     }
48931   }
48932   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48933     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48934   }
48935   return rc;
48936 }
48937 
48938 /*
48939 ** Query the BtShared.pHasContent vector.
48940 **
48941 ** This function is called when a free-list leaf page is removed from the
48942 ** free-list for reuse. It returns false if it is safe to retrieve the
48943 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48944 */
48945 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48946   Bitvec *p = pBt->pHasContent;
48947   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48948 }
48949 
48950 /*
48951 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48952 ** invoked at the conclusion of each write-transaction.
48953 */
48954 static void btreeClearHasContent(BtShared *pBt){
48955   sqlite3BitvecDestroy(pBt->pHasContent);
48956   pBt->pHasContent = 0;
48957 }
48958 
48959 /*
48960 ** Release all of the apPage[] pages for a cursor.
48961 */
48962 static void btreeReleaseAllCursorPages(BtCursor *pCur){
48963   int i;
48964   for(i=0; i<=pCur->iPage; i++){
48965     releasePage(pCur->apPage[i]);
48966     pCur->apPage[i] = 0;
48967   }
48968   pCur->iPage = -1;
48969 }
48970 
48971 
48972 /*
48973 ** Save the current cursor position in the variables BtCursor.nKey
48974 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48975 **
48976 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48977 ** prior to calling this routine.
48978 */
48979 static int saveCursorPosition(BtCursor *pCur){
48980   int rc;
48981 
48982   assert( CURSOR_VALID==pCur->eState );
48983   assert( 0==pCur->pKey );
48984   assert( cursorHoldsMutex(pCur) );
48985 
48986   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48987   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
48988 
48989   /* If this is an intKey table, then the above call to BtreeKeySize()
48990   ** stores the integer key in pCur->nKey. In this case this value is
48991   ** all that is required. Otherwise, if pCur is not open on an intKey
48992   ** table, then malloc space for and store the pCur->nKey bytes of key
48993   ** data.
48994   */
48995   if( 0==pCur->apPage[0]->intKey ){
48996     void *pKey = sqlite3Malloc( (int)pCur->nKey );
48997     if( pKey ){
48998       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
48999       if( rc==SQLITE_OK ){
49000         pCur->pKey = pKey;
49001       }else{
49002         sqlite3_free(pKey);
49003       }
49004     }else{
49005       rc = SQLITE_NOMEM;
49006     }
49007   }
49008   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
49009 
49010   if( rc==SQLITE_OK ){
49011     btreeReleaseAllCursorPages(pCur);
49012     pCur->eState = CURSOR_REQUIRESEEK;
49013   }
49014 
49015   invalidateOverflowCache(pCur);
49016   return rc;
49017 }
49018 
49019 /*
49020 ** Save the positions of all cursors (except pExcept) that are open on
49021 ** the table  with root-page iRoot. Usually, this is called just before cursor
49022 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
49023 */
49024 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
49025   BtCursor *p;
49026   assert( sqlite3_mutex_held(pBt->mutex) );
49027   assert( pExcept==0 || pExcept->pBt==pBt );
49028   for(p=pBt->pCursor; p; p=p->pNext){
49029     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
49030       if( p->eState==CURSOR_VALID ){
49031         int rc = saveCursorPosition(p);
49032         if( SQLITE_OK!=rc ){
49033           return rc;
49034         }
49035       }else{
49036         testcase( p->iPage>0 );
49037         btreeReleaseAllCursorPages(p);
49038       }
49039     }
49040   }
49041   return SQLITE_OK;
49042 }
49043 
49044 /*
49045 ** Clear the current cursor position.
49046 */
49047 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
49048   assert( cursorHoldsMutex(pCur) );
49049   sqlite3_free(pCur->pKey);
49050   pCur->pKey = 0;
49051   pCur->eState = CURSOR_INVALID;
49052 }
49053 
49054 /*
49055 ** In this version of BtreeMoveto, pKey is a packed index record
49056 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
49057 ** record and then call BtreeMovetoUnpacked() to do the work.
49058 */
49059 static int btreeMoveto(
49060   BtCursor *pCur,     /* Cursor open on the btree to be searched */
49061   const void *pKey,   /* Packed key if the btree is an index */
49062   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
49063   int bias,           /* Bias search to the high end */
49064   int *pRes           /* Write search results here */
49065 ){
49066   int rc;                    /* Status code */
49067   UnpackedRecord *pIdxKey;   /* Unpacked index key */
49068   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
49069   char *pFree = 0;
49070 
49071   if( pKey ){
49072     assert( nKey==(i64)(int)nKey );
49073     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
49074         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
49075     );
49076     if( pIdxKey==0 ) return SQLITE_NOMEM;
49077     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
49078   }else{
49079     pIdxKey = 0;
49080   }
49081   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
49082   if( pFree ){
49083     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
49084   }
49085   return rc;
49086 }
49087 
49088 /*
49089 ** Restore the cursor to the position it was in (or as close to as possible)
49090 ** when saveCursorPosition() was called. Note that this call deletes the
49091 ** saved position info stored by saveCursorPosition(), so there can be
49092 ** at most one effective restoreCursorPosition() call after each
49093 ** saveCursorPosition().
49094 */
49095 static int btreeRestoreCursorPosition(BtCursor *pCur){
49096   int rc;
49097   assert( cursorHoldsMutex(pCur) );
49098   assert( pCur->eState>=CURSOR_REQUIRESEEK );
49099   if( pCur->eState==CURSOR_FAULT ){
49100     return pCur->skipNext;
49101   }
49102   pCur->eState = CURSOR_INVALID;
49103   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
49104   if( rc==SQLITE_OK ){
49105     sqlite3_free(pCur->pKey);
49106     pCur->pKey = 0;
49107     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
49108   }
49109   return rc;
49110 }
49111 
49112 #define restoreCursorPosition(p) \
49113   (p->eState>=CURSOR_REQUIRESEEK ? \
49114          btreeRestoreCursorPosition(p) : \
49115          SQLITE_OK)
49116 
49117 /*
49118 ** Determine whether or not a cursor has moved from the position it
49119 ** was last placed at.  Cursors can move when the row they are pointing
49120 ** at is deleted out from under them.
49121 **
49122 ** This routine returns an error code if something goes wrong.  The
49123 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
49124 */
49125 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
49126   int rc;
49127 
49128   rc = restoreCursorPosition(pCur);
49129   if( rc ){
49130     *pHasMoved = 1;
49131     return rc;
49132   }
49133   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
49134     *pHasMoved = 1;
49135   }else{
49136     *pHasMoved = 0;
49137   }
49138   return SQLITE_OK;
49139 }
49140 
49141 #ifndef SQLITE_OMIT_AUTOVACUUM
49142 /*
49143 ** Given a page number of a regular database page, return the page
49144 ** number for the pointer-map page that contains the entry for the
49145 ** input page number.
49146 **
49147 ** Return 0 (not a valid page) for pgno==1 since there is
49148 ** no pointer map associated with page 1.  The integrity_check logic
49149 ** requires that ptrmapPageno(*,1)!=1.
49150 */
49151 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
49152   int nPagesPerMapPage;
49153   Pgno iPtrMap, ret;
49154   assert( sqlite3_mutex_held(pBt->mutex) );
49155   if( pgno<2 ) return 0;
49156   nPagesPerMapPage = (pBt->usableSize/5)+1;
49157   iPtrMap = (pgno-2)/nPagesPerMapPage;
49158   ret = (iPtrMap*nPagesPerMapPage) + 2;
49159   if( ret==PENDING_BYTE_PAGE(pBt) ){
49160     ret++;
49161   }
49162   return ret;
49163 }
49164 
49165 /*
49166 ** Write an entry into the pointer map.
49167 **
49168 ** This routine updates the pointer map entry for page number 'key'
49169 ** so that it maps to type 'eType' and parent page number 'pgno'.
49170 **
49171 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
49172 ** a no-op.  If an error occurs, the appropriate error code is written
49173 ** into *pRC.
49174 */
49175 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
49176   DbPage *pDbPage;  /* The pointer map page */
49177   u8 *pPtrmap;      /* The pointer map data */
49178   Pgno iPtrmap;     /* The pointer map page number */
49179   int offset;       /* Offset in pointer map page */
49180   int rc;           /* Return code from subfunctions */
49181 
49182   if( *pRC ) return;
49183 
49184   assert( sqlite3_mutex_held(pBt->mutex) );
49185   /* The master-journal page number must never be used as a pointer map page */
49186   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
49187 
49188   assert( pBt->autoVacuum );
49189   if( key==0 ){
49190     *pRC = SQLITE_CORRUPT_BKPT;
49191     return;
49192   }
49193   iPtrmap = PTRMAP_PAGENO(pBt, key);
49194   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49195   if( rc!=SQLITE_OK ){
49196     *pRC = rc;
49197     return;
49198   }
49199   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49200   if( offset<0 ){
49201     *pRC = SQLITE_CORRUPT_BKPT;
49202     goto ptrmap_exit;
49203   }
49204   assert( offset <= (int)pBt->usableSize-5 );
49205   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49206 
49207   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
49208     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
49209     *pRC= rc = sqlite3PagerWrite(pDbPage);
49210     if( rc==SQLITE_OK ){
49211       pPtrmap[offset] = eType;
49212       put4byte(&pPtrmap[offset+1], parent);
49213     }
49214   }
49215 
49216 ptrmap_exit:
49217   sqlite3PagerUnref(pDbPage);
49218 }
49219 
49220 /*
49221 ** Read an entry from the pointer map.
49222 **
49223 ** This routine retrieves the pointer map entry for page 'key', writing
49224 ** the type and parent page number to *pEType and *pPgno respectively.
49225 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
49226 */
49227 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
49228   DbPage *pDbPage;   /* The pointer map page */
49229   int iPtrmap;       /* Pointer map page index */
49230   u8 *pPtrmap;       /* Pointer map page data */
49231   int offset;        /* Offset of entry in pointer map */
49232   int rc;
49233 
49234   assert( sqlite3_mutex_held(pBt->mutex) );
49235 
49236   iPtrmap = PTRMAP_PAGENO(pBt, key);
49237   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49238   if( rc!=0 ){
49239     return rc;
49240   }
49241   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49242 
49243   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49244   if( offset<0 ){
49245     sqlite3PagerUnref(pDbPage);
49246     return SQLITE_CORRUPT_BKPT;
49247   }
49248   assert( offset <= (int)pBt->usableSize-5 );
49249   assert( pEType!=0 );
49250   *pEType = pPtrmap[offset];
49251   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
49252 
49253   sqlite3PagerUnref(pDbPage);
49254   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
49255   return SQLITE_OK;
49256 }
49257 
49258 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
49259   #define ptrmapPut(w,x,y,z,rc)
49260   #define ptrmapGet(w,x,y,z) SQLITE_OK
49261   #define ptrmapPutOvflPtr(x, y, rc)
49262 #endif
49263 
49264 /*
49265 ** Given a btree page and a cell index (0 means the first cell on
49266 ** the page, 1 means the second cell, and so forth) return a pointer
49267 ** to the cell content.
49268 **
49269 ** This routine works only for pages that do not contain overflow cells.
49270 */
49271 #define findCell(P,I) \
49272   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
49273 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
49274 
49275 
49276 /*
49277 ** This a more complex version of findCell() that works for
49278 ** pages that do contain overflow cells.
49279 */
49280 static u8 *findOverflowCell(MemPage *pPage, int iCell){
49281   int i;
49282   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49283   for(i=pPage->nOverflow-1; i>=0; i--){
49284     int k;
49285     k = pPage->aiOvfl[i];
49286     if( k<=iCell ){
49287       if( k==iCell ){
49288         return pPage->apOvfl[i];
49289       }
49290       iCell--;
49291     }
49292   }
49293   return findCell(pPage, iCell);
49294 }
49295 
49296 /*
49297 ** Parse a cell content block and fill in the CellInfo structure.  There
49298 ** are two versions of this function.  btreeParseCell() takes a
49299 ** cell index as the second argument and btreeParseCellPtr()
49300 ** takes a pointer to the body of the cell as its second argument.
49301 **
49302 ** Within this file, the parseCell() macro can be called instead of
49303 ** btreeParseCellPtr(). Using some compilers, this will be faster.
49304 */
49305 static void btreeParseCellPtr(
49306   MemPage *pPage,         /* Page containing the cell */
49307   u8 *pCell,              /* Pointer to the cell text. */
49308   CellInfo *pInfo         /* Fill in this structure */
49309 ){
49310   u16 n;                  /* Number bytes in cell content header */
49311   u32 nPayload;           /* Number of bytes of cell payload */
49312 
49313   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49314 
49315   pInfo->pCell = pCell;
49316   assert( pPage->leaf==0 || pPage->leaf==1 );
49317   n = pPage->childPtrSize;
49318   assert( n==4-4*pPage->leaf );
49319   if( pPage->intKey ){
49320     if( pPage->hasData ){
49321       n += getVarint32(&pCell[n], nPayload);
49322     }else{
49323       nPayload = 0;
49324     }
49325     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
49326     pInfo->nData = nPayload;
49327   }else{
49328     pInfo->nData = 0;
49329     n += getVarint32(&pCell[n], nPayload);
49330     pInfo->nKey = nPayload;
49331   }
49332   pInfo->nPayload = nPayload;
49333   pInfo->nHeader = n;
49334   testcase( nPayload==pPage->maxLocal );
49335   testcase( nPayload==pPage->maxLocal+1 );
49336   if( likely(nPayload<=pPage->maxLocal) ){
49337     /* This is the (easy) common case where the entire payload fits
49338     ** on the local page.  No overflow is required.
49339     */
49340     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
49341     pInfo->nLocal = (u16)nPayload;
49342     pInfo->iOverflow = 0;
49343   }else{
49344     /* If the payload will not fit completely on the local page, we have
49345     ** to decide how much to store locally and how much to spill onto
49346     ** overflow pages.  The strategy is to minimize the amount of unused
49347     ** space on overflow pages while keeping the amount of local storage
49348     ** in between minLocal and maxLocal.
49349     **
49350     ** Warning:  changing the way overflow payload is distributed in any
49351     ** way will result in an incompatible file format.
49352     */
49353     int minLocal;  /* Minimum amount of payload held locally */
49354     int maxLocal;  /* Maximum amount of payload held locally */
49355     int surplus;   /* Overflow payload available for local storage */
49356 
49357     minLocal = pPage->minLocal;
49358     maxLocal = pPage->maxLocal;
49359     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
49360     testcase( surplus==maxLocal );
49361     testcase( surplus==maxLocal+1 );
49362     if( surplus <= maxLocal ){
49363       pInfo->nLocal = (u16)surplus;
49364     }else{
49365       pInfo->nLocal = (u16)minLocal;
49366     }
49367     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
49368     pInfo->nSize = pInfo->iOverflow + 4;
49369   }
49370 }
49371 #define parseCell(pPage, iCell, pInfo) \
49372   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
49373 static void btreeParseCell(
49374   MemPage *pPage,         /* Page containing the cell */
49375   int iCell,              /* The cell index.  First cell is 0 */
49376   CellInfo *pInfo         /* Fill in this structure */
49377 ){
49378   parseCell(pPage, iCell, pInfo);
49379 }
49380 
49381 /*
49382 ** Compute the total number of bytes that a Cell needs in the cell
49383 ** data area of the btree-page.  The return number includes the cell
49384 ** data header and the local payload, but not any overflow page or
49385 ** the space used by the cell pointer.
49386 */
49387 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
49388   u8 *pIter = &pCell[pPage->childPtrSize];
49389   u32 nSize;
49390 
49391 #ifdef SQLITE_DEBUG
49392   /* The value returned by this function should always be the same as
49393   ** the (CellInfo.nSize) value found by doing a full parse of the
49394   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
49395   ** this function verifies that this invariant is not violated. */
49396   CellInfo debuginfo;
49397   btreeParseCellPtr(pPage, pCell, &debuginfo);
49398 #endif
49399 
49400   if( pPage->intKey ){
49401     u8 *pEnd;
49402     if( pPage->hasData ){
49403       pIter += getVarint32(pIter, nSize);
49404     }else{
49405       nSize = 0;
49406     }
49407 
49408     /* pIter now points at the 64-bit integer key value, a variable length
49409     ** integer. The following block moves pIter to point at the first byte
49410     ** past the end of the key value. */
49411     pEnd = &pIter[9];
49412     while( (*pIter++)&0x80 && pIter<pEnd );
49413   }else{
49414     pIter += getVarint32(pIter, nSize);
49415   }
49416 
49417   testcase( nSize==pPage->maxLocal );
49418   testcase( nSize==pPage->maxLocal+1 );
49419   if( nSize>pPage->maxLocal ){
49420     int minLocal = pPage->minLocal;
49421     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
49422     testcase( nSize==pPage->maxLocal );
49423     testcase( nSize==pPage->maxLocal+1 );
49424     if( nSize>pPage->maxLocal ){
49425       nSize = minLocal;
49426     }
49427     nSize += 4;
49428   }
49429   nSize += (u32)(pIter - pCell);
49430 
49431   /* The minimum size of any cell is 4 bytes. */
49432   if( nSize<4 ){
49433     nSize = 4;
49434   }
49435 
49436   assert( nSize==debuginfo.nSize );
49437   return (u16)nSize;
49438 }
49439 
49440 #ifdef SQLITE_DEBUG
49441 /* This variation on cellSizePtr() is used inside of assert() statements
49442 ** only. */
49443 static u16 cellSize(MemPage *pPage, int iCell){
49444   return cellSizePtr(pPage, findCell(pPage, iCell));
49445 }
49446 #endif
49447 
49448 #ifndef SQLITE_OMIT_AUTOVACUUM
49449 /*
49450 ** If the cell pCell, part of page pPage contains a pointer
49451 ** to an overflow page, insert an entry into the pointer-map
49452 ** for the overflow page.
49453 */
49454 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
49455   CellInfo info;
49456   if( *pRC ) return;
49457   assert( pCell!=0 );
49458   btreeParseCellPtr(pPage, pCell, &info);
49459   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
49460   if( info.iOverflow ){
49461     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
49462     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
49463   }
49464 }
49465 #endif
49466 
49467 
49468 /*
49469 ** Defragment the page given.  All Cells are moved to the
49470 ** end of the page and all free space is collected into one
49471 ** big FreeBlk that occurs in between the header and cell
49472 ** pointer array and the cell content area.
49473 */
49474 static int defragmentPage(MemPage *pPage){
49475   int i;                     /* Loop counter */
49476   int pc;                    /* Address of a i-th cell */
49477   int hdr;                   /* Offset to the page header */
49478   int size;                  /* Size of a cell */
49479   int usableSize;            /* Number of usable bytes on a page */
49480   int cellOffset;            /* Offset to the cell pointer array */
49481   int cbrk;                  /* Offset to the cell content area */
49482   int nCell;                 /* Number of cells on the page */
49483   unsigned char *data;       /* The page data */
49484   unsigned char *temp;       /* Temp area for cell content */
49485   int iCellFirst;            /* First allowable cell index */
49486   int iCellLast;             /* Last possible cell index */
49487 
49488 
49489   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49490   assert( pPage->pBt!=0 );
49491   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
49492   assert( pPage->nOverflow==0 );
49493   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49494   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
49495   data = pPage->aData;
49496   hdr = pPage->hdrOffset;
49497   cellOffset = pPage->cellOffset;
49498   nCell = pPage->nCell;
49499   assert( nCell==get2byte(&data[hdr+3]) );
49500   usableSize = pPage->pBt->usableSize;
49501   cbrk = get2byte(&data[hdr+5]);
49502   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
49503   cbrk = usableSize;
49504   iCellFirst = cellOffset + 2*nCell;
49505   iCellLast = usableSize - 4;
49506   for(i=0; i<nCell; i++){
49507     u8 *pAddr;     /* The i-th cell pointer */
49508     pAddr = &data[cellOffset + i*2];
49509     pc = get2byte(pAddr);
49510     testcase( pc==iCellFirst );
49511     testcase( pc==iCellLast );
49512 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49513     /* These conditions have already been verified in btreeInitPage()
49514     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
49515     */
49516     if( pc<iCellFirst || pc>iCellLast ){
49517       return SQLITE_CORRUPT_BKPT;
49518     }
49519 #endif
49520     assert( pc>=iCellFirst && pc<=iCellLast );
49521     size = cellSizePtr(pPage, &temp[pc]);
49522     cbrk -= size;
49523 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49524     if( cbrk<iCellFirst ){
49525       return SQLITE_CORRUPT_BKPT;
49526     }
49527 #else
49528     if( cbrk<iCellFirst || pc+size>usableSize ){
49529       return SQLITE_CORRUPT_BKPT;
49530     }
49531 #endif
49532     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
49533     testcase( cbrk+size==usableSize );
49534     testcase( pc+size==usableSize );
49535     memcpy(&data[cbrk], &temp[pc], size);
49536     put2byte(pAddr, cbrk);
49537   }
49538   assert( cbrk>=iCellFirst );
49539   put2byte(&data[hdr+5], cbrk);
49540   data[hdr+1] = 0;
49541   data[hdr+2] = 0;
49542   data[hdr+7] = 0;
49543   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
49544   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49545   if( cbrk-iCellFirst!=pPage->nFree ){
49546     return SQLITE_CORRUPT_BKPT;
49547   }
49548   return SQLITE_OK;
49549 }
49550 
49551 /*
49552 ** Allocate nByte bytes of space from within the B-Tree page passed
49553 ** as the first argument. Write into *pIdx the index into pPage->aData[]
49554 ** of the first byte of allocated space. Return either SQLITE_OK or
49555 ** an error code (usually SQLITE_CORRUPT).
49556 **
49557 ** The caller guarantees that there is sufficient space to make the
49558 ** allocation.  This routine might need to defragment in order to bring
49559 ** all the space together, however.  This routine will avoid using
49560 ** the first two bytes past the cell pointer area since presumably this
49561 ** allocation is being made in order to insert a new cell, so we will
49562 ** also end up needing a new cell pointer.
49563 */
49564 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
49565   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
49566   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
49567   int nFrag;                           /* Number of fragmented bytes on pPage */
49568   int top;                             /* First byte of cell content area */
49569   int gap;        /* First byte of gap between cell pointers and cell content */
49570   int rc;         /* Integer return code */
49571   int usableSize; /* Usable size of the page */
49572 
49573   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49574   assert( pPage->pBt );
49575   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49576   assert( nByte>=0 );  /* Minimum cell size is 4 */
49577   assert( pPage->nFree>=nByte );
49578   assert( pPage->nOverflow==0 );
49579   usableSize = pPage->pBt->usableSize;
49580   assert( nByte < usableSize-8 );
49581 
49582   nFrag = data[hdr+7];
49583   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
49584   gap = pPage->cellOffset + 2*pPage->nCell;
49585   top = get2byteNotZero(&data[hdr+5]);
49586   if( gap>top ) return SQLITE_CORRUPT_BKPT;
49587   testcase( gap+2==top );
49588   testcase( gap+1==top );
49589   testcase( gap==top );
49590 
49591   if( nFrag>=60 ){
49592     /* Always defragment highly fragmented pages */
49593     rc = defragmentPage(pPage);
49594     if( rc ) return rc;
49595     top = get2byteNotZero(&data[hdr+5]);
49596   }else if( gap+2<=top ){
49597     /* Search the freelist looking for a free slot big enough to satisfy
49598     ** the request. The allocation is made from the first free slot in
49599     ** the list that is large enough to accomadate it.
49600     */
49601     int pc, addr;
49602     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
49603       int size;            /* Size of the free slot */
49604       if( pc>usableSize-4 || pc<addr+4 ){
49605         return SQLITE_CORRUPT_BKPT;
49606       }
49607       size = get2byte(&data[pc+2]);
49608       if( size>=nByte ){
49609         int x = size - nByte;
49610         testcase( x==4 );
49611         testcase( x==3 );
49612         if( x<4 ){
49613           /* Remove the slot from the free-list. Update the number of
49614           ** fragmented bytes within the page. */
49615           memcpy(&data[addr], &data[pc], 2);
49616           data[hdr+7] = (u8)(nFrag + x);
49617         }else if( size+pc > usableSize ){
49618           return SQLITE_CORRUPT_BKPT;
49619         }else{
49620           /* The slot remains on the free-list. Reduce its size to account
49621           ** for the portion used by the new allocation. */
49622           put2byte(&data[pc+2], x);
49623         }
49624         *pIdx = pc + x;
49625         return SQLITE_OK;
49626       }
49627     }
49628   }
49629 
49630   /* Check to make sure there is enough space in the gap to satisfy
49631   ** the allocation.  If not, defragment.
49632   */
49633   testcase( gap+2+nByte==top );
49634   if( gap+2+nByte>top ){
49635     rc = defragmentPage(pPage);
49636     if( rc ) return rc;
49637     top = get2byteNotZero(&data[hdr+5]);
49638     assert( gap+nByte<=top );
49639   }
49640 
49641 
49642   /* Allocate memory from the gap in between the cell pointer array
49643   ** and the cell content area.  The btreeInitPage() call has already
49644   ** validated the freelist.  Given that the freelist is valid, there
49645   ** is no way that the allocation can extend off the end of the page.
49646   ** The assert() below verifies the previous sentence.
49647   */
49648   top -= nByte;
49649   put2byte(&data[hdr+5], top);
49650   assert( top+nByte <= (int)pPage->pBt->usableSize );
49651   *pIdx = top;
49652   return SQLITE_OK;
49653 }
49654 
49655 /*
49656 ** Return a section of the pPage->aData to the freelist.
49657 ** The first byte of the new free block is pPage->aDisk[start]
49658 ** and the size of the block is "size" bytes.
49659 **
49660 ** Most of the effort here is involved in coalesing adjacent
49661 ** free blocks into a single big free block.
49662 */
49663 static int freeSpace(MemPage *pPage, int start, int size){
49664   int addr, pbegin, hdr;
49665   int iLast;                        /* Largest possible freeblock offset */
49666   unsigned char *data = pPage->aData;
49667 
49668   assert( pPage->pBt!=0 );
49669   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49670   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
49671   assert( (start + size) <= (int)pPage->pBt->usableSize );
49672   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49673   assert( size>=0 );   /* Minimum cell size is 4 */
49674 
49675   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
49676     /* Overwrite deleted information with zeros when the secure_delete
49677     ** option is enabled */
49678     memset(&data[start], 0, size);
49679   }
49680 
49681   /* Add the space back into the linked list of freeblocks.  Note that
49682   ** even though the freeblock list was checked by btreeInitPage(),
49683   ** btreeInitPage() did not detect overlapping cells or
49684   ** freeblocks that overlapped cells.   Nor does it detect when the
49685   ** cell content area exceeds the value in the page header.  If these
49686   ** situations arise, then subsequent insert operations might corrupt
49687   ** the freelist.  So we do need to check for corruption while scanning
49688   ** the freelist.
49689   */
49690   hdr = pPage->hdrOffset;
49691   addr = hdr + 1;
49692   iLast = pPage->pBt->usableSize - 4;
49693   assert( start<=iLast );
49694   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
49695     if( pbegin<addr+4 ){
49696       return SQLITE_CORRUPT_BKPT;
49697     }
49698     addr = pbegin;
49699   }
49700   if( pbegin>iLast ){
49701     return SQLITE_CORRUPT_BKPT;
49702   }
49703   assert( pbegin>addr || pbegin==0 );
49704   put2byte(&data[addr], start);
49705   put2byte(&data[start], pbegin);
49706   put2byte(&data[start+2], size);
49707   pPage->nFree = pPage->nFree + (u16)size;
49708 
49709   /* Coalesce adjacent free blocks */
49710   addr = hdr + 1;
49711   while( (pbegin = get2byte(&data[addr]))>0 ){
49712     int pnext, psize, x;
49713     assert( pbegin>addr );
49714     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
49715     pnext = get2byte(&data[pbegin]);
49716     psize = get2byte(&data[pbegin+2]);
49717     if( pbegin + psize + 3 >= pnext && pnext>0 ){
49718       int frag = pnext - (pbegin+psize);
49719       if( (frag<0) || (frag>(int)data[hdr+7]) ){
49720         return SQLITE_CORRUPT_BKPT;
49721       }
49722       data[hdr+7] -= (u8)frag;
49723       x = get2byte(&data[pnext]);
49724       put2byte(&data[pbegin], x);
49725       x = pnext + get2byte(&data[pnext+2]) - pbegin;
49726       put2byte(&data[pbegin+2], x);
49727     }else{
49728       addr = pbegin;
49729     }
49730   }
49731 
49732   /* If the cell content area begins with a freeblock, remove it. */
49733   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
49734     int top;
49735     pbegin = get2byte(&data[hdr+1]);
49736     memcpy(&data[hdr+1], &data[pbegin], 2);
49737     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
49738     put2byte(&data[hdr+5], top);
49739   }
49740   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49741   return SQLITE_OK;
49742 }
49743 
49744 /*
49745 ** Decode the flags byte (the first byte of the header) for a page
49746 ** and initialize fields of the MemPage structure accordingly.
49747 **
49748 ** Only the following combinations are supported.  Anything different
49749 ** indicates a corrupt database files:
49750 **
49751 **         PTF_ZERODATA
49752 **         PTF_ZERODATA | PTF_LEAF
49753 **         PTF_LEAFDATA | PTF_INTKEY
49754 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
49755 */
49756 static int decodeFlags(MemPage *pPage, int flagByte){
49757   BtShared *pBt;     /* A copy of pPage->pBt */
49758 
49759   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
49760   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49761   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
49762   flagByte &= ~PTF_LEAF;
49763   pPage->childPtrSize = 4-4*pPage->leaf;
49764   pBt = pPage->pBt;
49765   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
49766     pPage->intKey = 1;
49767     pPage->hasData = pPage->leaf;
49768     pPage->maxLocal = pBt->maxLeaf;
49769     pPage->minLocal = pBt->minLeaf;
49770   }else if( flagByte==PTF_ZERODATA ){
49771     pPage->intKey = 0;
49772     pPage->hasData = 0;
49773     pPage->maxLocal = pBt->maxLocal;
49774     pPage->minLocal = pBt->minLocal;
49775   }else{
49776     return SQLITE_CORRUPT_BKPT;
49777   }
49778   pPage->max1bytePayload = pBt->max1bytePayload;
49779   return SQLITE_OK;
49780 }
49781 
49782 /*
49783 ** Initialize the auxiliary information for a disk block.
49784 **
49785 ** Return SQLITE_OK on success.  If we see that the page does
49786 ** not contain a well-formed database page, then return
49787 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
49788 ** guarantee that the page is well-formed.  It only shows that
49789 ** we failed to detect any corruption.
49790 */
49791 static int btreeInitPage(MemPage *pPage){
49792 
49793   assert( pPage->pBt!=0 );
49794   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49795   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
49796   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
49797   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
49798 
49799   if( !pPage->isInit ){
49800     u16 pc;            /* Address of a freeblock within pPage->aData[] */
49801     u8 hdr;            /* Offset to beginning of page header */
49802     u8 *data;          /* Equal to pPage->aData */
49803     BtShared *pBt;        /* The main btree structure */
49804     int usableSize;    /* Amount of usable space on each page */
49805     u16 cellOffset;    /* Offset from start of page to first cell pointer */
49806     int nFree;         /* Number of unused bytes on the page */
49807     int top;           /* First byte of the cell content area */
49808     int iCellFirst;    /* First allowable cell or freeblock offset */
49809     int iCellLast;     /* Last possible cell or freeblock offset */
49810 
49811     pBt = pPage->pBt;
49812 
49813     hdr = pPage->hdrOffset;
49814     data = pPage->aData;
49815     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
49816     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49817     pPage->maskPage = (u16)(pBt->pageSize - 1);
49818     pPage->nOverflow = 0;
49819     usableSize = pBt->usableSize;
49820     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
49821     pPage->aDataEnd = &data[usableSize];
49822     pPage->aCellIdx = &data[cellOffset];
49823     top = get2byteNotZero(&data[hdr+5]);
49824     pPage->nCell = get2byte(&data[hdr+3]);
49825     if( pPage->nCell>MX_CELL(pBt) ){
49826       /* To many cells for a single page.  The page must be corrupt */
49827       return SQLITE_CORRUPT_BKPT;
49828     }
49829     testcase( pPage->nCell==MX_CELL(pBt) );
49830 
49831     /* A malformed database page might cause us to read past the end
49832     ** of page when parsing a cell.
49833     **
49834     ** The following block of code checks early to see if a cell extends
49835     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
49836     ** returned if it does.
49837     */
49838     iCellFirst = cellOffset + 2*pPage->nCell;
49839     iCellLast = usableSize - 4;
49840 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49841     {
49842       int i;            /* Index into the cell pointer array */
49843       int sz;           /* Size of a cell */
49844 
49845       if( !pPage->leaf ) iCellLast--;
49846       for(i=0; i<pPage->nCell; i++){
49847         pc = get2byte(&data[cellOffset+i*2]);
49848         testcase( pc==iCellFirst );
49849         testcase( pc==iCellLast );
49850         if( pc<iCellFirst || pc>iCellLast ){
49851           return SQLITE_CORRUPT_BKPT;
49852         }
49853         sz = cellSizePtr(pPage, &data[pc]);
49854         testcase( pc+sz==usableSize );
49855         if( pc+sz>usableSize ){
49856           return SQLITE_CORRUPT_BKPT;
49857         }
49858       }
49859       if( !pPage->leaf ) iCellLast++;
49860     }
49861 #endif
49862 
49863     /* Compute the total free space on the page */
49864     pc = get2byte(&data[hdr+1]);
49865     nFree = data[hdr+7] + top;
49866     while( pc>0 ){
49867       u16 next, size;
49868       if( pc<iCellFirst || pc>iCellLast ){
49869         /* Start of free block is off the page */
49870         return SQLITE_CORRUPT_BKPT;
49871       }
49872       next = get2byte(&data[pc]);
49873       size = get2byte(&data[pc+2]);
49874       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
49875         /* Free blocks must be in ascending order. And the last byte of
49876         ** the free-block must lie on the database page.  */
49877         return SQLITE_CORRUPT_BKPT;
49878       }
49879       nFree = nFree + size;
49880       pc = next;
49881     }
49882 
49883     /* At this point, nFree contains the sum of the offset to the start
49884     ** of the cell-content area plus the number of free bytes within
49885     ** the cell-content area. If this is greater than the usable-size
49886     ** of the page, then the page must be corrupted. This check also
49887     ** serves to verify that the offset to the start of the cell-content
49888     ** area, according to the page header, lies within the page.
49889     */
49890     if( nFree>usableSize ){
49891       return SQLITE_CORRUPT_BKPT;
49892     }
49893     pPage->nFree = (u16)(nFree - iCellFirst);
49894     pPage->isInit = 1;
49895   }
49896   return SQLITE_OK;
49897 }
49898 
49899 /*
49900 ** Set up a raw page so that it looks like a database page holding
49901 ** no entries.
49902 */
49903 static void zeroPage(MemPage *pPage, int flags){
49904   unsigned char *data = pPage->aData;
49905   BtShared *pBt = pPage->pBt;
49906   u8 hdr = pPage->hdrOffset;
49907   u16 first;
49908 
49909   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49910   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49911   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49912   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49913   assert( sqlite3_mutex_held(pBt->mutex) );
49914   if( pBt->btsFlags & BTS_SECURE_DELETE ){
49915     memset(&data[hdr], 0, pBt->usableSize - hdr);
49916   }
49917   data[hdr] = (char)flags;
49918   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49919   memset(&data[hdr+1], 0, 4);
49920   data[hdr+7] = 0;
49921   put2byte(&data[hdr+5], pBt->usableSize);
49922   pPage->nFree = (u16)(pBt->usableSize - first);
49923   decodeFlags(pPage, flags);
49924   pPage->hdrOffset = hdr;
49925   pPage->cellOffset = first;
49926   pPage->aDataEnd = &data[pBt->usableSize];
49927   pPage->aCellIdx = &data[first];
49928   pPage->nOverflow = 0;
49929   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49930   pPage->maskPage = (u16)(pBt->pageSize - 1);
49931   pPage->nCell = 0;
49932   pPage->isInit = 1;
49933 }
49934 
49935 
49936 /*
49937 ** Convert a DbPage obtained from the pager into a MemPage used by
49938 ** the btree layer.
49939 */
49940 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49941   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49942   pPage->aData = sqlite3PagerGetData(pDbPage);
49943   pPage->pDbPage = pDbPage;
49944   pPage->pBt = pBt;
49945   pPage->pgno = pgno;
49946   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49947   return pPage;
49948 }
49949 
49950 /*
49951 ** Get a page from the pager.  Initialize the MemPage.pBt and
49952 ** MemPage.aData elements if needed.
49953 **
49954 ** If the noContent flag is set, it means that we do not care about
49955 ** the content of the page at this time.  So do not go to the disk
49956 ** to fetch the content.  Just fill in the content with zeros for now.
49957 ** If in the future we call sqlite3PagerWrite() on this page, that
49958 ** means we have started to be concerned about content and the disk
49959 ** read should occur at that point.
49960 */
49961 static int btreeGetPage(
49962   BtShared *pBt,       /* The btree */
49963   Pgno pgno,           /* Number of the page to fetch */
49964   MemPage **ppPage,    /* Return the page in this parameter */
49965   int noContent        /* Do not load page content if true */
49966 ){
49967   int rc;
49968   DbPage *pDbPage;
49969 
49970   assert( sqlite3_mutex_held(pBt->mutex) );
49971   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49972   if( rc ) return rc;
49973   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49974   return SQLITE_OK;
49975 }
49976 
49977 /*
49978 ** Retrieve a page from the pager cache. If the requested page is not
49979 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49980 ** MemPage.aData elements if needed.
49981 */
49982 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49983   DbPage *pDbPage;
49984   assert( sqlite3_mutex_held(pBt->mutex) );
49985   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49986   if( pDbPage ){
49987     return btreePageFromDbPage(pDbPage, pgno, pBt);
49988   }
49989   return 0;
49990 }
49991 
49992 /*
49993 ** Return the size of the database file in pages. If there is any kind of
49994 ** error, return ((unsigned int)-1).
49995 */
49996 static Pgno btreePagecount(BtShared *pBt){
49997   return pBt->nPage;
49998 }
49999 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
50000   assert( sqlite3BtreeHoldsMutex(p) );
50001   assert( ((p->pBt->nPage)&0x8000000)==0 );
50002   return (int)btreePagecount(p->pBt);
50003 }
50004 
50005 /*
50006 ** Get a page from the pager and initialize it.  This routine is just a
50007 ** convenience wrapper around separate calls to btreeGetPage() and
50008 ** btreeInitPage().
50009 **
50010 ** If an error occurs, then the value *ppPage is set to is undefined. It
50011 ** may remain unchanged, or it may be set to an invalid value.
50012 */
50013 static int getAndInitPage(
50014   BtShared *pBt,          /* The database file */
50015   Pgno pgno,           /* Number of the page to get */
50016   MemPage **ppPage     /* Write the page pointer here */
50017 ){
50018   int rc;
50019   assert( sqlite3_mutex_held(pBt->mutex) );
50020 
50021   if( pgno>btreePagecount(pBt) ){
50022     rc = SQLITE_CORRUPT_BKPT;
50023   }else{
50024     rc = btreeGetPage(pBt, pgno, ppPage, 0);
50025     if( rc==SQLITE_OK ){
50026       rc = btreeInitPage(*ppPage);
50027       if( rc!=SQLITE_OK ){
50028         releasePage(*ppPage);
50029       }
50030     }
50031   }
50032 
50033   testcase( pgno==0 );
50034   assert( pgno!=0 || rc==SQLITE_CORRUPT );
50035   return rc;
50036 }
50037 
50038 /*
50039 ** Release a MemPage.  This should be called once for each prior
50040 ** call to btreeGetPage.
50041 */
50042 static void releasePage(MemPage *pPage){
50043   if( pPage ){
50044     assert( pPage->aData );
50045     assert( pPage->pBt );
50046     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
50047     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
50048     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50049     sqlite3PagerUnref(pPage->pDbPage);
50050   }
50051 }
50052 
50053 /*
50054 ** During a rollback, when the pager reloads information into the cache
50055 ** so that the cache is restored to its original state at the start of
50056 ** the transaction, for each page restored this routine is called.
50057 **
50058 ** This routine needs to reset the extra data section at the end of the
50059 ** page to agree with the restored data.
50060 */
50061 static void pageReinit(DbPage *pData){
50062   MemPage *pPage;
50063   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
50064   assert( sqlite3PagerPageRefcount(pData)>0 );
50065   if( pPage->isInit ){
50066     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50067     pPage->isInit = 0;
50068     if( sqlite3PagerPageRefcount(pData)>1 ){
50069       /* pPage might not be a btree page;  it might be an overflow page
50070       ** or ptrmap page or a free page.  In those cases, the following
50071       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
50072       ** But no harm is done by this.  And it is very important that
50073       ** btreeInitPage() be called on every btree page so we make
50074       ** the call for every page that comes in for re-initing. */
50075       btreeInitPage(pPage);
50076     }
50077   }
50078 }
50079 
50080 /*
50081 ** Invoke the busy handler for a btree.
50082 */
50083 static int btreeInvokeBusyHandler(void *pArg){
50084   BtShared *pBt = (BtShared*)pArg;
50085   assert( pBt->db );
50086   assert( sqlite3_mutex_held(pBt->db->mutex) );
50087   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
50088 }
50089 
50090 /*
50091 ** Open a database file.
50092 **
50093 ** zFilename is the name of the database file.  If zFilename is NULL
50094 ** then an ephemeral database is created.  The ephemeral database might
50095 ** be exclusively in memory, or it might use a disk-based memory cache.
50096 ** Either way, the ephemeral database will be automatically deleted
50097 ** when sqlite3BtreeClose() is called.
50098 **
50099 ** If zFilename is ":memory:" then an in-memory database is created
50100 ** that is automatically destroyed when it is closed.
50101 **
50102 ** The "flags" parameter is a bitmask that might contain bits like
50103 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
50104 **
50105 ** If the database is already opened in the same database connection
50106 ** and we are in shared cache mode, then the open will fail with an
50107 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
50108 ** objects in the same database connection since doing so will lead
50109 ** to problems with locking.
50110 */
50111 SQLITE_PRIVATE int sqlite3BtreeOpen(
50112   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
50113   const char *zFilename,  /* Name of the file containing the BTree database */
50114   sqlite3 *db,            /* Associated database handle */
50115   Btree **ppBtree,        /* Pointer to new Btree object written here */
50116   int flags,              /* Options */
50117   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
50118 ){
50119   BtShared *pBt = 0;             /* Shared part of btree structure */
50120   Btree *p;                      /* Handle to return */
50121   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
50122   int rc = SQLITE_OK;            /* Result code from this function */
50123   u8 nReserve;                   /* Byte of unused space on each page */
50124   unsigned char zDbHeader[100];  /* Database header content */
50125 
50126   /* True if opening an ephemeral, temporary database */
50127   const int isTempDb = zFilename==0 || zFilename[0]==0;
50128 
50129   /* Set the variable isMemdb to true for an in-memory database, or
50130   ** false for a file-based database.
50131   */
50132 #ifdef SQLITE_OMIT_MEMORYDB
50133   const int isMemdb = 0;
50134 #else
50135   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
50136                        || (isTempDb && sqlite3TempInMemory(db))
50137                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
50138 #endif
50139 
50140   assert( db!=0 );
50141   assert( pVfs!=0 );
50142   assert( sqlite3_mutex_held(db->mutex) );
50143   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
50144 
50145   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
50146   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
50147 
50148   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
50149   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
50150 
50151   if( isMemdb ){
50152     flags |= BTREE_MEMORY;
50153   }
50154   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
50155     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
50156   }
50157   p = sqlite3MallocZero(sizeof(Btree));
50158   if( !p ){
50159     return SQLITE_NOMEM;
50160   }
50161   p->inTrans = TRANS_NONE;
50162   p->db = db;
50163 #ifndef SQLITE_OMIT_SHARED_CACHE
50164   p->lock.pBtree = p;
50165   p->lock.iTable = 1;
50166 #endif
50167 
50168 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50169   /*
50170   ** If this Btree is a candidate for shared cache, try to find an
50171   ** existing BtShared object that we can share with
50172   */
50173   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
50174     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
50175       int nFullPathname = pVfs->mxPathname+1;
50176       char *zFullPathname = sqlite3Malloc(nFullPathname);
50177       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
50178       p->sharable = 1;
50179       if( !zFullPathname ){
50180         sqlite3_free(p);
50181         return SQLITE_NOMEM;
50182       }
50183       if( isMemdb ){
50184         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
50185       }else{
50186         rc = sqlite3OsFullPathname(pVfs, zFilename,
50187                                    nFullPathname, zFullPathname);
50188         if( rc ){
50189           sqlite3_free(zFullPathname);
50190           sqlite3_free(p);
50191           return rc;
50192         }
50193       }
50194 #if SQLITE_THREADSAFE
50195       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
50196       sqlite3_mutex_enter(mutexOpen);
50197       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
50198       sqlite3_mutex_enter(mutexShared);
50199 #endif
50200       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
50201         assert( pBt->nRef>0 );
50202         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
50203                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
50204           int iDb;
50205           for(iDb=db->nDb-1; iDb>=0; iDb--){
50206             Btree *pExisting = db->aDb[iDb].pBt;
50207             if( pExisting && pExisting->pBt==pBt ){
50208               sqlite3_mutex_leave(mutexShared);
50209               sqlite3_mutex_leave(mutexOpen);
50210               sqlite3_free(zFullPathname);
50211               sqlite3_free(p);
50212               return SQLITE_CONSTRAINT;
50213             }
50214           }
50215           p->pBt = pBt;
50216           pBt->nRef++;
50217           break;
50218         }
50219       }
50220       sqlite3_mutex_leave(mutexShared);
50221       sqlite3_free(zFullPathname);
50222     }
50223 #ifdef SQLITE_DEBUG
50224     else{
50225       /* In debug mode, we mark all persistent databases as sharable
50226       ** even when they are not.  This exercises the locking code and
50227       ** gives more opportunity for asserts(sqlite3_mutex_held())
50228       ** statements to find locking problems.
50229       */
50230       p->sharable = 1;
50231     }
50232 #endif
50233   }
50234 #endif
50235   if( pBt==0 ){
50236     /*
50237     ** The following asserts make sure that structures used by the btree are
50238     ** the right size.  This is to guard against size changes that result
50239     ** when compiling on a different architecture.
50240     */
50241     assert( sizeof(i64)==8 || sizeof(i64)==4 );
50242     assert( sizeof(u64)==8 || sizeof(u64)==4 );
50243     assert( sizeof(u32)==4 );
50244     assert( sizeof(u16)==2 );
50245     assert( sizeof(Pgno)==4 );
50246 
50247     pBt = sqlite3MallocZero( sizeof(*pBt) );
50248     if( pBt==0 ){
50249       rc = SQLITE_NOMEM;
50250       goto btree_open_out;
50251     }
50252     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
50253                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
50254     if( rc==SQLITE_OK ){
50255       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
50256     }
50257     if( rc!=SQLITE_OK ){
50258       goto btree_open_out;
50259     }
50260     pBt->openFlags = (u8)flags;
50261     pBt->db = db;
50262     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
50263     p->pBt = pBt;
50264 
50265     pBt->pCursor = 0;
50266     pBt->pPage1 = 0;
50267     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
50268 #ifdef SQLITE_SECURE_DELETE
50269     pBt->btsFlags |= BTS_SECURE_DELETE;
50270 #endif
50271     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
50272     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
50273          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
50274       pBt->pageSize = 0;
50275 #ifndef SQLITE_OMIT_AUTOVACUUM
50276       /* If the magic name ":memory:" will create an in-memory database, then
50277       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
50278       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
50279       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
50280       ** regular file-name. In this case the auto-vacuum applies as per normal.
50281       */
50282       if( zFilename && !isMemdb ){
50283         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
50284         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
50285       }
50286 #endif
50287       nReserve = 0;
50288     }else{
50289       nReserve = zDbHeader[20];
50290       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50291 #ifndef SQLITE_OMIT_AUTOVACUUM
50292       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
50293       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
50294 #endif
50295     }
50296     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50297     if( rc ) goto btree_open_out;
50298     pBt->usableSize = pBt->pageSize - nReserve;
50299     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
50300 
50301 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50302     /* Add the new BtShared object to the linked list sharable BtShareds.
50303     */
50304     if( p->sharable ){
50305       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
50306       pBt->nRef = 1;
50307       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
50308       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
50309         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
50310         if( pBt->mutex==0 ){
50311           rc = SQLITE_NOMEM;
50312           db->mallocFailed = 0;
50313           goto btree_open_out;
50314         }
50315       }
50316       sqlite3_mutex_enter(mutexShared);
50317       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
50318       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
50319       sqlite3_mutex_leave(mutexShared);
50320     }
50321 #endif
50322   }
50323 
50324 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50325   /* If the new Btree uses a sharable pBtShared, then link the new
50326   ** Btree into the list of all sharable Btrees for the same connection.
50327   ** The list is kept in ascending order by pBt address.
50328   */
50329   if( p->sharable ){
50330     int i;
50331     Btree *pSib;
50332     for(i=0; i<db->nDb; i++){
50333       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
50334         while( pSib->pPrev ){ pSib = pSib->pPrev; }
50335         if( p->pBt<pSib->pBt ){
50336           p->pNext = pSib;
50337           p->pPrev = 0;
50338           pSib->pPrev = p;
50339         }else{
50340           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
50341             pSib = pSib->pNext;
50342           }
50343           p->pNext = pSib->pNext;
50344           p->pPrev = pSib;
50345           if( p->pNext ){
50346             p->pNext->pPrev = p;
50347           }
50348           pSib->pNext = p;
50349         }
50350         break;
50351       }
50352     }
50353   }
50354 #endif
50355   *ppBtree = p;
50356 
50357 btree_open_out:
50358   if( rc!=SQLITE_OK ){
50359     if( pBt && pBt->pPager ){
50360       sqlite3PagerClose(pBt->pPager);
50361     }
50362     sqlite3_free(pBt);
50363     sqlite3_free(p);
50364     *ppBtree = 0;
50365   }else{
50366     /* If the B-Tree was successfully opened, set the pager-cache size to the
50367     ** default value. Except, when opening on an existing shared pager-cache,
50368     ** do not change the pager-cache size.
50369     */
50370     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
50371       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
50372     }
50373   }
50374   if( mutexOpen ){
50375     assert( sqlite3_mutex_held(mutexOpen) );
50376     sqlite3_mutex_leave(mutexOpen);
50377   }
50378   return rc;
50379 }
50380 
50381 /*
50382 ** Decrement the BtShared.nRef counter.  When it reaches zero,
50383 ** remove the BtShared structure from the sharing list.  Return
50384 ** true if the BtShared.nRef counter reaches zero and return
50385 ** false if it is still positive.
50386 */
50387 static int removeFromSharingList(BtShared *pBt){
50388 #ifndef SQLITE_OMIT_SHARED_CACHE
50389   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
50390   BtShared *pList;
50391   int removed = 0;
50392 
50393   assert( sqlite3_mutex_notheld(pBt->mutex) );
50394   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
50395   sqlite3_mutex_enter(pMaster);
50396   pBt->nRef--;
50397   if( pBt->nRef<=0 ){
50398     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
50399       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
50400     }else{
50401       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
50402       while( ALWAYS(pList) && pList->pNext!=pBt ){
50403         pList=pList->pNext;
50404       }
50405       if( ALWAYS(pList) ){
50406         pList->pNext = pBt->pNext;
50407       }
50408     }
50409     if( SQLITE_THREADSAFE ){
50410       sqlite3_mutex_free(pBt->mutex);
50411     }
50412     removed = 1;
50413   }
50414   sqlite3_mutex_leave(pMaster);
50415   return removed;
50416 #else
50417   return 1;
50418 #endif
50419 }
50420 
50421 /*
50422 ** Make sure pBt->pTmpSpace points to an allocation of
50423 ** MX_CELL_SIZE(pBt) bytes.
50424 */
50425 static void allocateTempSpace(BtShared *pBt){
50426   if( !pBt->pTmpSpace ){
50427     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
50428   }
50429 }
50430 
50431 /*
50432 ** Free the pBt->pTmpSpace allocation
50433 */
50434 static void freeTempSpace(BtShared *pBt){
50435   sqlite3PageFree( pBt->pTmpSpace);
50436   pBt->pTmpSpace = 0;
50437 }
50438 
50439 /*
50440 ** Close an open database and invalidate all cursors.
50441 */
50442 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
50443   BtShared *pBt = p->pBt;
50444   BtCursor *pCur;
50445 
50446   /* Close all cursors opened via this handle.  */
50447   assert( sqlite3_mutex_held(p->db->mutex) );
50448   sqlite3BtreeEnter(p);
50449   pCur = pBt->pCursor;
50450   while( pCur ){
50451     BtCursor *pTmp = pCur;
50452     pCur = pCur->pNext;
50453     if( pTmp->pBtree==p ){
50454       sqlite3BtreeCloseCursor(pTmp);
50455     }
50456   }
50457 
50458   /* Rollback any active transaction and free the handle structure.
50459   ** The call to sqlite3BtreeRollback() drops any table-locks held by
50460   ** this handle.
50461   */
50462   sqlite3BtreeRollback(p, SQLITE_OK);
50463   sqlite3BtreeLeave(p);
50464 
50465   /* If there are still other outstanding references to the shared-btree
50466   ** structure, return now. The remainder of this procedure cleans
50467   ** up the shared-btree.
50468   */
50469   assert( p->wantToLock==0 && p->locked==0 );
50470   if( !p->sharable || removeFromSharingList(pBt) ){
50471     /* The pBt is no longer on the sharing list, so we can access
50472     ** it without having to hold the mutex.
50473     **
50474     ** Clean out and delete the BtShared object.
50475     */
50476     assert( !pBt->pCursor );
50477     sqlite3PagerClose(pBt->pPager);
50478     if( pBt->xFreeSchema && pBt->pSchema ){
50479       pBt->xFreeSchema(pBt->pSchema);
50480     }
50481     sqlite3DbFree(0, pBt->pSchema);
50482     freeTempSpace(pBt);
50483     sqlite3_free(pBt);
50484   }
50485 
50486 #ifndef SQLITE_OMIT_SHARED_CACHE
50487   assert( p->wantToLock==0 );
50488   assert( p->locked==0 );
50489   if( p->pPrev ) p->pPrev->pNext = p->pNext;
50490   if( p->pNext ) p->pNext->pPrev = p->pPrev;
50491 #endif
50492 
50493   sqlite3_free(p);
50494   return SQLITE_OK;
50495 }
50496 
50497 /*
50498 ** Change the limit on the number of pages allowed in the cache.
50499 **
50500 ** The maximum number of cache pages is set to the absolute
50501 ** value of mxPage.  If mxPage is negative, the pager will
50502 ** operate asynchronously - it will not stop to do fsync()s
50503 ** to insure data is written to the disk surface before
50504 ** continuing.  Transactions still work if synchronous is off,
50505 ** and the database cannot be corrupted if this program
50506 ** crashes.  But if the operating system crashes or there is
50507 ** an abrupt power failure when synchronous is off, the database
50508 ** could be left in an inconsistent and unrecoverable state.
50509 ** Synchronous is on by default so database corruption is not
50510 ** normally a worry.
50511 */
50512 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
50513   BtShared *pBt = p->pBt;
50514   assert( sqlite3_mutex_held(p->db->mutex) );
50515   sqlite3BtreeEnter(p);
50516   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
50517   sqlite3BtreeLeave(p);
50518   return SQLITE_OK;
50519 }
50520 
50521 /*
50522 ** Change the way data is synced to disk in order to increase or decrease
50523 ** how well the database resists damage due to OS crashes and power
50524 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
50525 ** there is a high probability of damage)  Level 2 is the default.  There
50526 ** is a very low but non-zero probability of damage.  Level 3 reduces the
50527 ** probability of damage to near zero but with a write performance reduction.
50528 */
50529 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
50530 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
50531   Btree *p,              /* The btree to set the safety level on */
50532   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
50533   int fullSync,          /* PRAGMA fullfsync. */
50534   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
50535 ){
50536   BtShared *pBt = p->pBt;
50537   assert( sqlite3_mutex_held(p->db->mutex) );
50538   assert( level>=1 && level<=3 );
50539   sqlite3BtreeEnter(p);
50540   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
50541   sqlite3BtreeLeave(p);
50542   return SQLITE_OK;
50543 }
50544 #endif
50545 
50546 /*
50547 ** Return TRUE if the given btree is set to safety level 1.  In other
50548 ** words, return TRUE if no sync() occurs on the disk files.
50549 */
50550 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
50551   BtShared *pBt = p->pBt;
50552   int rc;
50553   assert( sqlite3_mutex_held(p->db->mutex) );
50554   sqlite3BtreeEnter(p);
50555   assert( pBt && pBt->pPager );
50556   rc = sqlite3PagerNosync(pBt->pPager);
50557   sqlite3BtreeLeave(p);
50558   return rc;
50559 }
50560 
50561 /*
50562 ** Change the default pages size and the number of reserved bytes per page.
50563 ** Or, if the page size has already been fixed, return SQLITE_READONLY
50564 ** without changing anything.
50565 **
50566 ** The page size must be a power of 2 between 512 and 65536.  If the page
50567 ** size supplied does not meet this constraint then the page size is not
50568 ** changed.
50569 **
50570 ** Page sizes are constrained to be a power of two so that the region
50571 ** of the database file used for locking (beginning at PENDING_BYTE,
50572 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
50573 ** at the beginning of a page.
50574 **
50575 ** If parameter nReserve is less than zero, then the number of reserved
50576 ** bytes per page is left unchanged.
50577 **
50578 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
50579 ** and autovacuum mode can no longer be changed.
50580 */
50581 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
50582   int rc = SQLITE_OK;
50583   BtShared *pBt = p->pBt;
50584   assert( nReserve>=-1 && nReserve<=255 );
50585   sqlite3BtreeEnter(p);
50586   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
50587     sqlite3BtreeLeave(p);
50588     return SQLITE_READONLY;
50589   }
50590   if( nReserve<0 ){
50591     nReserve = pBt->pageSize - pBt->usableSize;
50592   }
50593   assert( nReserve>=0 && nReserve<=255 );
50594   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
50595         ((pageSize-1)&pageSize)==0 ){
50596     assert( (pageSize & 7)==0 );
50597     assert( !pBt->pPage1 && !pBt->pCursor );
50598     pBt->pageSize = (u32)pageSize;
50599     freeTempSpace(pBt);
50600   }
50601   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50602   pBt->usableSize = pBt->pageSize - (u16)nReserve;
50603   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50604   sqlite3BtreeLeave(p);
50605   return rc;
50606 }
50607 
50608 /*
50609 ** Return the currently defined page size
50610 */
50611 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
50612   return p->pBt->pageSize;
50613 }
50614 
50615 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
50616 /*
50617 ** This function is similar to sqlite3BtreeGetReserve(), except that it
50618 ** may only be called if it is guaranteed that the b-tree mutex is already
50619 ** held.
50620 **
50621 ** This is useful in one special case in the backup API code where it is
50622 ** known that the shared b-tree mutex is held, but the mutex on the
50623 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
50624 ** were to be called, it might collide with some other operation on the
50625 ** database handle that owns *p, causing undefined behavior.
50626 */
50627 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
50628   assert( sqlite3_mutex_held(p->pBt->mutex) );
50629   return p->pBt->pageSize - p->pBt->usableSize;
50630 }
50631 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
50632 
50633 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
50634 /*
50635 ** Return the number of bytes of space at the end of every page that
50636 ** are intentually left unused.  This is the "reserved" space that is
50637 ** sometimes used by extensions.
50638 */
50639 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
50640   int n;
50641   sqlite3BtreeEnter(p);
50642   n = p->pBt->pageSize - p->pBt->usableSize;
50643   sqlite3BtreeLeave(p);
50644   return n;
50645 }
50646 
50647 /*
50648 ** Set the maximum page count for a database if mxPage is positive.
50649 ** No changes are made if mxPage is 0 or negative.
50650 ** Regardless of the value of mxPage, return the maximum page count.
50651 */
50652 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
50653   int n;
50654   sqlite3BtreeEnter(p);
50655   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
50656   sqlite3BtreeLeave(p);
50657   return n;
50658 }
50659 
50660 /*
50661 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
50662 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
50663 ** setting after the change.
50664 */
50665 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
50666   int b;
50667   if( p==0 ) return 0;
50668   sqlite3BtreeEnter(p);
50669   if( newFlag>=0 ){
50670     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
50671     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
50672   }
50673   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
50674   sqlite3BtreeLeave(p);
50675   return b;
50676 }
50677 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
50678 
50679 /*
50680 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
50681 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
50682 ** is disabled. The default value for the auto-vacuum property is
50683 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
50684 */
50685 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
50686 #ifdef SQLITE_OMIT_AUTOVACUUM
50687   return SQLITE_READONLY;
50688 #else
50689   BtShared *pBt = p->pBt;
50690   int rc = SQLITE_OK;
50691   u8 av = (u8)autoVacuum;
50692 
50693   sqlite3BtreeEnter(p);
50694   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
50695     rc = SQLITE_READONLY;
50696   }else{
50697     pBt->autoVacuum = av ?1:0;
50698     pBt->incrVacuum = av==2 ?1:0;
50699   }
50700   sqlite3BtreeLeave(p);
50701   return rc;
50702 #endif
50703 }
50704 
50705 /*
50706 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
50707 ** enabled 1 is returned. Otherwise 0.
50708 */
50709 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
50710 #ifdef SQLITE_OMIT_AUTOVACUUM
50711   return BTREE_AUTOVACUUM_NONE;
50712 #else
50713   int rc;
50714   sqlite3BtreeEnter(p);
50715   rc = (
50716     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
50717     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
50718     BTREE_AUTOVACUUM_INCR
50719   );
50720   sqlite3BtreeLeave(p);
50721   return rc;
50722 #endif
50723 }
50724 
50725 
50726 /*
50727 ** Get a reference to pPage1 of the database file.  This will
50728 ** also acquire a readlock on that file.
50729 **
50730 ** SQLITE_OK is returned on success.  If the file is not a
50731 ** well-formed database file, then SQLITE_CORRUPT is returned.
50732 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
50733 ** is returned if we run out of memory.
50734 */
50735 static int lockBtree(BtShared *pBt){
50736   int rc;              /* Result code from subfunctions */
50737   MemPage *pPage1;     /* Page 1 of the database file */
50738   int nPage;           /* Number of pages in the database */
50739   int nPageFile = 0;   /* Number of pages in the database file */
50740   int nPageHeader;     /* Number of pages in the database according to hdr */
50741 
50742   assert( sqlite3_mutex_held(pBt->mutex) );
50743   assert( pBt->pPage1==0 );
50744   rc = sqlite3PagerSharedLock(pBt->pPager);
50745   if( rc!=SQLITE_OK ) return rc;
50746   rc = btreeGetPage(pBt, 1, &pPage1, 0);
50747   if( rc!=SQLITE_OK ) return rc;
50748 
50749   /* Do some checking to help insure the file we opened really is
50750   ** a valid database file.
50751   */
50752   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
50753   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
50754   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
50755     nPage = nPageFile;
50756   }
50757   if( nPage>0 ){
50758     u32 pageSize;
50759     u32 usableSize;
50760     u8 *page1 = pPage1->aData;
50761     rc = SQLITE_NOTADB;
50762     if( memcmp(page1, zMagicHeader, 16)!=0 ){
50763       goto page1_init_failed;
50764     }
50765 
50766 #ifdef SQLITE_OMIT_WAL
50767     if( page1[18]>1 ){
50768       pBt->btsFlags |= BTS_READ_ONLY;
50769     }
50770     if( page1[19]>1 ){
50771       goto page1_init_failed;
50772     }
50773 #else
50774     if( page1[18]>2 ){
50775       pBt->btsFlags |= BTS_READ_ONLY;
50776     }
50777     if( page1[19]>2 ){
50778       goto page1_init_failed;
50779     }
50780 
50781     /* If the write version is set to 2, this database should be accessed
50782     ** in WAL mode. If the log is not already open, open it now. Then
50783     ** return SQLITE_OK and return without populating BtShared.pPage1.
50784     ** The caller detects this and calls this function again. This is
50785     ** required as the version of page 1 currently in the page1 buffer
50786     ** may not be the latest version - there may be a newer one in the log
50787     ** file.
50788     */
50789     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
50790       int isOpen = 0;
50791       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
50792       if( rc!=SQLITE_OK ){
50793         goto page1_init_failed;
50794       }else if( isOpen==0 ){
50795         releasePage(pPage1);
50796         return SQLITE_OK;
50797       }
50798       rc = SQLITE_NOTADB;
50799     }
50800 #endif
50801 
50802     /* The maximum embedded fraction must be exactly 25%.  And the minimum
50803     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
50804     ** The original design allowed these amounts to vary, but as of
50805     ** version 3.6.0, we require them to be fixed.
50806     */
50807     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
50808       goto page1_init_failed;
50809     }
50810     pageSize = (page1[16]<<8) | (page1[17]<<16);
50811     if( ((pageSize-1)&pageSize)!=0
50812      || pageSize>SQLITE_MAX_PAGE_SIZE
50813      || pageSize<=256
50814     ){
50815       goto page1_init_failed;
50816     }
50817     assert( (pageSize & 7)==0 );
50818     usableSize = pageSize - page1[20];
50819     if( (u32)pageSize!=pBt->pageSize ){
50820       /* After reading the first page of the database assuming a page size
50821       ** of BtShared.pageSize, we have discovered that the page-size is
50822       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
50823       ** zero and return SQLITE_OK. The caller will call this function
50824       ** again with the correct page-size.
50825       */
50826       releasePage(pPage1);
50827       pBt->usableSize = usableSize;
50828       pBt->pageSize = pageSize;
50829       freeTempSpace(pBt);
50830       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
50831                                    pageSize-usableSize);
50832       return rc;
50833     }
50834     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
50835       rc = SQLITE_CORRUPT_BKPT;
50836       goto page1_init_failed;
50837     }
50838     if( usableSize<480 ){
50839       goto page1_init_failed;
50840     }
50841     pBt->pageSize = pageSize;
50842     pBt->usableSize = usableSize;
50843 #ifndef SQLITE_OMIT_AUTOVACUUM
50844     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
50845     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
50846 #endif
50847   }
50848 
50849   /* maxLocal is the maximum amount of payload to store locally for
50850   ** a cell.  Make sure it is small enough so that at least minFanout
50851   ** cells can will fit on one page.  We assume a 10-byte page header.
50852   ** Besides the payload, the cell must store:
50853   **     2-byte pointer to the cell
50854   **     4-byte child pointer
50855   **     9-byte nKey value
50856   **     4-byte nData value
50857   **     4-byte overflow page pointer
50858   ** So a cell consists of a 2-byte pointer, a header which is as much as
50859   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
50860   ** page pointer.
50861   */
50862   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
50863   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
50864   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
50865   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
50866   if( pBt->maxLocal>127 ){
50867     pBt->max1bytePayload = 127;
50868   }else{
50869     pBt->max1bytePayload = (u8)pBt->maxLocal;
50870   }
50871   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
50872   pBt->pPage1 = pPage1;
50873   pBt->nPage = nPage;
50874   return SQLITE_OK;
50875 
50876 page1_init_failed:
50877   releasePage(pPage1);
50878   pBt->pPage1 = 0;
50879   return rc;
50880 }
50881 
50882 /*
50883 ** If there are no outstanding cursors and we are not in the middle
50884 ** of a transaction but there is a read lock on the database, then
50885 ** this routine unrefs the first page of the database file which
50886 ** has the effect of releasing the read lock.
50887 **
50888 ** If there is a transaction in progress, this routine is a no-op.
50889 */
50890 static void unlockBtreeIfUnused(BtShared *pBt){
50891   assert( sqlite3_mutex_held(pBt->mutex) );
50892   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
50893   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
50894     assert( pBt->pPage1->aData );
50895     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
50896     assert( pBt->pPage1->aData );
50897     releasePage(pBt->pPage1);
50898     pBt->pPage1 = 0;
50899   }
50900 }
50901 
50902 /*
50903 ** If pBt points to an empty file then convert that empty file
50904 ** into a new empty database by initializing the first page of
50905 ** the database.
50906 */
50907 static int newDatabase(BtShared *pBt){
50908   MemPage *pP1;
50909   unsigned char *data;
50910   int rc;
50911 
50912   assert( sqlite3_mutex_held(pBt->mutex) );
50913   if( pBt->nPage>0 ){
50914     return SQLITE_OK;
50915   }
50916   pP1 = pBt->pPage1;
50917   assert( pP1!=0 );
50918   data = pP1->aData;
50919   rc = sqlite3PagerWrite(pP1->pDbPage);
50920   if( rc ) return rc;
50921   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
50922   assert( sizeof(zMagicHeader)==16 );
50923   data[16] = (u8)((pBt->pageSize>>8)&0xff);
50924   data[17] = (u8)((pBt->pageSize>>16)&0xff);
50925   data[18] = 1;
50926   data[19] = 1;
50927   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
50928   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
50929   data[21] = 64;
50930   data[22] = 32;
50931   data[23] = 32;
50932   memset(&data[24], 0, 100-24);
50933   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
50934   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
50935 #ifndef SQLITE_OMIT_AUTOVACUUM
50936   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50937   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50938   put4byte(&data[36 + 4*4], pBt->autoVacuum);
50939   put4byte(&data[36 + 7*4], pBt->incrVacuum);
50940 #endif
50941   pBt->nPage = 1;
50942   data[31] = 1;
50943   return SQLITE_OK;
50944 }
50945 
50946 /*
50947 ** Initialize the first page of the database file (creating a database
50948 ** consisting of a single page and no schema objects). Return SQLITE_OK
50949 ** if successful, or an SQLite error code otherwise.
50950 */
50951 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
50952   int rc;
50953   sqlite3BtreeEnter(p);
50954   p->pBt->nPage = 0;
50955   rc = newDatabase(p->pBt);
50956   sqlite3BtreeLeave(p);
50957   return rc;
50958 }
50959 
50960 /*
50961 ** Attempt to start a new transaction. A write-transaction
50962 ** is started if the second argument is nonzero, otherwise a read-
50963 ** transaction.  If the second argument is 2 or more and exclusive
50964 ** transaction is started, meaning that no other process is allowed
50965 ** to access the database.  A preexisting transaction may not be
50966 ** upgraded to exclusive by calling this routine a second time - the
50967 ** exclusivity flag only works for a new transaction.
50968 **
50969 ** A write-transaction must be started before attempting any
50970 ** changes to the database.  None of the following routines
50971 ** will work unless a transaction is started first:
50972 **
50973 **      sqlite3BtreeCreateTable()
50974 **      sqlite3BtreeCreateIndex()
50975 **      sqlite3BtreeClearTable()
50976 **      sqlite3BtreeDropTable()
50977 **      sqlite3BtreeInsert()
50978 **      sqlite3BtreeDelete()
50979 **      sqlite3BtreeUpdateMeta()
50980 **
50981 ** If an initial attempt to acquire the lock fails because of lock contention
50982 ** and the database was previously unlocked, then invoke the busy handler
50983 ** if there is one.  But if there was previously a read-lock, do not
50984 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
50985 ** returned when there is already a read-lock in order to avoid a deadlock.
50986 **
50987 ** Suppose there are two processes A and B.  A has a read lock and B has
50988 ** a reserved lock.  B tries to promote to exclusive but is blocked because
50989 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
50990 ** One or the other of the two processes must give way or there can be
50991 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
50992 ** when A already has a read lock, we encourage A to give up and let B
50993 ** proceed.
50994 */
50995 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
50996   sqlite3 *pBlock = 0;
50997   BtShared *pBt = p->pBt;
50998   int rc = SQLITE_OK;
50999 
51000   sqlite3BtreeEnter(p);
51001   btreeIntegrity(p);
51002 
51003   /* If the btree is already in a write-transaction, or it
51004   ** is already in a read-transaction and a read-transaction
51005   ** is requested, this is a no-op.
51006   */
51007   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
51008     goto trans_begun;
51009   }
51010   assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
51011 
51012   /* Write transactions are not possible on a read-only database */
51013   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
51014     rc = SQLITE_READONLY;
51015     goto trans_begun;
51016   }
51017 
51018 #ifndef SQLITE_OMIT_SHARED_CACHE
51019   /* If another database handle has already opened a write transaction
51020   ** on this shared-btree structure and a second write transaction is
51021   ** requested, return SQLITE_LOCKED.
51022   */
51023   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
51024    || (pBt->btsFlags & BTS_PENDING)!=0
51025   ){
51026     pBlock = pBt->pWriter->db;
51027   }else if( wrflag>1 ){
51028     BtLock *pIter;
51029     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51030       if( pIter->pBtree!=p ){
51031         pBlock = pIter->pBtree->db;
51032         break;
51033       }
51034     }
51035   }
51036   if( pBlock ){
51037     sqlite3ConnectionBlocked(p->db, pBlock);
51038     rc = SQLITE_LOCKED_SHAREDCACHE;
51039     goto trans_begun;
51040   }
51041 #endif
51042 
51043   /* Any read-only or read-write transaction implies a read-lock on
51044   ** page 1. So if some other shared-cache client already has a write-lock
51045   ** on page 1, the transaction cannot be opened. */
51046   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51047   if( SQLITE_OK!=rc ) goto trans_begun;
51048 
51049   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
51050   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
51051   do {
51052     /* Call lockBtree() until either pBt->pPage1 is populated or
51053     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
51054     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
51055     ** reading page 1 it discovers that the page-size of the database
51056     ** file is not pBt->pageSize. In this case lockBtree() will update
51057     ** pBt->pageSize to the page-size of the file on disk.
51058     */
51059     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
51060 
51061     if( rc==SQLITE_OK && wrflag ){
51062       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
51063         rc = SQLITE_READONLY;
51064       }else{
51065         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
51066         if( rc==SQLITE_OK ){
51067           rc = newDatabase(pBt);
51068         }
51069       }
51070     }
51071 
51072     if( rc!=SQLITE_OK ){
51073       unlockBtreeIfUnused(pBt);
51074     }
51075   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
51076           btreeInvokeBusyHandler(pBt) );
51077 
51078   if( rc==SQLITE_OK ){
51079     if( p->inTrans==TRANS_NONE ){
51080       pBt->nTransaction++;
51081 #ifndef SQLITE_OMIT_SHARED_CACHE
51082       if( p->sharable ){
51083         assert( p->lock.pBtree==p && p->lock.iTable==1 );
51084         p->lock.eLock = READ_LOCK;
51085         p->lock.pNext = pBt->pLock;
51086         pBt->pLock = &p->lock;
51087       }
51088 #endif
51089     }
51090     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
51091     if( p->inTrans>pBt->inTransaction ){
51092       pBt->inTransaction = p->inTrans;
51093     }
51094     if( wrflag ){
51095       MemPage *pPage1 = pBt->pPage1;
51096 #ifndef SQLITE_OMIT_SHARED_CACHE
51097       assert( !pBt->pWriter );
51098       pBt->pWriter = p;
51099       pBt->btsFlags &= ~BTS_EXCLUSIVE;
51100       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
51101 #endif
51102 
51103       /* If the db-size header field is incorrect (as it may be if an old
51104       ** client has been writing the database file), update it now. Doing
51105       ** this sooner rather than later means the database size can safely
51106       ** re-read the database size from page 1 if a savepoint or transaction
51107       ** rollback occurs within the transaction.
51108       */
51109       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
51110         rc = sqlite3PagerWrite(pPage1->pDbPage);
51111         if( rc==SQLITE_OK ){
51112           put4byte(&pPage1->aData[28], pBt->nPage);
51113         }
51114       }
51115     }
51116   }
51117 
51118 
51119 trans_begun:
51120   if( rc==SQLITE_OK && wrflag ){
51121     /* This call makes sure that the pager has the correct number of
51122     ** open savepoints. If the second parameter is greater than 0 and
51123     ** the sub-journal is not already open, then it will be opened here.
51124     */
51125     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
51126   }
51127 
51128   btreeIntegrity(p);
51129   sqlite3BtreeLeave(p);
51130   return rc;
51131 }
51132 
51133 #ifndef SQLITE_OMIT_AUTOVACUUM
51134 
51135 /*
51136 ** Set the pointer-map entries for all children of page pPage. Also, if
51137 ** pPage contains cells that point to overflow pages, set the pointer
51138 ** map entries for the overflow pages as well.
51139 */
51140 static int setChildPtrmaps(MemPage *pPage){
51141   int i;                             /* Counter variable */
51142   int nCell;                         /* Number of cells in page pPage */
51143   int rc;                            /* Return code */
51144   BtShared *pBt = pPage->pBt;
51145   u8 isInitOrig = pPage->isInit;
51146   Pgno pgno = pPage->pgno;
51147 
51148   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51149   rc = btreeInitPage(pPage);
51150   if( rc!=SQLITE_OK ){
51151     goto set_child_ptrmaps_out;
51152   }
51153   nCell = pPage->nCell;
51154 
51155   for(i=0; i<nCell; i++){
51156     u8 *pCell = findCell(pPage, i);
51157 
51158     ptrmapPutOvflPtr(pPage, pCell, &rc);
51159 
51160     if( !pPage->leaf ){
51161       Pgno childPgno = get4byte(pCell);
51162       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
51163     }
51164   }
51165 
51166   if( !pPage->leaf ){
51167     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51168     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
51169   }
51170 
51171 set_child_ptrmaps_out:
51172   pPage->isInit = isInitOrig;
51173   return rc;
51174 }
51175 
51176 /*
51177 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
51178 ** that it points to iTo. Parameter eType describes the type of pointer to
51179 ** be modified, as  follows:
51180 **
51181 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
51182 **                   page of pPage.
51183 **
51184 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
51185 **                   page pointed to by one of the cells on pPage.
51186 **
51187 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
51188 **                   overflow page in the list.
51189 */
51190 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
51191   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51192   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51193   if( eType==PTRMAP_OVERFLOW2 ){
51194     /* The pointer is always the first 4 bytes of the page in this case.  */
51195     if( get4byte(pPage->aData)!=iFrom ){
51196       return SQLITE_CORRUPT_BKPT;
51197     }
51198     put4byte(pPage->aData, iTo);
51199   }else{
51200     u8 isInitOrig = pPage->isInit;
51201     int i;
51202     int nCell;
51203 
51204     btreeInitPage(pPage);
51205     nCell = pPage->nCell;
51206 
51207     for(i=0; i<nCell; i++){
51208       u8 *pCell = findCell(pPage, i);
51209       if( eType==PTRMAP_OVERFLOW1 ){
51210         CellInfo info;
51211         btreeParseCellPtr(pPage, pCell, &info);
51212         if( info.iOverflow
51213          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
51214          && iFrom==get4byte(&pCell[info.iOverflow])
51215         ){
51216           put4byte(&pCell[info.iOverflow], iTo);
51217           break;
51218         }
51219       }else{
51220         if( get4byte(pCell)==iFrom ){
51221           put4byte(pCell, iTo);
51222           break;
51223         }
51224       }
51225     }
51226 
51227     if( i==nCell ){
51228       if( eType!=PTRMAP_BTREE ||
51229           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
51230         return SQLITE_CORRUPT_BKPT;
51231       }
51232       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
51233     }
51234 
51235     pPage->isInit = isInitOrig;
51236   }
51237   return SQLITE_OK;
51238 }
51239 
51240 
51241 /*
51242 ** Move the open database page pDbPage to location iFreePage in the
51243 ** database. The pDbPage reference remains valid.
51244 **
51245 ** The isCommit flag indicates that there is no need to remember that
51246 ** the journal needs to be sync()ed before database page pDbPage->pgno
51247 ** can be written to. The caller has already promised not to write to that
51248 ** page.
51249 */
51250 static int relocatePage(
51251   BtShared *pBt,           /* Btree */
51252   MemPage *pDbPage,        /* Open page to move */
51253   u8 eType,                /* Pointer map 'type' entry for pDbPage */
51254   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
51255   Pgno iFreePage,          /* The location to move pDbPage to */
51256   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
51257 ){
51258   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
51259   Pgno iDbPage = pDbPage->pgno;
51260   Pager *pPager = pBt->pPager;
51261   int rc;
51262 
51263   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
51264       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
51265   assert( sqlite3_mutex_held(pBt->mutex) );
51266   assert( pDbPage->pBt==pBt );
51267 
51268   /* Move page iDbPage from its current location to page number iFreePage */
51269   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
51270       iDbPage, iFreePage, iPtrPage, eType));
51271   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
51272   if( rc!=SQLITE_OK ){
51273     return rc;
51274   }
51275   pDbPage->pgno = iFreePage;
51276 
51277   /* If pDbPage was a btree-page, then it may have child pages and/or cells
51278   ** that point to overflow pages. The pointer map entries for all these
51279   ** pages need to be changed.
51280   **
51281   ** If pDbPage is an overflow page, then the first 4 bytes may store a
51282   ** pointer to a subsequent overflow page. If this is the case, then
51283   ** the pointer map needs to be updated for the subsequent overflow page.
51284   */
51285   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
51286     rc = setChildPtrmaps(pDbPage);
51287     if( rc!=SQLITE_OK ){
51288       return rc;
51289     }
51290   }else{
51291     Pgno nextOvfl = get4byte(pDbPage->aData);
51292     if( nextOvfl!=0 ){
51293       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
51294       if( rc!=SQLITE_OK ){
51295         return rc;
51296       }
51297     }
51298   }
51299 
51300   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
51301   ** that it points at iFreePage. Also fix the pointer map entry for
51302   ** iPtrPage.
51303   */
51304   if( eType!=PTRMAP_ROOTPAGE ){
51305     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
51306     if( rc!=SQLITE_OK ){
51307       return rc;
51308     }
51309     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
51310     if( rc!=SQLITE_OK ){
51311       releasePage(pPtrPage);
51312       return rc;
51313     }
51314     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
51315     releasePage(pPtrPage);
51316     if( rc==SQLITE_OK ){
51317       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
51318     }
51319   }
51320   return rc;
51321 }
51322 
51323 /* Forward declaration required by incrVacuumStep(). */
51324 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
51325 
51326 /*
51327 ** Perform a single step of an incremental-vacuum. If successful, return
51328 ** SQLITE_OK. If there is no work to do (and therefore no point in
51329 ** calling this function again), return SQLITE_DONE. Or, if an error
51330 ** occurs, return some other error code.
51331 **
51332 ** More specificly, this function attempts to re-organize the database so
51333 ** that the last page of the file currently in use is no longer in use.
51334 **
51335 ** Parameter nFin is the number of pages that this database would contain
51336 ** were this function called until it returns SQLITE_DONE.
51337 **
51338 ** If the bCommit parameter is non-zero, this function assumes that the
51339 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
51340 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
51341 ** operation, or false for an incremental vacuum.
51342 */
51343 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
51344   Pgno nFreeList;           /* Number of pages still on the free-list */
51345   int rc;
51346 
51347   assert( sqlite3_mutex_held(pBt->mutex) );
51348   assert( iLastPg>nFin );
51349 
51350   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
51351     u8 eType;
51352     Pgno iPtrPage;
51353 
51354     nFreeList = get4byte(&pBt->pPage1->aData[36]);
51355     if( nFreeList==0 ){
51356       return SQLITE_DONE;
51357     }
51358 
51359     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
51360     if( rc!=SQLITE_OK ){
51361       return rc;
51362     }
51363     if( eType==PTRMAP_ROOTPAGE ){
51364       return SQLITE_CORRUPT_BKPT;
51365     }
51366 
51367     if( eType==PTRMAP_FREEPAGE ){
51368       if( bCommit==0 ){
51369         /* Remove the page from the files free-list. This is not required
51370         ** if bCommit is non-zero. In that case, the free-list will be
51371         ** truncated to zero after this function returns, so it doesn't
51372         ** matter if it still contains some garbage entries.
51373         */
51374         Pgno iFreePg;
51375         MemPage *pFreePg;
51376         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
51377         if( rc!=SQLITE_OK ){
51378           return rc;
51379         }
51380         assert( iFreePg==iLastPg );
51381         releasePage(pFreePg);
51382       }
51383     } else {
51384       Pgno iFreePg;             /* Index of free page to move pLastPg to */
51385       MemPage *pLastPg;
51386       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
51387       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
51388 
51389       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
51390       if( rc!=SQLITE_OK ){
51391         return rc;
51392       }
51393 
51394       /* If bCommit is zero, this loop runs exactly once and page pLastPg
51395       ** is swapped with the first free page pulled off the free list.
51396       **
51397       ** On the other hand, if bCommit is greater than zero, then keep
51398       ** looping until a free-page located within the first nFin pages
51399       ** of the file is found.
51400       */
51401       if( bCommit==0 ){
51402         eMode = BTALLOC_LE;
51403         iNear = nFin;
51404       }
51405       do {
51406         MemPage *pFreePg;
51407         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
51408         if( rc!=SQLITE_OK ){
51409           releasePage(pLastPg);
51410           return rc;
51411         }
51412         releasePage(pFreePg);
51413       }while( bCommit && iFreePg>nFin );
51414       assert( iFreePg<iLastPg );
51415 
51416       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
51417       releasePage(pLastPg);
51418       if( rc!=SQLITE_OK ){
51419         return rc;
51420       }
51421     }
51422   }
51423 
51424   if( bCommit==0 ){
51425     do {
51426       iLastPg--;
51427     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
51428     pBt->bDoTruncate = 1;
51429     pBt->nPage = iLastPg;
51430   }
51431   return SQLITE_OK;
51432 }
51433 
51434 /*
51435 ** The database opened by the first argument is an auto-vacuum database
51436 ** nOrig pages in size containing nFree free pages. Return the expected
51437 ** size of the database in pages following an auto-vacuum operation.
51438 */
51439 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
51440   int nEntry;                     /* Number of entries on one ptrmap page */
51441   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
51442   Pgno nFin;                      /* Return value */
51443 
51444   nEntry = pBt->usableSize/5;
51445   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
51446   nFin = nOrig - nFree - nPtrmap;
51447   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
51448     nFin--;
51449   }
51450   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
51451     nFin--;
51452   }
51453 
51454   return nFin;
51455 }
51456 
51457 /*
51458 ** A write-transaction must be opened before calling this function.
51459 ** It performs a single unit of work towards an incremental vacuum.
51460 **
51461 ** If the incremental vacuum is finished after this function has run,
51462 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
51463 ** SQLITE_OK is returned. Otherwise an SQLite error code.
51464 */
51465 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
51466   int rc;
51467   BtShared *pBt = p->pBt;
51468 
51469   sqlite3BtreeEnter(p);
51470   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
51471   if( !pBt->autoVacuum ){
51472     rc = SQLITE_DONE;
51473   }else{
51474     Pgno nOrig = btreePagecount(pBt);
51475     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
51476     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
51477 
51478     if( nOrig<nFin ){
51479       rc = SQLITE_CORRUPT_BKPT;
51480     }else if( nFree>0 ){
51481       invalidateAllOverflowCache(pBt);
51482       rc = incrVacuumStep(pBt, nFin, nOrig, 0);
51483       if( rc==SQLITE_OK ){
51484         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51485         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
51486       }
51487     }else{
51488       rc = SQLITE_DONE;
51489     }
51490   }
51491   sqlite3BtreeLeave(p);
51492   return rc;
51493 }
51494 
51495 /*
51496 ** This routine is called prior to sqlite3PagerCommit when a transaction
51497 ** is commited for an auto-vacuum database.
51498 **
51499 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
51500 ** the database file should be truncated to during the commit process.
51501 ** i.e. the database has been reorganized so that only the first *pnTrunc
51502 ** pages are in use.
51503 */
51504 static int autoVacuumCommit(BtShared *pBt){
51505   int rc = SQLITE_OK;
51506   Pager *pPager = pBt->pPager;
51507   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
51508 
51509   assert( sqlite3_mutex_held(pBt->mutex) );
51510   invalidateAllOverflowCache(pBt);
51511   assert(pBt->autoVacuum);
51512   if( !pBt->incrVacuum ){
51513     Pgno nFin;         /* Number of pages in database after autovacuuming */
51514     Pgno nFree;        /* Number of pages on the freelist initially */
51515     Pgno iFree;        /* The next page to be freed */
51516     Pgno nOrig;        /* Database size before freeing */
51517 
51518     nOrig = btreePagecount(pBt);
51519     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
51520       /* It is not possible to create a database for which the final page
51521       ** is either a pointer-map page or the pending-byte page. If one
51522       ** is encountered, this indicates corruption.
51523       */
51524       return SQLITE_CORRUPT_BKPT;
51525     }
51526 
51527     nFree = get4byte(&pBt->pPage1->aData[36]);
51528     nFin = finalDbSize(pBt, nOrig, nFree);
51529     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
51530 
51531     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
51532       rc = incrVacuumStep(pBt, nFin, iFree, 1);
51533     }
51534     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
51535       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51536       put4byte(&pBt->pPage1->aData[32], 0);
51537       put4byte(&pBt->pPage1->aData[36], 0);
51538       put4byte(&pBt->pPage1->aData[28], nFin);
51539       pBt->bDoTruncate = 1;
51540       pBt->nPage = nFin;
51541     }
51542     if( rc!=SQLITE_OK ){
51543       sqlite3PagerRollback(pPager);
51544     }
51545   }
51546 
51547   assert( nRef==sqlite3PagerRefcount(pPager) );
51548   return rc;
51549 }
51550 
51551 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
51552 # define setChildPtrmaps(x) SQLITE_OK
51553 #endif
51554 
51555 /*
51556 ** This routine does the first phase of a two-phase commit.  This routine
51557 ** causes a rollback journal to be created (if it does not already exist)
51558 ** and populated with enough information so that if a power loss occurs
51559 ** the database can be restored to its original state by playing back
51560 ** the journal.  Then the contents of the journal are flushed out to
51561 ** the disk.  After the journal is safely on oxide, the changes to the
51562 ** database are written into the database file and flushed to oxide.
51563 ** At the end of this call, the rollback journal still exists on the
51564 ** disk and we are still holding all locks, so the transaction has not
51565 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
51566 ** commit process.
51567 **
51568 ** This call is a no-op if no write-transaction is currently active on pBt.
51569 **
51570 ** Otherwise, sync the database file for the btree pBt. zMaster points to
51571 ** the name of a master journal file that should be written into the
51572 ** individual journal file, or is NULL, indicating no master journal file
51573 ** (single database transaction).
51574 **
51575 ** When this is called, the master journal should already have been
51576 ** created, populated with this journal pointer and synced to disk.
51577 **
51578 ** Once this is routine has returned, the only thing required to commit
51579 ** the write-transaction for this database file is to delete the journal.
51580 */
51581 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
51582   int rc = SQLITE_OK;
51583   if( p->inTrans==TRANS_WRITE ){
51584     BtShared *pBt = p->pBt;
51585     sqlite3BtreeEnter(p);
51586 #ifndef SQLITE_OMIT_AUTOVACUUM
51587     if( pBt->autoVacuum ){
51588       rc = autoVacuumCommit(pBt);
51589       if( rc!=SQLITE_OK ){
51590         sqlite3BtreeLeave(p);
51591         return rc;
51592       }
51593     }
51594     if( pBt->bDoTruncate ){
51595       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
51596     }
51597 #endif
51598     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
51599     sqlite3BtreeLeave(p);
51600   }
51601   return rc;
51602 }
51603 
51604 /*
51605 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
51606 ** at the conclusion of a transaction.
51607 */
51608 static void btreeEndTransaction(Btree *p){
51609   BtShared *pBt = p->pBt;
51610   assert( sqlite3BtreeHoldsMutex(p) );
51611 
51612 #ifndef SQLITE_OMIT_AUTOVACUUM
51613   pBt->bDoTruncate = 0;
51614 #endif
51615   btreeClearHasContent(pBt);
51616   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
51617     /* If there are other active statements that belong to this database
51618     ** handle, downgrade to a read-only transaction. The other statements
51619     ** may still be reading from the database.  */
51620     downgradeAllSharedCacheTableLocks(p);
51621     p->inTrans = TRANS_READ;
51622   }else{
51623     /* If the handle had any kind of transaction open, decrement the
51624     ** transaction count of the shared btree. If the transaction count
51625     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
51626     ** call below will unlock the pager.  */
51627     if( p->inTrans!=TRANS_NONE ){
51628       clearAllSharedCacheTableLocks(p);
51629       pBt->nTransaction--;
51630       if( 0==pBt->nTransaction ){
51631         pBt->inTransaction = TRANS_NONE;
51632       }
51633     }
51634 
51635     /* Set the current transaction state to TRANS_NONE and unlock the
51636     ** pager if this call closed the only read or write transaction.  */
51637     p->inTrans = TRANS_NONE;
51638     unlockBtreeIfUnused(pBt);
51639   }
51640 
51641   btreeIntegrity(p);
51642 }
51643 
51644 /*
51645 ** Commit the transaction currently in progress.
51646 **
51647 ** This routine implements the second phase of a 2-phase commit.  The
51648 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
51649 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
51650 ** routine did all the work of writing information out to disk and flushing the
51651 ** contents so that they are written onto the disk platter.  All this
51652 ** routine has to do is delete or truncate or zero the header in the
51653 ** the rollback journal (which causes the transaction to commit) and
51654 ** drop locks.
51655 **
51656 ** Normally, if an error occurs while the pager layer is attempting to
51657 ** finalize the underlying journal file, this function returns an error and
51658 ** the upper layer will attempt a rollback. However, if the second argument
51659 ** is non-zero then this b-tree transaction is part of a multi-file
51660 ** transaction. In this case, the transaction has already been committed
51661 ** (by deleting a master journal file) and the caller will ignore this
51662 ** functions return code. So, even if an error occurs in the pager layer,
51663 ** reset the b-tree objects internal state to indicate that the write
51664 ** transaction has been closed. This is quite safe, as the pager will have
51665 ** transitioned to the error state.
51666 **
51667 ** This will release the write lock on the database file.  If there
51668 ** are no active cursors, it also releases the read lock.
51669 */
51670 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
51671 
51672   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
51673   sqlite3BtreeEnter(p);
51674   btreeIntegrity(p);
51675 
51676   /* If the handle has a write-transaction open, commit the shared-btrees
51677   ** transaction and set the shared state to TRANS_READ.
51678   */
51679   if( p->inTrans==TRANS_WRITE ){
51680     int rc;
51681     BtShared *pBt = p->pBt;
51682     assert( pBt->inTransaction==TRANS_WRITE );
51683     assert( pBt->nTransaction>0 );
51684     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
51685     if( rc!=SQLITE_OK && bCleanup==0 ){
51686       sqlite3BtreeLeave(p);
51687       return rc;
51688     }
51689     pBt->inTransaction = TRANS_READ;
51690   }
51691 
51692   btreeEndTransaction(p);
51693   sqlite3BtreeLeave(p);
51694   return SQLITE_OK;
51695 }
51696 
51697 /*
51698 ** Do both phases of a commit.
51699 */
51700 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
51701   int rc;
51702   sqlite3BtreeEnter(p);
51703   rc = sqlite3BtreeCommitPhaseOne(p, 0);
51704   if( rc==SQLITE_OK ){
51705     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
51706   }
51707   sqlite3BtreeLeave(p);
51708   return rc;
51709 }
51710 
51711 #ifndef NDEBUG
51712 /*
51713 ** Return the number of write-cursors open on this handle. This is for use
51714 ** in assert() expressions, so it is only compiled if NDEBUG is not
51715 ** defined.
51716 **
51717 ** For the purposes of this routine, a write-cursor is any cursor that
51718 ** is capable of writing to the databse.  That means the cursor was
51719 ** originally opened for writing and the cursor has not be disabled
51720 ** by having its state changed to CURSOR_FAULT.
51721 */
51722 static int countWriteCursors(BtShared *pBt){
51723   BtCursor *pCur;
51724   int r = 0;
51725   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
51726     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
51727   }
51728   return r;
51729 }
51730 #endif
51731 
51732 /*
51733 ** This routine sets the state to CURSOR_FAULT and the error
51734 ** code to errCode for every cursor on BtShared that pBtree
51735 ** references.
51736 **
51737 ** Every cursor is tripped, including cursors that belong
51738 ** to other database connections that happen to be sharing
51739 ** the cache with pBtree.
51740 **
51741 ** This routine gets called when a rollback occurs.
51742 ** All cursors using the same cache must be tripped
51743 ** to prevent them from trying to use the btree after
51744 ** the rollback.  The rollback may have deleted tables
51745 ** or moved root pages, so it is not sufficient to
51746 ** save the state of the cursor.  The cursor must be
51747 ** invalidated.
51748 */
51749 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
51750   BtCursor *p;
51751   if( pBtree==0 ) return;
51752   sqlite3BtreeEnter(pBtree);
51753   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51754     int i;
51755     sqlite3BtreeClearCursor(p);
51756     p->eState = CURSOR_FAULT;
51757     p->skipNext = errCode;
51758     for(i=0; i<=p->iPage; i++){
51759       releasePage(p->apPage[i]);
51760       p->apPage[i] = 0;
51761     }
51762   }
51763   sqlite3BtreeLeave(pBtree);
51764 }
51765 
51766 /*
51767 ** Rollback the transaction in progress.  All cursors will be
51768 ** invalided by this operation.  Any attempt to use a cursor
51769 ** that was open at the beginning of this operation will result
51770 ** in an error.
51771 **
51772 ** This will release the write lock on the database file.  If there
51773 ** are no active cursors, it also releases the read lock.
51774 */
51775 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
51776   int rc;
51777   BtShared *pBt = p->pBt;
51778   MemPage *pPage1;
51779 
51780   sqlite3BtreeEnter(p);
51781   if( tripCode==SQLITE_OK ){
51782     rc = tripCode = saveAllCursors(pBt, 0, 0);
51783   }else{
51784     rc = SQLITE_OK;
51785   }
51786   if( tripCode ){
51787     sqlite3BtreeTripAllCursors(p, tripCode);
51788   }
51789   btreeIntegrity(p);
51790 
51791   if( p->inTrans==TRANS_WRITE ){
51792     int rc2;
51793 
51794     assert( TRANS_WRITE==pBt->inTransaction );
51795     rc2 = sqlite3PagerRollback(pBt->pPager);
51796     if( rc2!=SQLITE_OK ){
51797       rc = rc2;
51798     }
51799 
51800     /* The rollback may have destroyed the pPage1->aData value.  So
51801     ** call btreeGetPage() on page 1 again to make
51802     ** sure pPage1->aData is set correctly. */
51803     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
51804       int nPage = get4byte(28+(u8*)pPage1->aData);
51805       testcase( nPage==0 );
51806       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
51807       testcase( pBt->nPage!=nPage );
51808       pBt->nPage = nPage;
51809       releasePage(pPage1);
51810     }
51811     assert( countWriteCursors(pBt)==0 );
51812     pBt->inTransaction = TRANS_READ;
51813   }
51814 
51815   btreeEndTransaction(p);
51816   sqlite3BtreeLeave(p);
51817   return rc;
51818 }
51819 
51820 /*
51821 ** Start a statement subtransaction. The subtransaction can can be rolled
51822 ** back independently of the main transaction. You must start a transaction
51823 ** before starting a subtransaction. The subtransaction is ended automatically
51824 ** if the main transaction commits or rolls back.
51825 **
51826 ** Statement subtransactions are used around individual SQL statements
51827 ** that are contained within a BEGIN...COMMIT block.  If a constraint
51828 ** error occurs within the statement, the effect of that one statement
51829 ** can be rolled back without having to rollback the entire transaction.
51830 **
51831 ** A statement sub-transaction is implemented as an anonymous savepoint. The
51832 ** value passed as the second parameter is the total number of savepoints,
51833 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
51834 ** are no active savepoints and no other statement-transactions open,
51835 ** iStatement is 1. This anonymous savepoint can be released or rolled back
51836 ** using the sqlite3BtreeSavepoint() function.
51837 */
51838 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
51839   int rc;
51840   BtShared *pBt = p->pBt;
51841   sqlite3BtreeEnter(p);
51842   assert( p->inTrans==TRANS_WRITE );
51843   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
51844   assert( iStatement>0 );
51845   assert( iStatement>p->db->nSavepoint );
51846   assert( pBt->inTransaction==TRANS_WRITE );
51847   /* At the pager level, a statement transaction is a savepoint with
51848   ** an index greater than all savepoints created explicitly using
51849   ** SQL statements. It is illegal to open, release or rollback any
51850   ** such savepoints while the statement transaction savepoint is active.
51851   */
51852   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
51853   sqlite3BtreeLeave(p);
51854   return rc;
51855 }
51856 
51857 /*
51858 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
51859 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
51860 ** savepoint identified by parameter iSavepoint, depending on the value
51861 ** of op.
51862 **
51863 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
51864 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
51865 ** contents of the entire transaction are rolled back. This is different
51866 ** from a normal transaction rollback, as no locks are released and the
51867 ** transaction remains open.
51868 */
51869 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
51870   int rc = SQLITE_OK;
51871   if( p && p->inTrans==TRANS_WRITE ){
51872     BtShared *pBt = p->pBt;
51873     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
51874     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
51875     sqlite3BtreeEnter(p);
51876     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
51877     if( rc==SQLITE_OK ){
51878       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
51879         pBt->nPage = 0;
51880       }
51881       rc = newDatabase(pBt);
51882       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
51883 
51884       /* The database size was written into the offset 28 of the header
51885       ** when the transaction started, so we know that the value at offset
51886       ** 28 is nonzero. */
51887       assert( pBt->nPage>0 );
51888     }
51889     sqlite3BtreeLeave(p);
51890   }
51891   return rc;
51892 }
51893 
51894 /*
51895 ** Create a new cursor for the BTree whose root is on the page
51896 ** iTable. If a read-only cursor is requested, it is assumed that
51897 ** the caller already has at least a read-only transaction open
51898 ** on the database already. If a write-cursor is requested, then
51899 ** the caller is assumed to have an open write transaction.
51900 **
51901 ** If wrFlag==0, then the cursor can only be used for reading.
51902 ** If wrFlag==1, then the cursor can be used for reading or for
51903 ** writing if other conditions for writing are also met.  These
51904 ** are the conditions that must be met in order for writing to
51905 ** be allowed:
51906 **
51907 ** 1:  The cursor must have been opened with wrFlag==1
51908 **
51909 ** 2:  Other database connections that share the same pager cache
51910 **     but which are not in the READ_UNCOMMITTED state may not have
51911 **     cursors open with wrFlag==0 on the same table.  Otherwise
51912 **     the changes made by this write cursor would be visible to
51913 **     the read cursors in the other database connection.
51914 **
51915 ** 3:  The database must be writable (not on read-only media)
51916 **
51917 ** 4:  There must be an active transaction.
51918 **
51919 ** No checking is done to make sure that page iTable really is the
51920 ** root page of a b-tree.  If it is not, then the cursor acquired
51921 ** will not work correctly.
51922 **
51923 ** It is assumed that the sqlite3BtreeCursorZero() has been called
51924 ** on pCur to initialize the memory space prior to invoking this routine.
51925 */
51926 static int btreeCursor(
51927   Btree *p,                              /* The btree */
51928   int iTable,                            /* Root page of table to open */
51929   int wrFlag,                            /* 1 to write. 0 read-only */
51930   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
51931   BtCursor *pCur                         /* Space for new cursor */
51932 ){
51933   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
51934 
51935   assert( sqlite3BtreeHoldsMutex(p) );
51936   assert( wrFlag==0 || wrFlag==1 );
51937 
51938   /* The following assert statements verify that if this is a sharable
51939   ** b-tree database, the connection is holding the required table locks,
51940   ** and that no other connection has any open cursor that conflicts with
51941   ** this lock.  */
51942   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
51943   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
51944 
51945   /* Assert that the caller has opened the required transaction. */
51946   assert( p->inTrans>TRANS_NONE );
51947   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
51948   assert( pBt->pPage1 && pBt->pPage1->aData );
51949 
51950   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
51951     return SQLITE_READONLY;
51952   }
51953   if( iTable==1 && btreePagecount(pBt)==0 ){
51954     assert( wrFlag==0 );
51955     iTable = 0;
51956   }
51957 
51958   /* Now that no other errors can occur, finish filling in the BtCursor
51959   ** variables and link the cursor into the BtShared list.  */
51960   pCur->pgnoRoot = (Pgno)iTable;
51961   pCur->iPage = -1;
51962   pCur->pKeyInfo = pKeyInfo;
51963   pCur->pBtree = p;
51964   pCur->pBt = pBt;
51965   pCur->wrFlag = (u8)wrFlag;
51966   pCur->pNext = pBt->pCursor;
51967   if( pCur->pNext ){
51968     pCur->pNext->pPrev = pCur;
51969   }
51970   pBt->pCursor = pCur;
51971   pCur->eState = CURSOR_INVALID;
51972   pCur->cachedRowid = 0;
51973   return SQLITE_OK;
51974 }
51975 SQLITE_PRIVATE int sqlite3BtreeCursor(
51976   Btree *p,                                   /* The btree */
51977   int iTable,                                 /* Root page of table to open */
51978   int wrFlag,                                 /* 1 to write. 0 read-only */
51979   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
51980   BtCursor *pCur                              /* Write new cursor here */
51981 ){
51982   int rc;
51983   sqlite3BtreeEnter(p);
51984   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51985   sqlite3BtreeLeave(p);
51986   return rc;
51987 }
51988 
51989 /*
51990 ** Return the size of a BtCursor object in bytes.
51991 **
51992 ** This interfaces is needed so that users of cursors can preallocate
51993 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
51994 ** to users so they cannot do the sizeof() themselves - they must call
51995 ** this routine.
51996 */
51997 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
51998   return ROUND8(sizeof(BtCursor));
51999 }
52000 
52001 /*
52002 ** Initialize memory that will be converted into a BtCursor object.
52003 **
52004 ** The simple approach here would be to memset() the entire object
52005 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
52006 ** do not need to be zeroed and they are large, so we can save a lot
52007 ** of run-time by skipping the initialization of those elements.
52008 */
52009 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
52010   memset(p, 0, offsetof(BtCursor, iPage));
52011 }
52012 
52013 /*
52014 ** Set the cached rowid value of every cursor in the same database file
52015 ** as pCur and having the same root page number as pCur.  The value is
52016 ** set to iRowid.
52017 **
52018 ** Only positive rowid values are considered valid for this cache.
52019 ** The cache is initialized to zero, indicating an invalid cache.
52020 ** A btree will work fine with zero or negative rowids.  We just cannot
52021 ** cache zero or negative rowids, which means tables that use zero or
52022 ** negative rowids might run a little slower.  But in practice, zero
52023 ** or negative rowids are very uncommon so this should not be a problem.
52024 */
52025 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
52026   BtCursor *p;
52027   for(p=pCur->pBt->pCursor; p; p=p->pNext){
52028     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
52029   }
52030   assert( pCur->cachedRowid==iRowid );
52031 }
52032 
52033 /*
52034 ** Return the cached rowid for the given cursor.  A negative or zero
52035 ** return value indicates that the rowid cache is invalid and should be
52036 ** ignored.  If the rowid cache has never before been set, then a
52037 ** zero is returned.
52038 */
52039 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
52040   return pCur->cachedRowid;
52041 }
52042 
52043 /*
52044 ** Close a cursor.  The read lock on the database file is released
52045 ** when the last cursor is closed.
52046 */
52047 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
52048   Btree *pBtree = pCur->pBtree;
52049   if( pBtree ){
52050     int i;
52051     BtShared *pBt = pCur->pBt;
52052     sqlite3BtreeEnter(pBtree);
52053     sqlite3BtreeClearCursor(pCur);
52054     if( pCur->pPrev ){
52055       pCur->pPrev->pNext = pCur->pNext;
52056     }else{
52057       pBt->pCursor = pCur->pNext;
52058     }
52059     if( pCur->pNext ){
52060       pCur->pNext->pPrev = pCur->pPrev;
52061     }
52062     for(i=0; i<=pCur->iPage; i++){
52063       releasePage(pCur->apPage[i]);
52064     }
52065     unlockBtreeIfUnused(pBt);
52066     invalidateOverflowCache(pCur);
52067     /* sqlite3_free(pCur); */
52068     sqlite3BtreeLeave(pBtree);
52069   }
52070   return SQLITE_OK;
52071 }
52072 
52073 /*
52074 ** Make sure the BtCursor* given in the argument has a valid
52075 ** BtCursor.info structure.  If it is not already valid, call
52076 ** btreeParseCell() to fill it in.
52077 **
52078 ** BtCursor.info is a cache of the information in the current cell.
52079 ** Using this cache reduces the number of calls to btreeParseCell().
52080 **
52081 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
52082 ** compiler to crash when getCellInfo() is implemented as a macro.
52083 ** But there is a measureable speed advantage to using the macro on gcc
52084 ** (when less compiler optimizations like -Os or -O0 are used and the
52085 ** compiler is not doing agressive inlining.)  So we use a real function
52086 ** for MSVC and a macro for everything else.  Ticket #2457.
52087 */
52088 #ifndef NDEBUG
52089   static void assertCellInfo(BtCursor *pCur){
52090     CellInfo info;
52091     int iPage = pCur->iPage;
52092     memset(&info, 0, sizeof(info));
52093     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
52094     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
52095   }
52096 #else
52097   #define assertCellInfo(x)
52098 #endif
52099 #ifdef _MSC_VER
52100   /* Use a real function in MSVC to work around bugs in that compiler. */
52101   static void getCellInfo(BtCursor *pCur){
52102     if( pCur->info.nSize==0 ){
52103       int iPage = pCur->iPage;
52104       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
52105       pCur->validNKey = 1;
52106     }else{
52107       assertCellInfo(pCur);
52108     }
52109   }
52110 #else /* if not _MSC_VER */
52111   /* Use a macro in all other compilers so that the function is inlined */
52112 #define getCellInfo(pCur)                                                      \
52113   if( pCur->info.nSize==0 ){                                                   \
52114     int iPage = pCur->iPage;                                                   \
52115     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
52116     pCur->validNKey = 1;                                                       \
52117   }else{                                                                       \
52118     assertCellInfo(pCur);                                                      \
52119   }
52120 #endif /* _MSC_VER */
52121 
52122 #ifndef NDEBUG  /* The next routine used only within assert() statements */
52123 /*
52124 ** Return true if the given BtCursor is valid.  A valid cursor is one
52125 ** that is currently pointing to a row in a (non-empty) table.
52126 ** This is a verification routine is used only within assert() statements.
52127 */
52128 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
52129   return pCur && pCur->eState==CURSOR_VALID;
52130 }
52131 #endif /* NDEBUG */
52132 
52133 /*
52134 ** Set *pSize to the size of the buffer needed to hold the value of
52135 ** the key for the current entry.  If the cursor is not pointing
52136 ** to a valid entry, *pSize is set to 0.
52137 **
52138 ** For a table with the INTKEY flag set, this routine returns the key
52139 ** itself, not the number of bytes in the key.
52140 **
52141 ** The caller must position the cursor prior to invoking this routine.
52142 **
52143 ** This routine cannot fail.  It always returns SQLITE_OK.
52144 */
52145 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
52146   assert( cursorHoldsMutex(pCur) );
52147   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
52148   if( pCur->eState!=CURSOR_VALID ){
52149     *pSize = 0;
52150   }else{
52151     getCellInfo(pCur);
52152     *pSize = pCur->info.nKey;
52153   }
52154   return SQLITE_OK;
52155 }
52156 
52157 /*
52158 ** Set *pSize to the number of bytes of data in the entry the
52159 ** cursor currently points to.
52160 **
52161 ** The caller must guarantee that the cursor is pointing to a non-NULL
52162 ** valid entry.  In other words, the calling procedure must guarantee
52163 ** that the cursor has Cursor.eState==CURSOR_VALID.
52164 **
52165 ** Failure is not possible.  This function always returns SQLITE_OK.
52166 ** It might just as well be a procedure (returning void) but we continue
52167 ** to return an integer result code for historical reasons.
52168 */
52169 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
52170   assert( cursorHoldsMutex(pCur) );
52171   assert( pCur->eState==CURSOR_VALID );
52172   getCellInfo(pCur);
52173   *pSize = pCur->info.nData;
52174   return SQLITE_OK;
52175 }
52176 
52177 /*
52178 ** Given the page number of an overflow page in the database (parameter
52179 ** ovfl), this function finds the page number of the next page in the
52180 ** linked list of overflow pages. If possible, it uses the auto-vacuum
52181 ** pointer-map data instead of reading the content of page ovfl to do so.
52182 **
52183 ** If an error occurs an SQLite error code is returned. Otherwise:
52184 **
52185 ** The page number of the next overflow page in the linked list is
52186 ** written to *pPgnoNext. If page ovfl is the last page in its linked
52187 ** list, *pPgnoNext is set to zero.
52188 **
52189 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
52190 ** to page number pOvfl was obtained, then *ppPage is set to point to that
52191 ** reference. It is the responsibility of the caller to call releasePage()
52192 ** on *ppPage to free the reference. In no reference was obtained (because
52193 ** the pointer-map was used to obtain the value for *pPgnoNext), then
52194 ** *ppPage is set to zero.
52195 */
52196 static int getOverflowPage(
52197   BtShared *pBt,               /* The database file */
52198   Pgno ovfl,                   /* Current overflow page number */
52199   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
52200   Pgno *pPgnoNext              /* OUT: Next overflow page number */
52201 ){
52202   Pgno next = 0;
52203   MemPage *pPage = 0;
52204   int rc = SQLITE_OK;
52205 
52206   assert( sqlite3_mutex_held(pBt->mutex) );
52207   assert(pPgnoNext);
52208 
52209 #ifndef SQLITE_OMIT_AUTOVACUUM
52210   /* Try to find the next page in the overflow list using the
52211   ** autovacuum pointer-map pages. Guess that the next page in
52212   ** the overflow list is page number (ovfl+1). If that guess turns
52213   ** out to be wrong, fall back to loading the data of page
52214   ** number ovfl to determine the next page number.
52215   */
52216   if( pBt->autoVacuum ){
52217     Pgno pgno;
52218     Pgno iGuess = ovfl+1;
52219     u8 eType;
52220 
52221     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
52222       iGuess++;
52223     }
52224 
52225     if( iGuess<=btreePagecount(pBt) ){
52226       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
52227       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
52228         next = iGuess;
52229         rc = SQLITE_DONE;
52230       }
52231     }
52232   }
52233 #endif
52234 
52235   assert( next==0 || rc==SQLITE_DONE );
52236   if( rc==SQLITE_OK ){
52237     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
52238     assert( rc==SQLITE_OK || pPage==0 );
52239     if( rc==SQLITE_OK ){
52240       next = get4byte(pPage->aData);
52241     }
52242   }
52243 
52244   *pPgnoNext = next;
52245   if( ppPage ){
52246     *ppPage = pPage;
52247   }else{
52248     releasePage(pPage);
52249   }
52250   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
52251 }
52252 
52253 /*
52254 ** Copy data from a buffer to a page, or from a page to a buffer.
52255 **
52256 ** pPayload is a pointer to data stored on database page pDbPage.
52257 ** If argument eOp is false, then nByte bytes of data are copied
52258 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
52259 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
52260 ** of data are copied from the buffer pBuf to pPayload.
52261 **
52262 ** SQLITE_OK is returned on success, otherwise an error code.
52263 */
52264 static int copyPayload(
52265   void *pPayload,           /* Pointer to page data */
52266   void *pBuf,               /* Pointer to buffer */
52267   int nByte,                /* Number of bytes to copy */
52268   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
52269   DbPage *pDbPage           /* Page containing pPayload */
52270 ){
52271   if( eOp ){
52272     /* Copy data from buffer to page (a write operation) */
52273     int rc = sqlite3PagerWrite(pDbPage);
52274     if( rc!=SQLITE_OK ){
52275       return rc;
52276     }
52277     memcpy(pPayload, pBuf, nByte);
52278   }else{
52279     /* Copy data from page to buffer (a read operation) */
52280     memcpy(pBuf, pPayload, nByte);
52281   }
52282   return SQLITE_OK;
52283 }
52284 
52285 /*
52286 ** This function is used to read or overwrite payload information
52287 ** for the entry that the pCur cursor is pointing to. If the eOp
52288 ** parameter is 0, this is a read operation (data copied into
52289 ** buffer pBuf). If it is non-zero, a write (data copied from
52290 ** buffer pBuf).
52291 **
52292 ** A total of "amt" bytes are read or written beginning at "offset".
52293 ** Data is read to or from the buffer pBuf.
52294 **
52295 ** The content being read or written might appear on the main page
52296 ** or be scattered out on multiple overflow pages.
52297 **
52298 ** If the BtCursor.isIncrblobHandle flag is set, and the current
52299 ** cursor entry uses one or more overflow pages, this function
52300 ** allocates space for and lazily popluates the overflow page-list
52301 ** cache array (BtCursor.aOverflow). Subsequent calls use this
52302 ** cache to make seeking to the supplied offset more efficient.
52303 **
52304 ** Once an overflow page-list cache has been allocated, it may be
52305 ** invalidated if some other cursor writes to the same table, or if
52306 ** the cursor is moved to a different row. Additionally, in auto-vacuum
52307 ** mode, the following events may invalidate an overflow page-list cache.
52308 **
52309 **   * An incremental vacuum,
52310 **   * A commit in auto_vacuum="full" mode,
52311 **   * Creating a table (may require moving an overflow page).
52312 */
52313 static int accessPayload(
52314   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52315   u32 offset,          /* Begin reading this far into payload */
52316   u32 amt,             /* Read this many bytes */
52317   unsigned char *pBuf, /* Write the bytes into this buffer */
52318   int eOp              /* zero to read. non-zero to write. */
52319 ){
52320   unsigned char *aPayload;
52321   int rc = SQLITE_OK;
52322   u32 nKey;
52323   int iIdx = 0;
52324   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
52325   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
52326 
52327   assert( pPage );
52328   assert( pCur->eState==CURSOR_VALID );
52329   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52330   assert( cursorHoldsMutex(pCur) );
52331 
52332   getCellInfo(pCur);
52333   aPayload = pCur->info.pCell + pCur->info.nHeader;
52334   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
52335 
52336   if( NEVER(offset+amt > nKey+pCur->info.nData)
52337    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
52338   ){
52339     /* Trying to read or write past the end of the data is an error */
52340     return SQLITE_CORRUPT_BKPT;
52341   }
52342 
52343   /* Check if data must be read/written to/from the btree page itself. */
52344   if( offset<pCur->info.nLocal ){
52345     int a = amt;
52346     if( a+offset>pCur->info.nLocal ){
52347       a = pCur->info.nLocal - offset;
52348     }
52349     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
52350     offset = 0;
52351     pBuf += a;
52352     amt -= a;
52353   }else{
52354     offset -= pCur->info.nLocal;
52355   }
52356 
52357   if( rc==SQLITE_OK && amt>0 ){
52358     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
52359     Pgno nextPage;
52360 
52361     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
52362 
52363 #ifndef SQLITE_OMIT_INCRBLOB
52364     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
52365     ** has not been allocated, allocate it now. The array is sized at
52366     ** one entry for each overflow page in the overflow chain. The
52367     ** page number of the first overflow page is stored in aOverflow[0],
52368     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
52369     ** (the cache is lazily populated).
52370     */
52371     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
52372       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
52373       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
52374       /* nOvfl is always positive.  If it were zero, fetchPayload would have
52375       ** been used instead of this routine. */
52376       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
52377         rc = SQLITE_NOMEM;
52378       }
52379     }
52380 
52381     /* If the overflow page-list cache has been allocated and the
52382     ** entry for the first required overflow page is valid, skip
52383     ** directly to it.
52384     */
52385     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
52386       iIdx = (offset/ovflSize);
52387       nextPage = pCur->aOverflow[iIdx];
52388       offset = (offset%ovflSize);
52389     }
52390 #endif
52391 
52392     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
52393 
52394 #ifndef SQLITE_OMIT_INCRBLOB
52395       /* If required, populate the overflow page-list cache. */
52396       if( pCur->aOverflow ){
52397         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
52398         pCur->aOverflow[iIdx] = nextPage;
52399       }
52400 #endif
52401 
52402       if( offset>=ovflSize ){
52403         /* The only reason to read this page is to obtain the page
52404         ** number for the next page in the overflow chain. The page
52405         ** data is not required. So first try to lookup the overflow
52406         ** page-list cache, if any, then fall back to the getOverflowPage()
52407         ** function.
52408         */
52409 #ifndef SQLITE_OMIT_INCRBLOB
52410         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
52411           nextPage = pCur->aOverflow[iIdx+1];
52412         } else
52413 #endif
52414           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
52415         offset -= ovflSize;
52416       }else{
52417         /* Need to read this page properly. It contains some of the
52418         ** range of data that is being read (eOp==0) or written (eOp!=0).
52419         */
52420 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52421         sqlite3_file *fd;
52422 #endif
52423         int a = amt;
52424         if( a + offset > ovflSize ){
52425           a = ovflSize - offset;
52426         }
52427 
52428 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52429         /* If all the following are true:
52430         **
52431         **   1) this is a read operation, and
52432         **   2) data is required from the start of this overflow page, and
52433         **   3) the database is file-backed, and
52434         **   4) there is no open write-transaction, and
52435         **   5) the database is not a WAL database,
52436         **
52437         ** then data can be read directly from the database file into the
52438         ** output buffer, bypassing the page-cache altogether. This speeds
52439         ** up loading large records that span many overflow pages.
52440         */
52441         if( eOp==0                                             /* (1) */
52442          && offset==0                                          /* (2) */
52443          && pBt->inTransaction==TRANS_READ                     /* (4) */
52444          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
52445          && pBt->pPage1->aData[19]==0x01                       /* (5) */
52446         ){
52447           u8 aSave[4];
52448           u8 *aWrite = &pBuf[-4];
52449           memcpy(aSave, aWrite, 4);
52450           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
52451           nextPage = get4byte(aWrite);
52452           memcpy(aWrite, aSave, 4);
52453         }else
52454 #endif
52455 
52456         {
52457           DbPage *pDbPage;
52458           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
52459           if( rc==SQLITE_OK ){
52460             aPayload = sqlite3PagerGetData(pDbPage);
52461             nextPage = get4byte(aPayload);
52462             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
52463             sqlite3PagerUnref(pDbPage);
52464             offset = 0;
52465           }
52466         }
52467         amt -= a;
52468         pBuf += a;
52469       }
52470     }
52471   }
52472 
52473   if( rc==SQLITE_OK && amt>0 ){
52474     return SQLITE_CORRUPT_BKPT;
52475   }
52476   return rc;
52477 }
52478 
52479 /*
52480 ** Read part of the key associated with cursor pCur.  Exactly
52481 ** "amt" bytes will be transfered into pBuf[].  The transfer
52482 ** begins at "offset".
52483 **
52484 ** The caller must ensure that pCur is pointing to a valid row
52485 ** in the table.
52486 **
52487 ** Return SQLITE_OK on success or an error code if anything goes
52488 ** wrong.  An error is returned if "offset+amt" is larger than
52489 ** the available payload.
52490 */
52491 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52492   assert( cursorHoldsMutex(pCur) );
52493   assert( pCur->eState==CURSOR_VALID );
52494   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52495   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52496   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
52497 }
52498 
52499 /*
52500 ** Read part of the data associated with cursor pCur.  Exactly
52501 ** "amt" bytes will be transfered into pBuf[].  The transfer
52502 ** begins at "offset".
52503 **
52504 ** Return SQLITE_OK on success or an error code if anything goes
52505 ** wrong.  An error is returned if "offset+amt" is larger than
52506 ** the available payload.
52507 */
52508 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52509   int rc;
52510 
52511 #ifndef SQLITE_OMIT_INCRBLOB
52512   if ( pCur->eState==CURSOR_INVALID ){
52513     return SQLITE_ABORT;
52514   }
52515 #endif
52516 
52517   assert( cursorHoldsMutex(pCur) );
52518   rc = restoreCursorPosition(pCur);
52519   if( rc==SQLITE_OK ){
52520     assert( pCur->eState==CURSOR_VALID );
52521     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52522     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52523     rc = accessPayload(pCur, offset, amt, pBuf, 0);
52524   }
52525   return rc;
52526 }
52527 
52528 /*
52529 ** Return a pointer to payload information from the entry that the
52530 ** pCur cursor is pointing to.  The pointer is to the beginning of
52531 ** the key if skipKey==0 and it points to the beginning of data if
52532 ** skipKey==1.  The number of bytes of available key/data is written
52533 ** into *pAmt.  If *pAmt==0, then the value returned will not be
52534 ** a valid pointer.
52535 **
52536 ** This routine is an optimization.  It is common for the entire key
52537 ** and data to fit on the local page and for there to be no overflow
52538 ** pages.  When that is so, this routine can be used to access the
52539 ** key and data without making a copy.  If the key and/or data spills
52540 ** onto overflow pages, then accessPayload() must be used to reassemble
52541 ** the key/data and copy it into a preallocated buffer.
52542 **
52543 ** The pointer returned by this routine looks directly into the cached
52544 ** page of the database.  The data might change or move the next time
52545 ** any btree routine is called.
52546 */
52547 static const unsigned char *fetchPayload(
52548   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52549   int *pAmt,           /* Write the number of available bytes here */
52550   int skipKey          /* read beginning at data if this is true */
52551 ){
52552   unsigned char *aPayload;
52553   MemPage *pPage;
52554   u32 nKey;
52555   u32 nLocal;
52556 
52557   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
52558   assert( pCur->eState==CURSOR_VALID );
52559   assert( cursorHoldsMutex(pCur) );
52560   pPage = pCur->apPage[pCur->iPage];
52561   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52562   if( NEVER(pCur->info.nSize==0) ){
52563     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
52564                    &pCur->info);
52565   }
52566   aPayload = pCur->info.pCell;
52567   aPayload += pCur->info.nHeader;
52568   if( pPage->intKey ){
52569     nKey = 0;
52570   }else{
52571     nKey = (int)pCur->info.nKey;
52572   }
52573   if( skipKey ){
52574     aPayload += nKey;
52575     nLocal = pCur->info.nLocal - nKey;
52576   }else{
52577     nLocal = pCur->info.nLocal;
52578     assert( nLocal<=nKey );
52579   }
52580   *pAmt = nLocal;
52581   return aPayload;
52582 }
52583 
52584 
52585 /*
52586 ** For the entry that cursor pCur is point to, return as
52587 ** many bytes of the key or data as are available on the local
52588 ** b-tree page.  Write the number of available bytes into *pAmt.
52589 **
52590 ** The pointer returned is ephemeral.  The key/data may move
52591 ** or be destroyed on the next call to any Btree routine,
52592 ** including calls from other threads against the same cache.
52593 ** Hence, a mutex on the BtShared should be held prior to calling
52594 ** this routine.
52595 **
52596 ** These routines is used to get quick access to key and data
52597 ** in the common case where no overflow pages are used.
52598 */
52599 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
52600   const void *p = 0;
52601   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52602   assert( cursorHoldsMutex(pCur) );
52603   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52604     p = (const void*)fetchPayload(pCur, pAmt, 0);
52605   }
52606   return p;
52607 }
52608 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
52609   const void *p = 0;
52610   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52611   assert( cursorHoldsMutex(pCur) );
52612   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52613     p = (const void*)fetchPayload(pCur, pAmt, 1);
52614   }
52615   return p;
52616 }
52617 
52618 
52619 /*
52620 ** Move the cursor down to a new child page.  The newPgno argument is the
52621 ** page number of the child page to move to.
52622 **
52623 ** This function returns SQLITE_CORRUPT if the page-header flags field of
52624 ** the new child page does not match the flags field of the parent (i.e.
52625 ** if an intkey page appears to be the parent of a non-intkey page, or
52626 ** vice-versa).
52627 */
52628 static int moveToChild(BtCursor *pCur, u32 newPgno){
52629   int rc;
52630   int i = pCur->iPage;
52631   MemPage *pNewPage;
52632   BtShared *pBt = pCur->pBt;
52633 
52634   assert( cursorHoldsMutex(pCur) );
52635   assert( pCur->eState==CURSOR_VALID );
52636   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
52637   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
52638     return SQLITE_CORRUPT_BKPT;
52639   }
52640   rc = getAndInitPage(pBt, newPgno, &pNewPage);
52641   if( rc ) return rc;
52642   pCur->apPage[i+1] = pNewPage;
52643   pCur->aiIdx[i+1] = 0;
52644   pCur->iPage++;
52645 
52646   pCur->info.nSize = 0;
52647   pCur->validNKey = 0;
52648   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
52649     return SQLITE_CORRUPT_BKPT;
52650   }
52651   return SQLITE_OK;
52652 }
52653 
52654 #if 0
52655 /*
52656 ** Page pParent is an internal (non-leaf) tree page. This function
52657 ** asserts that page number iChild is the left-child if the iIdx'th
52658 ** cell in page pParent. Or, if iIdx is equal to the total number of
52659 ** cells in pParent, that page number iChild is the right-child of
52660 ** the page.
52661 */
52662 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
52663   assert( iIdx<=pParent->nCell );
52664   if( iIdx==pParent->nCell ){
52665     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
52666   }else{
52667     assert( get4byte(findCell(pParent, iIdx))==iChild );
52668   }
52669 }
52670 #else
52671 #  define assertParentIndex(x,y,z)
52672 #endif
52673 
52674 /*
52675 ** Move the cursor up to the parent page.
52676 **
52677 ** pCur->idx is set to the cell index that contains the pointer
52678 ** to the page we are coming from.  If we are coming from the
52679 ** right-most child page then pCur->idx is set to one more than
52680 ** the largest cell index.
52681 */
52682 static void moveToParent(BtCursor *pCur){
52683   assert( cursorHoldsMutex(pCur) );
52684   assert( pCur->eState==CURSOR_VALID );
52685   assert( pCur->iPage>0 );
52686   assert( pCur->apPage[pCur->iPage] );
52687 
52688   /* UPDATE: It is actually possible for the condition tested by the assert
52689   ** below to be untrue if the database file is corrupt. This can occur if
52690   ** one cursor has modified page pParent while a reference to it is held
52691   ** by a second cursor. Which can only happen if a single page is linked
52692   ** into more than one b-tree structure in a corrupt database.  */
52693 #if 0
52694   assertParentIndex(
52695     pCur->apPage[pCur->iPage-1],
52696     pCur->aiIdx[pCur->iPage-1],
52697     pCur->apPage[pCur->iPage]->pgno
52698   );
52699 #endif
52700   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
52701 
52702   releasePage(pCur->apPage[pCur->iPage]);
52703   pCur->iPage--;
52704   pCur->info.nSize = 0;
52705   pCur->validNKey = 0;
52706 }
52707 
52708 /*
52709 ** Move the cursor to point to the root page of its b-tree structure.
52710 **
52711 ** If the table has a virtual root page, then the cursor is moved to point
52712 ** to the virtual root page instead of the actual root page. A table has a
52713 ** virtual root page when the actual root page contains no cells and a
52714 ** single child page. This can only happen with the table rooted at page 1.
52715 **
52716 ** If the b-tree structure is empty, the cursor state is set to
52717 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
52718 ** cell located on the root (or virtual root) page and the cursor state
52719 ** is set to CURSOR_VALID.
52720 **
52721 ** If this function returns successfully, it may be assumed that the
52722 ** page-header flags indicate that the [virtual] root-page is the expected
52723 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
52724 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
52725 ** indicating a table b-tree, or if the caller did specify a KeyInfo
52726 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
52727 ** b-tree).
52728 */
52729 static int moveToRoot(BtCursor *pCur){
52730   MemPage *pRoot;
52731   int rc = SQLITE_OK;
52732   Btree *p = pCur->pBtree;
52733   BtShared *pBt = p->pBt;
52734 
52735   assert( cursorHoldsMutex(pCur) );
52736   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
52737   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
52738   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
52739   if( pCur->eState>=CURSOR_REQUIRESEEK ){
52740     if( pCur->eState==CURSOR_FAULT ){
52741       assert( pCur->skipNext!=SQLITE_OK );
52742       return pCur->skipNext;
52743     }
52744     sqlite3BtreeClearCursor(pCur);
52745   }
52746 
52747   if( pCur->iPage>=0 ){
52748     int i;
52749     for(i=1; i<=pCur->iPage; i++){
52750       releasePage(pCur->apPage[i]);
52751     }
52752     pCur->iPage = 0;
52753   }else if( pCur->pgnoRoot==0 ){
52754     pCur->eState = CURSOR_INVALID;
52755     return SQLITE_OK;
52756   }else{
52757     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
52758     if( rc!=SQLITE_OK ){
52759       pCur->eState = CURSOR_INVALID;
52760       return rc;
52761     }
52762     pCur->iPage = 0;
52763 
52764     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
52765     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
52766     ** NULL, the caller expects a table b-tree. If this is not the case,
52767     ** return an SQLITE_CORRUPT error.  */
52768     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
52769     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
52770       return SQLITE_CORRUPT_BKPT;
52771     }
52772   }
52773 
52774   /* Assert that the root page is of the correct type. This must be the
52775   ** case as the call to this function that loaded the root-page (either
52776   ** this call or a previous invocation) would have detected corruption
52777   ** if the assumption were not true, and it is not possible for the flags
52778   ** byte to have been modified while this cursor is holding a reference
52779   ** to the page.  */
52780   pRoot = pCur->apPage[0];
52781   assert( pRoot->pgno==pCur->pgnoRoot );
52782   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
52783 
52784   pCur->aiIdx[0] = 0;
52785   pCur->info.nSize = 0;
52786   pCur->atLast = 0;
52787   pCur->validNKey = 0;
52788 
52789   if( pRoot->nCell==0 && !pRoot->leaf ){
52790     Pgno subpage;
52791     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
52792     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
52793     pCur->eState = CURSOR_VALID;
52794     rc = moveToChild(pCur, subpage);
52795   }else{
52796     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
52797   }
52798   return rc;
52799 }
52800 
52801 /*
52802 ** Move the cursor down to the left-most leaf entry beneath the
52803 ** entry to which it is currently pointing.
52804 **
52805 ** The left-most leaf is the one with the smallest key - the first
52806 ** in ascending order.
52807 */
52808 static int moveToLeftmost(BtCursor *pCur){
52809   Pgno pgno;
52810   int rc = SQLITE_OK;
52811   MemPage *pPage;
52812 
52813   assert( cursorHoldsMutex(pCur) );
52814   assert( pCur->eState==CURSOR_VALID );
52815   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52816     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52817     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
52818     rc = moveToChild(pCur, pgno);
52819   }
52820   return rc;
52821 }
52822 
52823 /*
52824 ** Move the cursor down to the right-most leaf entry beneath the
52825 ** page to which it is currently pointing.  Notice the difference
52826 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
52827 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
52828 ** finds the right-most entry beneath the *page*.
52829 **
52830 ** The right-most entry is the one with the largest key - the last
52831 ** key in ascending order.
52832 */
52833 static int moveToRightmost(BtCursor *pCur){
52834   Pgno pgno;
52835   int rc = SQLITE_OK;
52836   MemPage *pPage = 0;
52837 
52838   assert( cursorHoldsMutex(pCur) );
52839   assert( pCur->eState==CURSOR_VALID );
52840   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52841     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52842     pCur->aiIdx[pCur->iPage] = pPage->nCell;
52843     rc = moveToChild(pCur, pgno);
52844   }
52845   if( rc==SQLITE_OK ){
52846     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
52847     pCur->info.nSize = 0;
52848     pCur->validNKey = 0;
52849   }
52850   return rc;
52851 }
52852 
52853 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
52854 ** on success.  Set *pRes to 0 if the cursor actually points to something
52855 ** or set *pRes to 1 if the table is empty.
52856 */
52857 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
52858   int rc;
52859 
52860   assert( cursorHoldsMutex(pCur) );
52861   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52862   rc = moveToRoot(pCur);
52863   if( rc==SQLITE_OK ){
52864     if( pCur->eState==CURSOR_INVALID ){
52865       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52866       *pRes = 1;
52867     }else{
52868       assert( pCur->apPage[pCur->iPage]->nCell>0 );
52869       *pRes = 0;
52870       rc = moveToLeftmost(pCur);
52871     }
52872   }
52873   return rc;
52874 }
52875 
52876 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
52877 ** on success.  Set *pRes to 0 if the cursor actually points to something
52878 ** or set *pRes to 1 if the table is empty.
52879 */
52880 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
52881   int rc;
52882 
52883   assert( cursorHoldsMutex(pCur) );
52884   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52885 
52886   /* If the cursor already points to the last entry, this is a no-op. */
52887   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
52888 #ifdef SQLITE_DEBUG
52889     /* This block serves to assert() that the cursor really does point
52890     ** to the last entry in the b-tree. */
52891     int ii;
52892     for(ii=0; ii<pCur->iPage; ii++){
52893       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
52894     }
52895     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
52896     assert( pCur->apPage[pCur->iPage]->leaf );
52897 #endif
52898     return SQLITE_OK;
52899   }
52900 
52901   rc = moveToRoot(pCur);
52902   if( rc==SQLITE_OK ){
52903     if( CURSOR_INVALID==pCur->eState ){
52904       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52905       *pRes = 1;
52906     }else{
52907       assert( pCur->eState==CURSOR_VALID );
52908       *pRes = 0;
52909       rc = moveToRightmost(pCur);
52910       pCur->atLast = rc==SQLITE_OK ?1:0;
52911     }
52912   }
52913   return rc;
52914 }
52915 
52916 /* Move the cursor so that it points to an entry near the key
52917 ** specified by pIdxKey or intKey.   Return a success code.
52918 **
52919 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
52920 ** must be NULL.  For index tables, pIdxKey is used and intKey
52921 ** is ignored.
52922 **
52923 ** If an exact match is not found, then the cursor is always
52924 ** left pointing at a leaf page which would hold the entry if it
52925 ** were present.  The cursor might point to an entry that comes
52926 ** before or after the key.
52927 **
52928 ** An integer is written into *pRes which is the result of
52929 ** comparing the key with the entry to which the cursor is
52930 ** pointing.  The meaning of the integer written into
52931 ** *pRes is as follows:
52932 **
52933 **     *pRes<0      The cursor is left pointing at an entry that
52934 **                  is smaller than intKey/pIdxKey or if the table is empty
52935 **                  and the cursor is therefore left point to nothing.
52936 **
52937 **     *pRes==0     The cursor is left pointing at an entry that
52938 **                  exactly matches intKey/pIdxKey.
52939 **
52940 **     *pRes>0      The cursor is left pointing at an entry that
52941 **                  is larger than intKey/pIdxKey.
52942 **
52943 */
52944 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
52945   BtCursor *pCur,          /* The cursor to be moved */
52946   UnpackedRecord *pIdxKey, /* Unpacked index key */
52947   i64 intKey,              /* The table key */
52948   int biasRight,           /* If true, bias the search to the high end */
52949   int *pRes                /* Write search results here */
52950 ){
52951   int rc;
52952 
52953   assert( cursorHoldsMutex(pCur) );
52954   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52955   assert( pRes );
52956   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
52957 
52958   /* If the cursor is already positioned at the point we are trying
52959   ** to move to, then just return without doing any work */
52960   if( pCur->eState==CURSOR_VALID && pCur->validNKey
52961    && pCur->apPage[0]->intKey
52962   ){
52963     if( pCur->info.nKey==intKey ){
52964       *pRes = 0;
52965       return SQLITE_OK;
52966     }
52967     if( pCur->atLast && pCur->info.nKey<intKey ){
52968       *pRes = -1;
52969       return SQLITE_OK;
52970     }
52971   }
52972 
52973   rc = moveToRoot(pCur);
52974   if( rc ){
52975     return rc;
52976   }
52977   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
52978   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
52979   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
52980   if( pCur->eState==CURSOR_INVALID ){
52981     *pRes = -1;
52982     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52983     return SQLITE_OK;
52984   }
52985   assert( pCur->apPage[0]->intKey || pIdxKey );
52986   for(;;){
52987     int lwr, upr, idx;
52988     Pgno chldPg;
52989     MemPage *pPage = pCur->apPage[pCur->iPage];
52990     int c;
52991 
52992     /* pPage->nCell must be greater than zero. If this is the root-page
52993     ** the cursor would have been INVALID above and this for(;;) loop
52994     ** not run. If this is not the root-page, then the moveToChild() routine
52995     ** would have already detected db corruption. Similarly, pPage must
52996     ** be the right kind (index or table) of b-tree page. Otherwise
52997     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
52998     assert( pPage->nCell>0 );
52999     assert( pPage->intKey==(pIdxKey==0) );
53000     lwr = 0;
53001     upr = pPage->nCell-1;
53002     if( biasRight ){
53003       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
53004     }else{
53005       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
53006     }
53007     for(;;){
53008       u8 *pCell;                          /* Pointer to current cell in pPage */
53009 
53010       assert( idx==pCur->aiIdx[pCur->iPage] );
53011       pCur->info.nSize = 0;
53012       pCell = findCell(pPage, idx) + pPage->childPtrSize;
53013       if( pPage->intKey ){
53014         i64 nCellKey;
53015         if( pPage->hasData ){
53016           u32 dummy;
53017           pCell += getVarint32(pCell, dummy);
53018         }
53019         getVarint(pCell, (u64*)&nCellKey);
53020         if( nCellKey==intKey ){
53021           c = 0;
53022         }else if( nCellKey<intKey ){
53023           c = -1;
53024         }else{
53025           assert( nCellKey>intKey );
53026           c = +1;
53027         }
53028         pCur->validNKey = 1;
53029         pCur->info.nKey = nCellKey;
53030       }else{
53031         /* The maximum supported page-size is 65536 bytes. This means that
53032         ** the maximum number of record bytes stored on an index B-Tree
53033         ** page is less than 16384 bytes and may be stored as a 2-byte
53034         ** varint. This information is used to attempt to avoid parsing
53035         ** the entire cell by checking for the cases where the record is
53036         ** stored entirely within the b-tree page by inspecting the first
53037         ** 2 bytes of the cell.
53038         */
53039         int nCell = pCell[0];
53040         if( nCell<=pPage->max1bytePayload
53041          /* && (pCell+nCell)<pPage->aDataEnd */
53042         ){
53043           /* This branch runs if the record-size field of the cell is a
53044           ** single byte varint and the record fits entirely on the main
53045           ** b-tree page.  */
53046           testcase( pCell+nCell+1==pPage->aDataEnd );
53047           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
53048         }else if( !(pCell[1] & 0x80)
53049           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
53050           /* && (pCell+nCell+2)<=pPage->aDataEnd */
53051         ){
53052           /* The record-size field is a 2 byte varint and the record
53053           ** fits entirely on the main b-tree page.  */
53054           testcase( pCell+nCell+2==pPage->aDataEnd );
53055           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
53056         }else{
53057           /* The record flows over onto one or more overflow pages. In
53058           ** this case the whole cell needs to be parsed, a buffer allocated
53059           ** and accessPayload() used to retrieve the record into the
53060           ** buffer before VdbeRecordCompare() can be called. */
53061           void *pCellKey;
53062           u8 * const pCellBody = pCell - pPage->childPtrSize;
53063           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
53064           nCell = (int)pCur->info.nKey;
53065           pCellKey = sqlite3Malloc( nCell );
53066           if( pCellKey==0 ){
53067             rc = SQLITE_NOMEM;
53068             goto moveto_finish;
53069           }
53070           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
53071           if( rc ){
53072             sqlite3_free(pCellKey);
53073             goto moveto_finish;
53074           }
53075           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
53076           sqlite3_free(pCellKey);
53077         }
53078       }
53079       if( c==0 ){
53080         if( pPage->intKey && !pPage->leaf ){
53081           lwr = idx;
53082           break;
53083         }else{
53084           *pRes = 0;
53085           rc = SQLITE_OK;
53086           goto moveto_finish;
53087         }
53088       }
53089       if( c<0 ){
53090         lwr = idx+1;
53091       }else{
53092         upr = idx-1;
53093       }
53094       if( lwr>upr ){
53095         break;
53096       }
53097       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
53098     }
53099     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
53100     assert( pPage->isInit );
53101     if( pPage->leaf ){
53102       chldPg = 0;
53103     }else if( lwr>=pPage->nCell ){
53104       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53105     }else{
53106       chldPg = get4byte(findCell(pPage, lwr));
53107     }
53108     if( chldPg==0 ){
53109       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53110       *pRes = c;
53111       rc = SQLITE_OK;
53112       goto moveto_finish;
53113     }
53114     pCur->aiIdx[pCur->iPage] = (u16)lwr;
53115     pCur->info.nSize = 0;
53116     pCur->validNKey = 0;
53117     rc = moveToChild(pCur, chldPg);
53118     if( rc ) goto moveto_finish;
53119   }
53120 moveto_finish:
53121   return rc;
53122 }
53123 
53124 
53125 /*
53126 ** Return TRUE if the cursor is not pointing at an entry of the table.
53127 **
53128 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
53129 ** past the last entry in the table or sqlite3BtreePrev() moves past
53130 ** the first entry.  TRUE is also returned if the table is empty.
53131 */
53132 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
53133   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
53134   ** have been deleted? This API will need to change to return an error code
53135   ** as well as the boolean result value.
53136   */
53137   return (CURSOR_VALID!=pCur->eState);
53138 }
53139 
53140 /*
53141 ** Advance the cursor to the next entry in the database.  If
53142 ** successful then set *pRes=0.  If the cursor
53143 ** was already pointing to the last entry in the database before
53144 ** this routine was called, then set *pRes=1.
53145 */
53146 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
53147   int rc;
53148   int idx;
53149   MemPage *pPage;
53150 
53151   assert( cursorHoldsMutex(pCur) );
53152   rc = restoreCursorPosition(pCur);
53153   if( rc!=SQLITE_OK ){
53154     return rc;
53155   }
53156   assert( pRes!=0 );
53157   if( CURSOR_INVALID==pCur->eState ){
53158     *pRes = 1;
53159     return SQLITE_OK;
53160   }
53161   if( pCur->skipNext>0 ){
53162     pCur->skipNext = 0;
53163     *pRes = 0;
53164     return SQLITE_OK;
53165   }
53166   pCur->skipNext = 0;
53167 
53168   pPage = pCur->apPage[pCur->iPage];
53169   idx = ++pCur->aiIdx[pCur->iPage];
53170   assert( pPage->isInit );
53171 
53172   /* If the database file is corrupt, it is possible for the value of idx
53173   ** to be invalid here. This can only occur if a second cursor modifies
53174   ** the page while cursor pCur is holding a reference to it. Which can
53175   ** only happen if the database is corrupt in such a way as to link the
53176   ** page into more than one b-tree structure. */
53177   testcase( idx>pPage->nCell );
53178 
53179   pCur->info.nSize = 0;
53180   pCur->validNKey = 0;
53181   if( idx>=pPage->nCell ){
53182     if( !pPage->leaf ){
53183       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
53184       if( rc ) return rc;
53185       rc = moveToLeftmost(pCur);
53186       *pRes = 0;
53187       return rc;
53188     }
53189     do{
53190       if( pCur->iPage==0 ){
53191         *pRes = 1;
53192         pCur->eState = CURSOR_INVALID;
53193         return SQLITE_OK;
53194       }
53195       moveToParent(pCur);
53196       pPage = pCur->apPage[pCur->iPage];
53197     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
53198     *pRes = 0;
53199     if( pPage->intKey ){
53200       rc = sqlite3BtreeNext(pCur, pRes);
53201     }else{
53202       rc = SQLITE_OK;
53203     }
53204     return rc;
53205   }
53206   *pRes = 0;
53207   if( pPage->leaf ){
53208     return SQLITE_OK;
53209   }
53210   rc = moveToLeftmost(pCur);
53211   return rc;
53212 }
53213 
53214 
53215 /*
53216 ** Step the cursor to the back to the previous entry in the database.  If
53217 ** successful then set *pRes=0.  If the cursor
53218 ** was already pointing to the first entry in the database before
53219 ** this routine was called, then set *pRes=1.
53220 */
53221 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
53222   int rc;
53223   MemPage *pPage;
53224 
53225   assert( cursorHoldsMutex(pCur) );
53226   rc = restoreCursorPosition(pCur);
53227   if( rc!=SQLITE_OK ){
53228     return rc;
53229   }
53230   pCur->atLast = 0;
53231   if( CURSOR_INVALID==pCur->eState ){
53232     *pRes = 1;
53233     return SQLITE_OK;
53234   }
53235   if( pCur->skipNext<0 ){
53236     pCur->skipNext = 0;
53237     *pRes = 0;
53238     return SQLITE_OK;
53239   }
53240   pCur->skipNext = 0;
53241 
53242   pPage = pCur->apPage[pCur->iPage];
53243   assert( pPage->isInit );
53244   if( !pPage->leaf ){
53245     int idx = pCur->aiIdx[pCur->iPage];
53246     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
53247     if( rc ){
53248       return rc;
53249     }
53250     rc = moveToRightmost(pCur);
53251   }else{
53252     while( pCur->aiIdx[pCur->iPage]==0 ){
53253       if( pCur->iPage==0 ){
53254         pCur->eState = CURSOR_INVALID;
53255         *pRes = 1;
53256         return SQLITE_OK;
53257       }
53258       moveToParent(pCur);
53259     }
53260     pCur->info.nSize = 0;
53261     pCur->validNKey = 0;
53262 
53263     pCur->aiIdx[pCur->iPage]--;
53264     pPage = pCur->apPage[pCur->iPage];
53265     if( pPage->intKey && !pPage->leaf ){
53266       rc = sqlite3BtreePrevious(pCur, pRes);
53267     }else{
53268       rc = SQLITE_OK;
53269     }
53270   }
53271   *pRes = 0;
53272   return rc;
53273 }
53274 
53275 /*
53276 ** Allocate a new page from the database file.
53277 **
53278 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
53279 ** has already been called on the new page.)  The new page has also
53280 ** been referenced and the calling routine is responsible for calling
53281 ** sqlite3PagerUnref() on the new page when it is done.
53282 **
53283 ** SQLITE_OK is returned on success.  Any other return value indicates
53284 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
53285 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
53286 **
53287 ** If the "nearby" parameter is not 0, then an effort is made to
53288 ** locate a page close to the page number "nearby".  This can be used in an
53289 ** attempt to keep related pages close to each other in the database file,
53290 ** which in turn can make database access faster.
53291 **
53292 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
53293 ** anywhere on the free-list, then it is guaranteed to be returned.  If
53294 ** eMode is BTALLOC_LT then the page returned will be less than or equal
53295 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
53296 ** are no restrictions on which page is returned.
53297 */
53298 static int allocateBtreePage(
53299   BtShared *pBt,         /* The btree */
53300   MemPage **ppPage,      /* Store pointer to the allocated page here */
53301   Pgno *pPgno,           /* Store the page number here */
53302   Pgno nearby,           /* Search for a page near this one */
53303   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
53304 ){
53305   MemPage *pPage1;
53306   int rc;
53307   u32 n;     /* Number of pages on the freelist */
53308   u32 k;     /* Number of leaves on the trunk of the freelist */
53309   MemPage *pTrunk = 0;
53310   MemPage *pPrevTrunk = 0;
53311   Pgno mxPage;     /* Total size of the database file */
53312 
53313   assert( sqlite3_mutex_held(pBt->mutex) );
53314   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
53315   pPage1 = pBt->pPage1;
53316   mxPage = btreePagecount(pBt);
53317   n = get4byte(&pPage1->aData[36]);
53318   testcase( n==mxPage-1 );
53319   if( n>=mxPage ){
53320     return SQLITE_CORRUPT_BKPT;
53321   }
53322   if( n>0 ){
53323     /* There are pages on the freelist.  Reuse one of those pages. */
53324     Pgno iTrunk;
53325     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
53326 
53327     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
53328     ** shows that the page 'nearby' is somewhere on the free-list, then
53329     ** the entire-list will be searched for that page.
53330     */
53331 #ifndef SQLITE_OMIT_AUTOVACUUM
53332     if( eMode==BTALLOC_EXACT ){
53333       if( nearby<=mxPage ){
53334         u8 eType;
53335         assert( nearby>0 );
53336         assert( pBt->autoVacuum );
53337         rc = ptrmapGet(pBt, nearby, &eType, 0);
53338         if( rc ) return rc;
53339         if( eType==PTRMAP_FREEPAGE ){
53340           searchList = 1;
53341         }
53342       }
53343     }else if( eMode==BTALLOC_LE ){
53344       searchList = 1;
53345     }
53346 #endif
53347 
53348     /* Decrement the free-list count by 1. Set iTrunk to the index of the
53349     ** first free-list trunk page. iPrevTrunk is initially 1.
53350     */
53351     rc = sqlite3PagerWrite(pPage1->pDbPage);
53352     if( rc ) return rc;
53353     put4byte(&pPage1->aData[36], n-1);
53354 
53355     /* The code within this loop is run only once if the 'searchList' variable
53356     ** is not true. Otherwise, it runs once for each trunk-page on the
53357     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
53358     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
53359     */
53360     do {
53361       pPrevTrunk = pTrunk;
53362       if( pPrevTrunk ){
53363         iTrunk = get4byte(&pPrevTrunk->aData[0]);
53364       }else{
53365         iTrunk = get4byte(&pPage1->aData[32]);
53366       }
53367       testcase( iTrunk==mxPage );
53368       if( iTrunk>mxPage ){
53369         rc = SQLITE_CORRUPT_BKPT;
53370       }else{
53371         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53372       }
53373       if( rc ){
53374         pTrunk = 0;
53375         goto end_allocate_page;
53376       }
53377       assert( pTrunk!=0 );
53378       assert( pTrunk->aData!=0 );
53379 
53380       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
53381       if( k==0 && !searchList ){
53382         /* The trunk has no leaves and the list is not being searched.
53383         ** So extract the trunk page itself and use it as the newly
53384         ** allocated page */
53385         assert( pPrevTrunk==0 );
53386         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53387         if( rc ){
53388           goto end_allocate_page;
53389         }
53390         *pPgno = iTrunk;
53391         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53392         *ppPage = pTrunk;
53393         pTrunk = 0;
53394         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53395       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
53396         /* Value of k is out of range.  Database corruption */
53397         rc = SQLITE_CORRUPT_BKPT;
53398         goto end_allocate_page;
53399 #ifndef SQLITE_OMIT_AUTOVACUUM
53400       }else if( searchList
53401             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
53402       ){
53403         /* The list is being searched and this trunk page is the page
53404         ** to allocate, regardless of whether it has leaves.
53405         */
53406         *pPgno = iTrunk;
53407         *ppPage = pTrunk;
53408         searchList = 0;
53409         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53410         if( rc ){
53411           goto end_allocate_page;
53412         }
53413         if( k==0 ){
53414           if( !pPrevTrunk ){
53415             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53416           }else{
53417             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53418             if( rc!=SQLITE_OK ){
53419               goto end_allocate_page;
53420             }
53421             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
53422           }
53423         }else{
53424           /* The trunk page is required by the caller but it contains
53425           ** pointers to free-list leaves. The first leaf becomes a trunk
53426           ** page in this case.
53427           */
53428           MemPage *pNewTrunk;
53429           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
53430           if( iNewTrunk>mxPage ){
53431             rc = SQLITE_CORRUPT_BKPT;
53432             goto end_allocate_page;
53433           }
53434           testcase( iNewTrunk==mxPage );
53435           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
53436           if( rc!=SQLITE_OK ){
53437             goto end_allocate_page;
53438           }
53439           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
53440           if( rc!=SQLITE_OK ){
53441             releasePage(pNewTrunk);
53442             goto end_allocate_page;
53443           }
53444           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
53445           put4byte(&pNewTrunk->aData[4], k-1);
53446           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
53447           releasePage(pNewTrunk);
53448           if( !pPrevTrunk ){
53449             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
53450             put4byte(&pPage1->aData[32], iNewTrunk);
53451           }else{
53452             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53453             if( rc ){
53454               goto end_allocate_page;
53455             }
53456             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
53457           }
53458         }
53459         pTrunk = 0;
53460         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53461 #endif
53462       }else if( k>0 ){
53463         /* Extract a leaf from the trunk */
53464         u32 closest;
53465         Pgno iPage;
53466         unsigned char *aData = pTrunk->aData;
53467         if( nearby>0 ){
53468           u32 i;
53469           closest = 0;
53470           if( eMode==BTALLOC_LE ){
53471             for(i=0; i<k; i++){
53472               iPage = get4byte(&aData[8+i*4]);
53473               if( iPage<=nearby ){
53474                 closest = i;
53475                 break;
53476               }
53477             }
53478           }else{
53479             int dist;
53480             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
53481             for(i=1; i<k; i++){
53482               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
53483               if( d2<dist ){
53484                 closest = i;
53485                 dist = d2;
53486               }
53487             }
53488           }
53489         }else{
53490           closest = 0;
53491         }
53492 
53493         iPage = get4byte(&aData[8+closest*4]);
53494         testcase( iPage==mxPage );
53495         if( iPage>mxPage ){
53496           rc = SQLITE_CORRUPT_BKPT;
53497           goto end_allocate_page;
53498         }
53499         testcase( iPage==mxPage );
53500         if( !searchList
53501          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
53502         ){
53503           int noContent;
53504           *pPgno = iPage;
53505           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
53506                  ": %d more free pages\n",
53507                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
53508           rc = sqlite3PagerWrite(pTrunk->pDbPage);
53509           if( rc ) goto end_allocate_page;
53510           if( closest<k-1 ){
53511             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
53512           }
53513           put4byte(&aData[4], k-1);
53514           noContent = !btreeGetHasContent(pBt, *pPgno);
53515           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
53516           if( rc==SQLITE_OK ){
53517             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53518             if( rc!=SQLITE_OK ){
53519               releasePage(*ppPage);
53520             }
53521           }
53522           searchList = 0;
53523         }
53524       }
53525       releasePage(pPrevTrunk);
53526       pPrevTrunk = 0;
53527     }while( searchList );
53528   }else{
53529     /* There are no pages on the freelist, so append a new page to the
53530     ** database image.
53531     **
53532     ** Normally, new pages allocated by this block can be requested from the
53533     ** pager layer with the 'no-content' flag set. This prevents the pager
53534     ** from trying to read the pages content from disk. However, if the
53535     ** current transaction has already run one or more incremental-vacuum
53536     ** steps, then the page we are about to allocate may contain content
53537     ** that is required in the event of a rollback. In this case, do
53538     ** not set the no-content flag. This causes the pager to load and journal
53539     ** the current page content before overwriting it.
53540     **
53541     ** Note that the pager will not actually attempt to load or journal
53542     ** content for any page that really does lie past the end of the database
53543     ** file on disk. So the effects of disabling the no-content optimization
53544     ** here are confined to those pages that lie between the end of the
53545     ** database image and the end of the database file.
53546     */
53547     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate));
53548 
53549     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53550     if( rc ) return rc;
53551     pBt->nPage++;
53552     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
53553 
53554 #ifndef SQLITE_OMIT_AUTOVACUUM
53555     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
53556       /* If *pPgno refers to a pointer-map page, allocate two new pages
53557       ** at the end of the file instead of one. The first allocated page
53558       ** becomes a new pointer-map page, the second is used by the caller.
53559       */
53560       MemPage *pPg = 0;
53561       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
53562       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
53563       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
53564       if( rc==SQLITE_OK ){
53565         rc = sqlite3PagerWrite(pPg->pDbPage);
53566         releasePage(pPg);
53567       }
53568       if( rc ) return rc;
53569       pBt->nPage++;
53570       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
53571     }
53572 #endif
53573     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
53574     *pPgno = pBt->nPage;
53575 
53576     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53577     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
53578     if( rc ) return rc;
53579     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53580     if( rc!=SQLITE_OK ){
53581       releasePage(*ppPage);
53582     }
53583     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
53584   }
53585 
53586   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53587 
53588 end_allocate_page:
53589   releasePage(pTrunk);
53590   releasePage(pPrevTrunk);
53591   if( rc==SQLITE_OK ){
53592     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
53593       releasePage(*ppPage);
53594       return SQLITE_CORRUPT_BKPT;
53595     }
53596     (*ppPage)->isInit = 0;
53597   }else{
53598     *ppPage = 0;
53599   }
53600   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
53601   return rc;
53602 }
53603 
53604 /*
53605 ** This function is used to add page iPage to the database file free-list.
53606 ** It is assumed that the page is not already a part of the free-list.
53607 **
53608 ** The value passed as the second argument to this function is optional.
53609 ** If the caller happens to have a pointer to the MemPage object
53610 ** corresponding to page iPage handy, it may pass it as the second value.
53611 ** Otherwise, it may pass NULL.
53612 **
53613 ** If a pointer to a MemPage object is passed as the second argument,
53614 ** its reference count is not altered by this function.
53615 */
53616 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
53617   MemPage *pTrunk = 0;                /* Free-list trunk page */
53618   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
53619   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
53620   MemPage *pPage;                     /* Page being freed. May be NULL. */
53621   int rc;                             /* Return Code */
53622   int nFree;                          /* Initial number of pages on free-list */
53623 
53624   assert( sqlite3_mutex_held(pBt->mutex) );
53625   assert( iPage>1 );
53626   assert( !pMemPage || pMemPage->pgno==iPage );
53627 
53628   if( pMemPage ){
53629     pPage = pMemPage;
53630     sqlite3PagerRef(pPage->pDbPage);
53631   }else{
53632     pPage = btreePageLookup(pBt, iPage);
53633   }
53634 
53635   /* Increment the free page count on pPage1 */
53636   rc = sqlite3PagerWrite(pPage1->pDbPage);
53637   if( rc ) goto freepage_out;
53638   nFree = get4byte(&pPage1->aData[36]);
53639   put4byte(&pPage1->aData[36], nFree+1);
53640 
53641   if( pBt->btsFlags & BTS_SECURE_DELETE ){
53642     /* If the secure_delete option is enabled, then
53643     ** always fully overwrite deleted information with zeros.
53644     */
53645     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
53646      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
53647     ){
53648       goto freepage_out;
53649     }
53650     memset(pPage->aData, 0, pPage->pBt->pageSize);
53651   }
53652 
53653   /* If the database supports auto-vacuum, write an entry in the pointer-map
53654   ** to indicate that the page is free.
53655   */
53656   if( ISAUTOVACUUM ){
53657     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
53658     if( rc ) goto freepage_out;
53659   }
53660 
53661   /* Now manipulate the actual database free-list structure. There are two
53662   ** possibilities. If the free-list is currently empty, or if the first
53663   ** trunk page in the free-list is full, then this page will become a
53664   ** new free-list trunk page. Otherwise, it will become a leaf of the
53665   ** first trunk page in the current free-list. This block tests if it
53666   ** is possible to add the page as a new free-list leaf.
53667   */
53668   if( nFree!=0 ){
53669     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
53670 
53671     iTrunk = get4byte(&pPage1->aData[32]);
53672     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53673     if( rc!=SQLITE_OK ){
53674       goto freepage_out;
53675     }
53676 
53677     nLeaf = get4byte(&pTrunk->aData[4]);
53678     assert( pBt->usableSize>32 );
53679     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
53680       rc = SQLITE_CORRUPT_BKPT;
53681       goto freepage_out;
53682     }
53683     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
53684       /* In this case there is room on the trunk page to insert the page
53685       ** being freed as a new leaf.
53686       **
53687       ** Note that the trunk page is not really full until it contains
53688       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
53689       ** coded.  But due to a coding error in versions of SQLite prior to
53690       ** 3.6.0, databases with freelist trunk pages holding more than
53691       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
53692       ** to maintain backwards compatibility with older versions of SQLite,
53693       ** we will continue to restrict the number of entries to usableSize/4 - 8
53694       ** for now.  At some point in the future (once everyone has upgraded
53695       ** to 3.6.0 or later) we should consider fixing the conditional above
53696       ** to read "usableSize/4-2" instead of "usableSize/4-8".
53697       */
53698       rc = sqlite3PagerWrite(pTrunk->pDbPage);
53699       if( rc==SQLITE_OK ){
53700         put4byte(&pTrunk->aData[4], nLeaf+1);
53701         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
53702         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
53703           sqlite3PagerDontWrite(pPage->pDbPage);
53704         }
53705         rc = btreeSetHasContent(pBt, iPage);
53706       }
53707       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
53708       goto freepage_out;
53709     }
53710   }
53711 
53712   /* If control flows to this point, then it was not possible to add the
53713   ** the page being freed as a leaf page of the first trunk in the free-list.
53714   ** Possibly because the free-list is empty, or possibly because the
53715   ** first trunk in the free-list is full. Either way, the page being freed
53716   ** will become the new first trunk page in the free-list.
53717   */
53718   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
53719     goto freepage_out;
53720   }
53721   rc = sqlite3PagerWrite(pPage->pDbPage);
53722   if( rc!=SQLITE_OK ){
53723     goto freepage_out;
53724   }
53725   put4byte(pPage->aData, iTrunk);
53726   put4byte(&pPage->aData[4], 0);
53727   put4byte(&pPage1->aData[32], iPage);
53728   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
53729 
53730 freepage_out:
53731   if( pPage ){
53732     pPage->isInit = 0;
53733   }
53734   releasePage(pPage);
53735   releasePage(pTrunk);
53736   return rc;
53737 }
53738 static void freePage(MemPage *pPage, int *pRC){
53739   if( (*pRC)==SQLITE_OK ){
53740     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
53741   }
53742 }
53743 
53744 /*
53745 ** Free any overflow pages associated with the given Cell.
53746 */
53747 static int clearCell(MemPage *pPage, unsigned char *pCell){
53748   BtShared *pBt = pPage->pBt;
53749   CellInfo info;
53750   Pgno ovflPgno;
53751   int rc;
53752   int nOvfl;
53753   u32 ovflPageSize;
53754 
53755   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53756   btreeParseCellPtr(pPage, pCell, &info);
53757   if( info.iOverflow==0 ){
53758     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
53759   }
53760   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
53761     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
53762   }
53763   ovflPgno = get4byte(&pCell[info.iOverflow]);
53764   assert( pBt->usableSize > 4 );
53765   ovflPageSize = pBt->usableSize - 4;
53766   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
53767   assert( ovflPgno==0 || nOvfl>0 );
53768   while( nOvfl-- ){
53769     Pgno iNext = 0;
53770     MemPage *pOvfl = 0;
53771     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
53772       /* 0 is not a legal page number and page 1 cannot be an
53773       ** overflow page. Therefore if ovflPgno<2 or past the end of the
53774       ** file the database must be corrupt. */
53775       return SQLITE_CORRUPT_BKPT;
53776     }
53777     if( nOvfl ){
53778       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
53779       if( rc ) return rc;
53780     }
53781 
53782     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
53783      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
53784     ){
53785       /* There is no reason any cursor should have an outstanding reference
53786       ** to an overflow page belonging to a cell that is being deleted/updated.
53787       ** So if there exists more than one reference to this page, then it
53788       ** must not really be an overflow page and the database must be corrupt.
53789       ** It is helpful to detect this before calling freePage2(), as
53790       ** freePage2() may zero the page contents if secure-delete mode is
53791       ** enabled. If this 'overflow' page happens to be a page that the
53792       ** caller is iterating through or using in some other way, this
53793       ** can be problematic.
53794       */
53795       rc = SQLITE_CORRUPT_BKPT;
53796     }else{
53797       rc = freePage2(pBt, pOvfl, ovflPgno);
53798     }
53799 
53800     if( pOvfl ){
53801       sqlite3PagerUnref(pOvfl->pDbPage);
53802     }
53803     if( rc ) return rc;
53804     ovflPgno = iNext;
53805   }
53806   return SQLITE_OK;
53807 }
53808 
53809 /*
53810 ** Create the byte sequence used to represent a cell on page pPage
53811 ** and write that byte sequence into pCell[].  Overflow pages are
53812 ** allocated and filled in as necessary.  The calling procedure
53813 ** is responsible for making sure sufficient space has been allocated
53814 ** for pCell[].
53815 **
53816 ** Note that pCell does not necessary need to point to the pPage->aData
53817 ** area.  pCell might point to some temporary storage.  The cell will
53818 ** be constructed in this temporary area then copied into pPage->aData
53819 ** later.
53820 */
53821 static int fillInCell(
53822   MemPage *pPage,                /* The page that contains the cell */
53823   unsigned char *pCell,          /* Complete text of the cell */
53824   const void *pKey, i64 nKey,    /* The key */
53825   const void *pData,int nData,   /* The data */
53826   int nZero,                     /* Extra zero bytes to append to pData */
53827   int *pnSize                    /* Write cell size here */
53828 ){
53829   int nPayload;
53830   const u8 *pSrc;
53831   int nSrc, n, rc;
53832   int spaceLeft;
53833   MemPage *pOvfl = 0;
53834   MemPage *pToRelease = 0;
53835   unsigned char *pPrior;
53836   unsigned char *pPayload;
53837   BtShared *pBt = pPage->pBt;
53838   Pgno pgnoOvfl = 0;
53839   int nHeader;
53840   CellInfo info;
53841 
53842   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53843 
53844   /* pPage is not necessarily writeable since pCell might be auxiliary
53845   ** buffer space that is separate from the pPage buffer area */
53846   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
53847             || sqlite3PagerIswriteable(pPage->pDbPage) );
53848 
53849   /* Fill in the header. */
53850   nHeader = 0;
53851   if( !pPage->leaf ){
53852     nHeader += 4;
53853   }
53854   if( pPage->hasData ){
53855     nHeader += putVarint(&pCell[nHeader], nData+nZero);
53856   }else{
53857     nData = nZero = 0;
53858   }
53859   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
53860   btreeParseCellPtr(pPage, pCell, &info);
53861   assert( info.nHeader==nHeader );
53862   assert( info.nKey==nKey );
53863   assert( info.nData==(u32)(nData+nZero) );
53864 
53865   /* Fill in the payload */
53866   nPayload = nData + nZero;
53867   if( pPage->intKey ){
53868     pSrc = pData;
53869     nSrc = nData;
53870     nData = 0;
53871   }else{
53872     if( NEVER(nKey>0x7fffffff || pKey==0) ){
53873       return SQLITE_CORRUPT_BKPT;
53874     }
53875     nPayload += (int)nKey;
53876     pSrc = pKey;
53877     nSrc = (int)nKey;
53878   }
53879   *pnSize = info.nSize;
53880   spaceLeft = info.nLocal;
53881   pPayload = &pCell[nHeader];
53882   pPrior = &pCell[info.iOverflow];
53883 
53884   while( nPayload>0 ){
53885     if( spaceLeft==0 ){
53886 #ifndef SQLITE_OMIT_AUTOVACUUM
53887       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
53888       if( pBt->autoVacuum ){
53889         do{
53890           pgnoOvfl++;
53891         } while(
53892           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
53893         );
53894       }
53895 #endif
53896       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
53897 #ifndef SQLITE_OMIT_AUTOVACUUM
53898       /* If the database supports auto-vacuum, and the second or subsequent
53899       ** overflow page is being allocated, add an entry to the pointer-map
53900       ** for that page now.
53901       **
53902       ** If this is the first overflow page, then write a partial entry
53903       ** to the pointer-map. If we write nothing to this pointer-map slot,
53904       ** then the optimistic overflow chain processing in clearCell()
53905       ** may misinterpret the uninitialized values and delete the
53906       ** wrong pages from the database.
53907       */
53908       if( pBt->autoVacuum && rc==SQLITE_OK ){
53909         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
53910         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
53911         if( rc ){
53912           releasePage(pOvfl);
53913         }
53914       }
53915 #endif
53916       if( rc ){
53917         releasePage(pToRelease);
53918         return rc;
53919       }
53920 
53921       /* If pToRelease is not zero than pPrior points into the data area
53922       ** of pToRelease.  Make sure pToRelease is still writeable. */
53923       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53924 
53925       /* If pPrior is part of the data area of pPage, then make sure pPage
53926       ** is still writeable */
53927       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
53928             || sqlite3PagerIswriteable(pPage->pDbPage) );
53929 
53930       put4byte(pPrior, pgnoOvfl);
53931       releasePage(pToRelease);
53932       pToRelease = pOvfl;
53933       pPrior = pOvfl->aData;
53934       put4byte(pPrior, 0);
53935       pPayload = &pOvfl->aData[4];
53936       spaceLeft = pBt->usableSize - 4;
53937     }
53938     n = nPayload;
53939     if( n>spaceLeft ) n = spaceLeft;
53940 
53941     /* If pToRelease is not zero than pPayload points into the data area
53942     ** of pToRelease.  Make sure pToRelease is still writeable. */
53943     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53944 
53945     /* If pPayload is part of the data area of pPage, then make sure pPage
53946     ** is still writeable */
53947     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
53948             || sqlite3PagerIswriteable(pPage->pDbPage) );
53949 
53950     if( nSrc>0 ){
53951       if( n>nSrc ) n = nSrc;
53952       assert( pSrc );
53953       memcpy(pPayload, pSrc, n);
53954     }else{
53955       memset(pPayload, 0, n);
53956     }
53957     nPayload -= n;
53958     pPayload += n;
53959     pSrc += n;
53960     nSrc -= n;
53961     spaceLeft -= n;
53962     if( nSrc==0 ){
53963       nSrc = nData;
53964       pSrc = pData;
53965     }
53966   }
53967   releasePage(pToRelease);
53968   return SQLITE_OK;
53969 }
53970 
53971 /*
53972 ** Remove the i-th cell from pPage.  This routine effects pPage only.
53973 ** The cell content is not freed or deallocated.  It is assumed that
53974 ** the cell content has been copied someplace else.  This routine just
53975 ** removes the reference to the cell from pPage.
53976 **
53977 ** "sz" must be the number of bytes in the cell.
53978 */
53979 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
53980   u32 pc;         /* Offset to cell content of cell being deleted */
53981   u8 *data;       /* pPage->aData */
53982   u8 *ptr;        /* Used to move bytes around within data[] */
53983   u8 *endPtr;     /* End of loop */
53984   int rc;         /* The return code */
53985   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
53986 
53987   if( *pRC ) return;
53988 
53989   assert( idx>=0 && idx<pPage->nCell );
53990   assert( sz==cellSize(pPage, idx) );
53991   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53992   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53993   data = pPage->aData;
53994   ptr = &pPage->aCellIdx[2*idx];
53995   pc = get2byte(ptr);
53996   hdr = pPage->hdrOffset;
53997   testcase( pc==get2byte(&data[hdr+5]) );
53998   testcase( pc+sz==pPage->pBt->usableSize );
53999   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
54000     *pRC = SQLITE_CORRUPT_BKPT;
54001     return;
54002   }
54003   rc = freeSpace(pPage, pc, sz);
54004   if( rc ){
54005     *pRC = rc;
54006     return;
54007   }
54008   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
54009   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54010   while( ptr<endPtr ){
54011     *(u16*)ptr = *(u16*)&ptr[2];
54012     ptr += 2;
54013   }
54014   pPage->nCell--;
54015   put2byte(&data[hdr+3], pPage->nCell);
54016   pPage->nFree += 2;
54017 }
54018 
54019 /*
54020 ** Insert a new cell on pPage at cell index "i".  pCell points to the
54021 ** content of the cell.
54022 **
54023 ** If the cell content will fit on the page, then put it there.  If it
54024 ** will not fit, then make a copy of the cell content into pTemp if
54025 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
54026 ** in pPage->apOvfl[] and make it point to the cell content (either
54027 ** in pTemp or the original pCell) and also record its index.
54028 ** Allocating a new entry in pPage->aCell[] implies that
54029 ** pPage->nOverflow is incremented.
54030 **
54031 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
54032 ** cell. The caller will overwrite them after this function returns. If
54033 ** nSkip is non-zero, then pCell may not point to an invalid memory location
54034 ** (but pCell+nSkip is always valid).
54035 */
54036 static void insertCell(
54037   MemPage *pPage,   /* Page into which we are copying */
54038   int i,            /* New cell becomes the i-th cell of the page */
54039   u8 *pCell,        /* Content of the new cell */
54040   int sz,           /* Bytes of content in pCell */
54041   u8 *pTemp,        /* Temp storage space for pCell, if needed */
54042   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
54043   int *pRC          /* Read and write return code from here */
54044 ){
54045   int idx = 0;      /* Where to write new cell content in data[] */
54046   int j;            /* Loop counter */
54047   int end;          /* First byte past the last cell pointer in data[] */
54048   int ins;          /* Index in data[] where new cell pointer is inserted */
54049   int cellOffset;   /* Address of first cell pointer in data[] */
54050   u8 *data;         /* The content of the whole page */
54051   u8 *ptr;          /* Used for moving information around in data[] */
54052   u8 *endPtr;       /* End of the loop */
54053 
54054   int nSkip = (iChild ? 4 : 0);
54055 
54056   if( *pRC ) return;
54057 
54058   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
54059   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
54060   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
54061   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
54062   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54063   /* The cell should normally be sized correctly.  However, when moving a
54064   ** malformed cell from a leaf page to an interior page, if the cell size
54065   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
54066   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
54067   ** the term after the || in the following assert(). */
54068   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
54069   if( pPage->nOverflow || sz+2>pPage->nFree ){
54070     if( pTemp ){
54071       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
54072       pCell = pTemp;
54073     }
54074     if( iChild ){
54075       put4byte(pCell, iChild);
54076     }
54077     j = pPage->nOverflow++;
54078     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
54079     pPage->apOvfl[j] = pCell;
54080     pPage->aiOvfl[j] = (u16)i;
54081   }else{
54082     int rc = sqlite3PagerWrite(pPage->pDbPage);
54083     if( rc!=SQLITE_OK ){
54084       *pRC = rc;
54085       return;
54086     }
54087     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54088     data = pPage->aData;
54089     cellOffset = pPage->cellOffset;
54090     end = cellOffset + 2*pPage->nCell;
54091     ins = cellOffset + 2*i;
54092     rc = allocateSpace(pPage, sz, &idx);
54093     if( rc ){ *pRC = rc; return; }
54094     /* The allocateSpace() routine guarantees the following two properties
54095     ** if it returns success */
54096     assert( idx >= end+2 );
54097     assert( idx+sz <= (int)pPage->pBt->usableSize );
54098     pPage->nCell++;
54099     pPage->nFree -= (u16)(2 + sz);
54100     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
54101     if( iChild ){
54102       put4byte(&data[idx], iChild);
54103     }
54104     ptr = &data[end];
54105     endPtr = &data[ins];
54106     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54107     while( ptr>endPtr ){
54108       *(u16*)ptr = *(u16*)&ptr[-2];
54109       ptr -= 2;
54110     }
54111     put2byte(&data[ins], idx);
54112     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
54113 #ifndef SQLITE_OMIT_AUTOVACUUM
54114     if( pPage->pBt->autoVacuum ){
54115       /* The cell may contain a pointer to an overflow page. If so, write
54116       ** the entry for the overflow page into the pointer map.
54117       */
54118       ptrmapPutOvflPtr(pPage, pCell, pRC);
54119     }
54120 #endif
54121   }
54122 }
54123 
54124 /*
54125 ** Add a list of cells to a page.  The page should be initially empty.
54126 ** The cells are guaranteed to fit on the page.
54127 */
54128 static void assemblePage(
54129   MemPage *pPage,   /* The page to be assemblied */
54130   int nCell,        /* The number of cells to add to this page */
54131   u8 **apCell,      /* Pointers to cell bodies */
54132   u16 *aSize        /* Sizes of the cells */
54133 ){
54134   int i;            /* Loop counter */
54135   u8 *pCellptr;     /* Address of next cell pointer */
54136   int cellbody;     /* Address of next cell body */
54137   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
54138   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
54139   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
54140 
54141   assert( pPage->nOverflow==0 );
54142   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54143   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
54144             && (int)MX_CELL(pPage->pBt)<=10921);
54145   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54146 
54147   /* Check that the page has just been zeroed by zeroPage() */
54148   assert( pPage->nCell==0 );
54149   assert( get2byteNotZero(&data[hdr+5])==nUsable );
54150 
54151   pCellptr = &pPage->aCellIdx[nCell*2];
54152   cellbody = nUsable;
54153   for(i=nCell-1; i>=0; i--){
54154     u16 sz = aSize[i];
54155     pCellptr -= 2;
54156     cellbody -= sz;
54157     put2byte(pCellptr, cellbody);
54158     memcpy(&data[cellbody], apCell[i], sz);
54159   }
54160   put2byte(&data[hdr+3], nCell);
54161   put2byte(&data[hdr+5], cellbody);
54162   pPage->nFree -= (nCell*2 + nUsable - cellbody);
54163   pPage->nCell = (u16)nCell;
54164 }
54165 
54166 /*
54167 ** The following parameters determine how many adjacent pages get involved
54168 ** in a balancing operation.  NN is the number of neighbors on either side
54169 ** of the page that participate in the balancing operation.  NB is the
54170 ** total number of pages that participate, including the target page and
54171 ** NN neighbors on either side.
54172 **
54173 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
54174 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
54175 ** in exchange for a larger degradation in INSERT and UPDATE performance.
54176 ** The value of NN appears to give the best results overall.
54177 */
54178 #define NN 1             /* Number of neighbors on either side of pPage */
54179 #define NB (NN*2+1)      /* Total pages involved in the balance */
54180 
54181 
54182 #ifndef SQLITE_OMIT_QUICKBALANCE
54183 /*
54184 ** This version of balance() handles the common special case where
54185 ** a new entry is being inserted on the extreme right-end of the
54186 ** tree, in other words, when the new entry will become the largest
54187 ** entry in the tree.
54188 **
54189 ** Instead of trying to balance the 3 right-most leaf pages, just add
54190 ** a new page to the right-hand side and put the one new entry in
54191 ** that page.  This leaves the right side of the tree somewhat
54192 ** unbalanced.  But odds are that we will be inserting new entries
54193 ** at the end soon afterwards so the nearly empty page will quickly
54194 ** fill up.  On average.
54195 **
54196 ** pPage is the leaf page which is the right-most page in the tree.
54197 ** pParent is its parent.  pPage must have a single overflow entry
54198 ** which is also the right-most entry on the page.
54199 **
54200 ** The pSpace buffer is used to store a temporary copy of the divider
54201 ** cell that will be inserted into pParent. Such a cell consists of a 4
54202 ** byte page number followed by a variable length integer. In other
54203 ** words, at most 13 bytes. Hence the pSpace buffer must be at
54204 ** least 13 bytes in size.
54205 */
54206 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
54207   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
54208   MemPage *pNew;                       /* Newly allocated page */
54209   int rc;                              /* Return Code */
54210   Pgno pgnoNew;                        /* Page number of pNew */
54211 
54212   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54213   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54214   assert( pPage->nOverflow==1 );
54215 
54216   /* This error condition is now caught prior to reaching this function */
54217   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
54218 
54219   /* Allocate a new page. This page will become the right-sibling of
54220   ** pPage. Make the parent page writable, so that the new divider cell
54221   ** may be inserted. If both these operations are successful, proceed.
54222   */
54223   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
54224 
54225   if( rc==SQLITE_OK ){
54226 
54227     u8 *pOut = &pSpace[4];
54228     u8 *pCell = pPage->apOvfl[0];
54229     u16 szCell = cellSizePtr(pPage, pCell);
54230     u8 *pStop;
54231 
54232     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
54233     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
54234     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
54235     assemblePage(pNew, 1, &pCell, &szCell);
54236 
54237     /* If this is an auto-vacuum database, update the pointer map
54238     ** with entries for the new page, and any pointer from the
54239     ** cell on the page to an overflow page. If either of these
54240     ** operations fails, the return code is set, but the contents
54241     ** of the parent page are still manipulated by thh code below.
54242     ** That is Ok, at this point the parent page is guaranteed to
54243     ** be marked as dirty. Returning an error code will cause a
54244     ** rollback, undoing any changes made to the parent page.
54245     */
54246     if( ISAUTOVACUUM ){
54247       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
54248       if( szCell>pNew->minLocal ){
54249         ptrmapPutOvflPtr(pNew, pCell, &rc);
54250       }
54251     }
54252 
54253     /* Create a divider cell to insert into pParent. The divider cell
54254     ** consists of a 4-byte page number (the page number of pPage) and
54255     ** a variable length key value (which must be the same value as the
54256     ** largest key on pPage).
54257     **
54258     ** To find the largest key value on pPage, first find the right-most
54259     ** cell on pPage. The first two fields of this cell are the
54260     ** record-length (a variable length integer at most 32-bits in size)
54261     ** and the key value (a variable length integer, may have any value).
54262     ** The first of the while(...) loops below skips over the record-length
54263     ** field. The second while(...) loop copies the key value from the
54264     ** cell on pPage into the pSpace buffer.
54265     */
54266     pCell = findCell(pPage, pPage->nCell-1);
54267     pStop = &pCell[9];
54268     while( (*(pCell++)&0x80) && pCell<pStop );
54269     pStop = &pCell[9];
54270     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
54271 
54272     /* Insert the new divider cell into pParent. */
54273     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
54274                0, pPage->pgno, &rc);
54275 
54276     /* Set the right-child pointer of pParent to point to the new page. */
54277     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
54278 
54279     /* Release the reference to the new page. */
54280     releasePage(pNew);
54281   }
54282 
54283   return rc;
54284 }
54285 #endif /* SQLITE_OMIT_QUICKBALANCE */
54286 
54287 #if 0
54288 /*
54289 ** This function does not contribute anything to the operation of SQLite.
54290 ** it is sometimes activated temporarily while debugging code responsible
54291 ** for setting pointer-map entries.
54292 */
54293 static int ptrmapCheckPages(MemPage **apPage, int nPage){
54294   int i, j;
54295   for(i=0; i<nPage; i++){
54296     Pgno n;
54297     u8 e;
54298     MemPage *pPage = apPage[i];
54299     BtShared *pBt = pPage->pBt;
54300     assert( pPage->isInit );
54301 
54302     for(j=0; j<pPage->nCell; j++){
54303       CellInfo info;
54304       u8 *z;
54305 
54306       z = findCell(pPage, j);
54307       btreeParseCellPtr(pPage, z, &info);
54308       if( info.iOverflow ){
54309         Pgno ovfl = get4byte(&z[info.iOverflow]);
54310         ptrmapGet(pBt, ovfl, &e, &n);
54311         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
54312       }
54313       if( !pPage->leaf ){
54314         Pgno child = get4byte(z);
54315         ptrmapGet(pBt, child, &e, &n);
54316         assert( n==pPage->pgno && e==PTRMAP_BTREE );
54317       }
54318     }
54319     if( !pPage->leaf ){
54320       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54321       ptrmapGet(pBt, child, &e, &n);
54322       assert( n==pPage->pgno && e==PTRMAP_BTREE );
54323     }
54324   }
54325   return 1;
54326 }
54327 #endif
54328 
54329 /*
54330 ** This function is used to copy the contents of the b-tree node stored
54331 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
54332 ** the pointer-map entries for each child page are updated so that the
54333 ** parent page stored in the pointer map is page pTo. If pFrom contained
54334 ** any cells with overflow page pointers, then the corresponding pointer
54335 ** map entries are also updated so that the parent page is page pTo.
54336 **
54337 ** If pFrom is currently carrying any overflow cells (entries in the
54338 ** MemPage.apOvfl[] array), they are not copied to pTo.
54339 **
54340 ** Before returning, page pTo is reinitialized using btreeInitPage().
54341 **
54342 ** The performance of this function is not critical. It is only used by
54343 ** the balance_shallower() and balance_deeper() procedures, neither of
54344 ** which are called often under normal circumstances.
54345 */
54346 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
54347   if( (*pRC)==SQLITE_OK ){
54348     BtShared * const pBt = pFrom->pBt;
54349     u8 * const aFrom = pFrom->aData;
54350     u8 * const aTo = pTo->aData;
54351     int const iFromHdr = pFrom->hdrOffset;
54352     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
54353     int rc;
54354     int iData;
54355 
54356 
54357     assert( pFrom->isInit );
54358     assert( pFrom->nFree>=iToHdr );
54359     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
54360 
54361     /* Copy the b-tree node content from page pFrom to page pTo. */
54362     iData = get2byte(&aFrom[iFromHdr+5]);
54363     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
54364     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
54365 
54366     /* Reinitialize page pTo so that the contents of the MemPage structure
54367     ** match the new data. The initialization of pTo can actually fail under
54368     ** fairly obscure circumstances, even though it is a copy of initialized
54369     ** page pFrom.
54370     */
54371     pTo->isInit = 0;
54372     rc = btreeInitPage(pTo);
54373     if( rc!=SQLITE_OK ){
54374       *pRC = rc;
54375       return;
54376     }
54377 
54378     /* If this is an auto-vacuum database, update the pointer-map entries
54379     ** for any b-tree or overflow pages that pTo now contains the pointers to.
54380     */
54381     if( ISAUTOVACUUM ){
54382       *pRC = setChildPtrmaps(pTo);
54383     }
54384   }
54385 }
54386 
54387 /*
54388 ** This routine redistributes cells on the iParentIdx'th child of pParent
54389 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
54390 ** same amount of free space. Usually a single sibling on either side of the
54391 ** page are used in the balancing, though both siblings might come from one
54392 ** side if the page is the first or last child of its parent. If the page
54393 ** has fewer than 2 siblings (something which can only happen if the page
54394 ** is a root page or a child of a root page) then all available siblings
54395 ** participate in the balancing.
54396 **
54397 ** The number of siblings of the page might be increased or decreased by
54398 ** one or two in an effort to keep pages nearly full but not over full.
54399 **
54400 ** Note that when this routine is called, some of the cells on the page
54401 ** might not actually be stored in MemPage.aData[]. This can happen
54402 ** if the page is overfull. This routine ensures that all cells allocated
54403 ** to the page and its siblings fit into MemPage.aData[] before returning.
54404 **
54405 ** In the course of balancing the page and its siblings, cells may be
54406 ** inserted into or removed from the parent page (pParent). Doing so
54407 ** may cause the parent page to become overfull or underfull. If this
54408 ** happens, it is the responsibility of the caller to invoke the correct
54409 ** balancing routine to fix this problem (see the balance() routine).
54410 **
54411 ** If this routine fails for any reason, it might leave the database
54412 ** in a corrupted state. So if this routine fails, the database should
54413 ** be rolled back.
54414 **
54415 ** The third argument to this function, aOvflSpace, is a pointer to a
54416 ** buffer big enough to hold one page. If while inserting cells into the parent
54417 ** page (pParent) the parent page becomes overfull, this buffer is
54418 ** used to store the parent's overflow cells. Because this function inserts
54419 ** a maximum of four divider cells into the parent page, and the maximum
54420 ** size of a cell stored within an internal node is always less than 1/4
54421 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
54422 ** enough for all overflow cells.
54423 **
54424 ** If aOvflSpace is set to a null pointer, this function returns
54425 ** SQLITE_NOMEM.
54426 */
54427 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
54428 #pragma optimize("", off)
54429 #endif
54430 static int balance_nonroot(
54431   MemPage *pParent,               /* Parent page of siblings being balanced */
54432   int iParentIdx,                 /* Index of "the page" in pParent */
54433   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
54434   int isRoot,                     /* True if pParent is a root-page */
54435   int bBulk                       /* True if this call is part of a bulk load */
54436 ){
54437   BtShared *pBt;               /* The whole database */
54438   int nCell = 0;               /* Number of cells in apCell[] */
54439   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
54440   int nNew = 0;                /* Number of pages in apNew[] */
54441   int nOld;                    /* Number of pages in apOld[] */
54442   int i, j, k;                 /* Loop counters */
54443   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
54444   int rc = SQLITE_OK;          /* The return code */
54445   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
54446   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
54447   int usableSpace;             /* Bytes in pPage beyond the header */
54448   int pageFlags;               /* Value of pPage->aData[0] */
54449   int subtotal;                /* Subtotal of bytes in cells on one page */
54450   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
54451   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
54452   int szScratch;               /* Size of scratch memory requested */
54453   MemPage *apOld[NB];          /* pPage and up to two siblings */
54454   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
54455   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
54456   u8 *pRight;                  /* Location in parent of right-sibling pointer */
54457   u8 *apDiv[NB-1];             /* Divider cells in pParent */
54458   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
54459   int szNew[NB+2];             /* Combined size of cells place on i-th page */
54460   u8 **apCell = 0;             /* All cells begin balanced */
54461   u16 *szCell;                 /* Local size of all cells in apCell[] */
54462   u8 *aSpace1;                 /* Space for copies of dividers cells */
54463   Pgno pgno;                   /* Temp var to store a page number in */
54464 
54465   pBt = pParent->pBt;
54466   assert( sqlite3_mutex_held(pBt->mutex) );
54467   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54468 
54469 #if 0
54470   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
54471 #endif
54472 
54473   /* At this point pParent may have at most one overflow cell. And if
54474   ** this overflow cell is present, it must be the cell with
54475   ** index iParentIdx. This scenario comes about when this function
54476   ** is called (indirectly) from sqlite3BtreeDelete().
54477   */
54478   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
54479   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
54480 
54481   if( !aOvflSpace ){
54482     return SQLITE_NOMEM;
54483   }
54484 
54485   /* Find the sibling pages to balance. Also locate the cells in pParent
54486   ** that divide the siblings. An attempt is made to find NN siblings on
54487   ** either side of pPage. More siblings are taken from one side, however,
54488   ** if there are fewer than NN siblings on the other side. If pParent
54489   ** has NB or fewer children then all children of pParent are taken.
54490   **
54491   ** This loop also drops the divider cells from the parent page. This
54492   ** way, the remainder of the function does not have to deal with any
54493   ** overflow cells in the parent page, since if any existed they will
54494   ** have already been removed.
54495   */
54496   i = pParent->nOverflow + pParent->nCell;
54497   if( i<2 ){
54498     nxDiv = 0;
54499   }else{
54500     assert( bBulk==0 || bBulk==1 );
54501     if( iParentIdx==0 ){
54502       nxDiv = 0;
54503     }else if( iParentIdx==i ){
54504       nxDiv = i-2+bBulk;
54505     }else{
54506       assert( bBulk==0 );
54507       nxDiv = iParentIdx-1;
54508     }
54509     i = 2-bBulk;
54510   }
54511   nOld = i+1;
54512   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
54513     pRight = &pParent->aData[pParent->hdrOffset+8];
54514   }else{
54515     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
54516   }
54517   pgno = get4byte(pRight);
54518   while( 1 ){
54519     rc = getAndInitPage(pBt, pgno, &apOld[i]);
54520     if( rc ){
54521       memset(apOld, 0, (i+1)*sizeof(MemPage*));
54522       goto balance_cleanup;
54523     }
54524     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
54525     if( (i--)==0 ) break;
54526 
54527     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
54528       apDiv[i] = pParent->apOvfl[0];
54529       pgno = get4byte(apDiv[i]);
54530       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54531       pParent->nOverflow = 0;
54532     }else{
54533       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
54534       pgno = get4byte(apDiv[i]);
54535       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54536 
54537       /* Drop the cell from the parent page. apDiv[i] still points to
54538       ** the cell within the parent, even though it has been dropped.
54539       ** This is safe because dropping a cell only overwrites the first
54540       ** four bytes of it, and this function does not need the first
54541       ** four bytes of the divider cell. So the pointer is safe to use
54542       ** later on.
54543       **
54544       ** But not if we are in secure-delete mode. In secure-delete mode,
54545       ** the dropCell() routine will overwrite the entire cell with zeroes.
54546       ** In this case, temporarily copy the cell into the aOvflSpace[]
54547       ** buffer. It will be copied out again as soon as the aSpace[] buffer
54548       ** is allocated.  */
54549       if( pBt->btsFlags & BTS_SECURE_DELETE ){
54550         int iOff;
54551 
54552         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
54553         if( (iOff+szNew[i])>(int)pBt->usableSize ){
54554           rc = SQLITE_CORRUPT_BKPT;
54555           memset(apOld, 0, (i+1)*sizeof(MemPage*));
54556           goto balance_cleanup;
54557         }else{
54558           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
54559           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
54560         }
54561       }
54562       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
54563     }
54564   }
54565 
54566   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
54567   ** alignment */
54568   nMaxCells = (nMaxCells + 3)&~3;
54569 
54570   /*
54571   ** Allocate space for memory structures
54572   */
54573   k = pBt->pageSize + ROUND8(sizeof(MemPage));
54574   szScratch =
54575        nMaxCells*sizeof(u8*)                       /* apCell */
54576      + nMaxCells*sizeof(u16)                       /* szCell */
54577      + pBt->pageSize                               /* aSpace1 */
54578      + k*nOld;                                     /* Page copies (apCopy) */
54579   apCell = sqlite3ScratchMalloc( szScratch );
54580   if( apCell==0 ){
54581     rc = SQLITE_NOMEM;
54582     goto balance_cleanup;
54583   }
54584   szCell = (u16*)&apCell[nMaxCells];
54585   aSpace1 = (u8*)&szCell[nMaxCells];
54586   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
54587 
54588   /*
54589   ** Load pointers to all cells on sibling pages and the divider cells
54590   ** into the local apCell[] array.  Make copies of the divider cells
54591   ** into space obtained from aSpace1[] and remove the divider cells
54592   ** from pParent.
54593   **
54594   ** If the siblings are on leaf pages, then the child pointers of the
54595   ** divider cells are stripped from the cells before they are copied
54596   ** into aSpace1[].  In this way, all cells in apCell[] are without
54597   ** child pointers.  If siblings are not leaves, then all cell in
54598   ** apCell[] include child pointers.  Either way, all cells in apCell[]
54599   ** are alike.
54600   **
54601   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
54602   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
54603   */
54604   leafCorrection = apOld[0]->leaf*4;
54605   leafData = apOld[0]->hasData;
54606   for(i=0; i<nOld; i++){
54607     int limit;
54608 
54609     /* Before doing anything else, take a copy of the i'th original sibling
54610     ** The rest of this function will use data from the copies rather
54611     ** that the original pages since the original pages will be in the
54612     ** process of being overwritten.  */
54613     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
54614     memcpy(pOld, apOld[i], sizeof(MemPage));
54615     pOld->aData = (void*)&pOld[1];
54616     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
54617 
54618     limit = pOld->nCell+pOld->nOverflow;
54619     if( pOld->nOverflow>0 ){
54620       for(j=0; j<limit; j++){
54621         assert( nCell<nMaxCells );
54622         apCell[nCell] = findOverflowCell(pOld, j);
54623         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54624         nCell++;
54625       }
54626     }else{
54627       u8 *aData = pOld->aData;
54628       u16 maskPage = pOld->maskPage;
54629       u16 cellOffset = pOld->cellOffset;
54630       for(j=0; j<limit; j++){
54631         assert( nCell<nMaxCells );
54632         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
54633         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54634         nCell++;
54635       }
54636     }
54637     if( i<nOld-1 && !leafData){
54638       u16 sz = (u16)szNew[i];
54639       u8 *pTemp;
54640       assert( nCell<nMaxCells );
54641       szCell[nCell] = sz;
54642       pTemp = &aSpace1[iSpace1];
54643       iSpace1 += sz;
54644       assert( sz<=pBt->maxLocal+23 );
54645       assert( iSpace1 <= (int)pBt->pageSize );
54646       memcpy(pTemp, apDiv[i], sz);
54647       apCell[nCell] = pTemp+leafCorrection;
54648       assert( leafCorrection==0 || leafCorrection==4 );
54649       szCell[nCell] = szCell[nCell] - leafCorrection;
54650       if( !pOld->leaf ){
54651         assert( leafCorrection==0 );
54652         assert( pOld->hdrOffset==0 );
54653         /* The right pointer of the child page pOld becomes the left
54654         ** pointer of the divider cell */
54655         memcpy(apCell[nCell], &pOld->aData[8], 4);
54656       }else{
54657         assert( leafCorrection==4 );
54658         if( szCell[nCell]<4 ){
54659           /* Do not allow any cells smaller than 4 bytes. */
54660           szCell[nCell] = 4;
54661         }
54662       }
54663       nCell++;
54664     }
54665   }
54666 
54667   /*
54668   ** Figure out the number of pages needed to hold all nCell cells.
54669   ** Store this number in "k".  Also compute szNew[] which is the total
54670   ** size of all cells on the i-th page and cntNew[] which is the index
54671   ** in apCell[] of the cell that divides page i from page i+1.
54672   ** cntNew[k] should equal nCell.
54673   **
54674   ** Values computed by this block:
54675   **
54676   **           k: The total number of sibling pages
54677   **    szNew[i]: Spaced used on the i-th sibling page.
54678   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
54679   **              the right of the i-th sibling page.
54680   ** usableSpace: Number of bytes of space available on each sibling.
54681   **
54682   */
54683   usableSpace = pBt->usableSize - 12 + leafCorrection;
54684   for(subtotal=k=i=0; i<nCell; i++){
54685     assert( i<nMaxCells );
54686     subtotal += szCell[i] + 2;
54687     if( subtotal > usableSpace ){
54688       szNew[k] = subtotal - szCell[i];
54689       cntNew[k] = i;
54690       if( leafData ){ i--; }
54691       subtotal = 0;
54692       k++;
54693       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
54694     }
54695   }
54696   szNew[k] = subtotal;
54697   cntNew[k] = nCell;
54698   k++;
54699 
54700   /*
54701   ** The packing computed by the previous block is biased toward the siblings
54702   ** on the left side.  The left siblings are always nearly full, while the
54703   ** right-most sibling might be nearly empty.  This block of code attempts
54704   ** to adjust the packing of siblings to get a better balance.
54705   **
54706   ** This adjustment is more than an optimization.  The packing above might
54707   ** be so out of balance as to be illegal.  For example, the right-most
54708   ** sibling might be completely empty.  This adjustment is not optional.
54709   */
54710   for(i=k-1; i>0; i--){
54711     int szRight = szNew[i];  /* Size of sibling on the right */
54712     int szLeft = szNew[i-1]; /* Size of sibling on the left */
54713     int r;              /* Index of right-most cell in left sibling */
54714     int d;              /* Index of first cell to the left of right sibling */
54715 
54716     r = cntNew[i-1] - 1;
54717     d = r + 1 - leafData;
54718     assert( d<nMaxCells );
54719     assert( r<nMaxCells );
54720     while( szRight==0
54721        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
54722     ){
54723       szRight += szCell[d] + 2;
54724       szLeft -= szCell[r] + 2;
54725       cntNew[i-1]--;
54726       r = cntNew[i-1] - 1;
54727       d = r + 1 - leafData;
54728     }
54729     szNew[i] = szRight;
54730     szNew[i-1] = szLeft;
54731   }
54732 
54733   /* Either we found one or more cells (cntnew[0])>0) or pPage is
54734   ** a virtual root page.  A virtual root page is when the real root
54735   ** page is page 1 and we are the only child of that page.
54736   **
54737   ** UPDATE:  The assert() below is not necessarily true if the database
54738   ** file is corrupt.  The corruption will be detected and reported later
54739   ** in this procedure so there is no need to act upon it now.
54740   */
54741 #if 0
54742   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
54743 #endif
54744 
54745   TRACE(("BALANCE: old: %d %d %d  ",
54746     apOld[0]->pgno,
54747     nOld>=2 ? apOld[1]->pgno : 0,
54748     nOld>=3 ? apOld[2]->pgno : 0
54749   ));
54750 
54751   /*
54752   ** Allocate k new pages.  Reuse old pages where possible.
54753   */
54754   if( apOld[0]->pgno<=1 ){
54755     rc = SQLITE_CORRUPT_BKPT;
54756     goto balance_cleanup;
54757   }
54758   pageFlags = apOld[0]->aData[0];
54759   for(i=0; i<k; i++){
54760     MemPage *pNew;
54761     if( i<nOld ){
54762       pNew = apNew[i] = apOld[i];
54763       apOld[i] = 0;
54764       rc = sqlite3PagerWrite(pNew->pDbPage);
54765       nNew++;
54766       if( rc ) goto balance_cleanup;
54767     }else{
54768       assert( i>0 );
54769       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
54770       if( rc ) goto balance_cleanup;
54771       apNew[i] = pNew;
54772       nNew++;
54773 
54774       /* Set the pointer-map entry for the new sibling page. */
54775       if( ISAUTOVACUUM ){
54776         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
54777         if( rc!=SQLITE_OK ){
54778           goto balance_cleanup;
54779         }
54780       }
54781     }
54782   }
54783 
54784   /* Free any old pages that were not reused as new pages.
54785   */
54786   while( i<nOld ){
54787     freePage(apOld[i], &rc);
54788     if( rc ) goto balance_cleanup;
54789     releasePage(apOld[i]);
54790     apOld[i] = 0;
54791     i++;
54792   }
54793 
54794   /*
54795   ** Put the new pages in accending order.  This helps to
54796   ** keep entries in the disk file in order so that a scan
54797   ** of the table is a linear scan through the file.  That
54798   ** in turn helps the operating system to deliver pages
54799   ** from the disk more rapidly.
54800   **
54801   ** An O(n^2) insertion sort algorithm is used, but since
54802   ** n is never more than NB (a small constant), that should
54803   ** not be a problem.
54804   **
54805   ** When NB==3, this one optimization makes the database
54806   ** about 25% faster for large insertions and deletions.
54807   */
54808   for(i=0; i<k-1; i++){
54809     int minV = apNew[i]->pgno;
54810     int minI = i;
54811     for(j=i+1; j<k; j++){
54812       if( apNew[j]->pgno<(unsigned)minV ){
54813         minI = j;
54814         minV = apNew[j]->pgno;
54815       }
54816     }
54817     if( minI>i ){
54818       MemPage *pT;
54819       pT = apNew[i];
54820       apNew[i] = apNew[minI];
54821       apNew[minI] = pT;
54822     }
54823   }
54824   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
54825     apNew[0]->pgno, szNew[0],
54826     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
54827     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
54828     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
54829     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
54830 
54831   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54832   put4byte(pRight, apNew[nNew-1]->pgno);
54833 
54834   /*
54835   ** Evenly distribute the data in apCell[] across the new pages.
54836   ** Insert divider cells into pParent as necessary.
54837   */
54838   j = 0;
54839   for(i=0; i<nNew; i++){
54840     /* Assemble the new sibling page. */
54841     MemPage *pNew = apNew[i];
54842     assert( j<nMaxCells );
54843     zeroPage(pNew, pageFlags);
54844     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
54845     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
54846     assert( pNew->nOverflow==0 );
54847 
54848     j = cntNew[i];
54849 
54850     /* If the sibling page assembled above was not the right-most sibling,
54851     ** insert a divider cell into the parent page.
54852     */
54853     assert( i<nNew-1 || j==nCell );
54854     if( j<nCell ){
54855       u8 *pCell;
54856       u8 *pTemp;
54857       int sz;
54858 
54859       assert( j<nMaxCells );
54860       pCell = apCell[j];
54861       sz = szCell[j] + leafCorrection;
54862       pTemp = &aOvflSpace[iOvflSpace];
54863       if( !pNew->leaf ){
54864         memcpy(&pNew->aData[8], pCell, 4);
54865       }else if( leafData ){
54866         /* If the tree is a leaf-data tree, and the siblings are leaves,
54867         ** then there is no divider cell in apCell[]. Instead, the divider
54868         ** cell consists of the integer key for the right-most cell of
54869         ** the sibling-page assembled above only.
54870         */
54871         CellInfo info;
54872         j--;
54873         btreeParseCellPtr(pNew, apCell[j], &info);
54874         pCell = pTemp;
54875         sz = 4 + putVarint(&pCell[4], info.nKey);
54876         pTemp = 0;
54877       }else{
54878         pCell -= 4;
54879         /* Obscure case for non-leaf-data trees: If the cell at pCell was
54880         ** previously stored on a leaf node, and its reported size was 4
54881         ** bytes, then it may actually be smaller than this
54882         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
54883         ** any cell). But it is important to pass the correct size to
54884         ** insertCell(), so reparse the cell now.
54885         **
54886         ** Note that this can never happen in an SQLite data file, as all
54887         ** cells are at least 4 bytes. It only happens in b-trees used
54888         ** to evaluate "IN (SELECT ...)" and similar clauses.
54889         */
54890         if( szCell[j]==4 ){
54891           assert(leafCorrection==4);
54892           sz = cellSizePtr(pParent, pCell);
54893         }
54894       }
54895       iOvflSpace += sz;
54896       assert( sz<=pBt->maxLocal+23 );
54897       assert( iOvflSpace <= (int)pBt->pageSize );
54898       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
54899       if( rc!=SQLITE_OK ) goto balance_cleanup;
54900       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54901 
54902       j++;
54903       nxDiv++;
54904     }
54905   }
54906   assert( j==nCell );
54907   assert( nOld>0 );
54908   assert( nNew>0 );
54909   if( (pageFlags & PTF_LEAF)==0 ){
54910     u8 *zChild = &apCopy[nOld-1]->aData[8];
54911     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
54912   }
54913 
54914   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
54915     /* The root page of the b-tree now contains no cells. The only sibling
54916     ** page is the right-child of the parent. Copy the contents of the
54917     ** child page into the parent, decreasing the overall height of the
54918     ** b-tree structure by one. This is described as the "balance-shallower"
54919     ** sub-algorithm in some documentation.
54920     **
54921     ** If this is an auto-vacuum database, the call to copyNodeContent()
54922     ** sets all pointer-map entries corresponding to database image pages
54923     ** for which the pointer is stored within the content being copied.
54924     **
54925     ** The second assert below verifies that the child page is defragmented
54926     ** (it must be, as it was just reconstructed using assemblePage()). This
54927     ** is important if the parent page happens to be page 1 of the database
54928     ** image.  */
54929     assert( nNew==1 );
54930     assert( apNew[0]->nFree ==
54931         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
54932     );
54933     copyNodeContent(apNew[0], pParent, &rc);
54934     freePage(apNew[0], &rc);
54935   }else if( ISAUTOVACUUM ){
54936     /* Fix the pointer-map entries for all the cells that were shifted around.
54937     ** There are several different types of pointer-map entries that need to
54938     ** be dealt with by this routine. Some of these have been set already, but
54939     ** many have not. The following is a summary:
54940     **
54941     **   1) The entries associated with new sibling pages that were not
54942     **      siblings when this function was called. These have already
54943     **      been set. We don't need to worry about old siblings that were
54944     **      moved to the free-list - the freePage() code has taken care
54945     **      of those.
54946     **
54947     **   2) The pointer-map entries associated with the first overflow
54948     **      page in any overflow chains used by new divider cells. These
54949     **      have also already been taken care of by the insertCell() code.
54950     **
54951     **   3) If the sibling pages are not leaves, then the child pages of
54952     **      cells stored on the sibling pages may need to be updated.
54953     **
54954     **   4) If the sibling pages are not internal intkey nodes, then any
54955     **      overflow pages used by these cells may need to be updated
54956     **      (internal intkey nodes never contain pointers to overflow pages).
54957     **
54958     **   5) If the sibling pages are not leaves, then the pointer-map
54959     **      entries for the right-child pages of each sibling may need
54960     **      to be updated.
54961     **
54962     ** Cases 1 and 2 are dealt with above by other code. The next
54963     ** block deals with cases 3 and 4 and the one after that, case 5. Since
54964     ** setting a pointer map entry is a relatively expensive operation, this
54965     ** code only sets pointer map entries for child or overflow pages that have
54966     ** actually moved between pages.  */
54967     MemPage *pNew = apNew[0];
54968     MemPage *pOld = apCopy[0];
54969     int nOverflow = pOld->nOverflow;
54970     int iNextOld = pOld->nCell + nOverflow;
54971     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
54972     j = 0;                             /* Current 'old' sibling page */
54973     k = 0;                             /* Current 'new' sibling page */
54974     for(i=0; i<nCell; i++){
54975       int isDivider = 0;
54976       while( i==iNextOld ){
54977         /* Cell i is the cell immediately following the last cell on old
54978         ** sibling page j. If the siblings are not leaf pages of an
54979         ** intkey b-tree, then cell i was a divider cell. */
54980         assert( j+1 < ArraySize(apCopy) );
54981         assert( j+1 < nOld );
54982         pOld = apCopy[++j];
54983         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
54984         if( pOld->nOverflow ){
54985           nOverflow = pOld->nOverflow;
54986           iOverflow = i + !leafData + pOld->aiOvfl[0];
54987         }
54988         isDivider = !leafData;
54989       }
54990 
54991       assert(nOverflow>0 || iOverflow<i );
54992       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
54993       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
54994       if( i==iOverflow ){
54995         isDivider = 1;
54996         if( (--nOverflow)>0 ){
54997           iOverflow++;
54998         }
54999       }
55000 
55001       if( i==cntNew[k] ){
55002         /* Cell i is the cell immediately following the last cell on new
55003         ** sibling page k. If the siblings are not leaf pages of an
55004         ** intkey b-tree, then cell i is a divider cell.  */
55005         pNew = apNew[++k];
55006         if( !leafData ) continue;
55007       }
55008       assert( j<nOld );
55009       assert( k<nNew );
55010 
55011       /* If the cell was originally divider cell (and is not now) or
55012       ** an overflow cell, or if the cell was located on a different sibling
55013       ** page before the balancing, then the pointer map entries associated
55014       ** with any child or overflow pages need to be updated.  */
55015       if( isDivider || pOld->pgno!=pNew->pgno ){
55016         if( !leafCorrection ){
55017           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
55018         }
55019         if( szCell[i]>pNew->minLocal ){
55020           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
55021         }
55022       }
55023     }
55024 
55025     if( !leafCorrection ){
55026       for(i=0; i<nNew; i++){
55027         u32 key = get4byte(&apNew[i]->aData[8]);
55028         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
55029       }
55030     }
55031 
55032 #if 0
55033     /* The ptrmapCheckPages() contains assert() statements that verify that
55034     ** all pointer map pages are set correctly. This is helpful while
55035     ** debugging. This is usually disabled because a corrupt database may
55036     ** cause an assert() statement to fail.  */
55037     ptrmapCheckPages(apNew, nNew);
55038     ptrmapCheckPages(&pParent, 1);
55039 #endif
55040   }
55041 
55042   assert( pParent->isInit );
55043   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
55044           nOld, nNew, nCell));
55045 
55046   /*
55047   ** Cleanup before returning.
55048   */
55049 balance_cleanup:
55050   sqlite3ScratchFree(apCell);
55051   for(i=0; i<nOld; i++){
55052     releasePage(apOld[i]);
55053   }
55054   for(i=0; i<nNew; i++){
55055     releasePage(apNew[i]);
55056   }
55057 
55058   return rc;
55059 }
55060 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
55061 #pragma optimize("", on)
55062 #endif
55063 
55064 
55065 /*
55066 ** This function is called when the root page of a b-tree structure is
55067 ** overfull (has one or more overflow pages).
55068 **
55069 ** A new child page is allocated and the contents of the current root
55070 ** page, including overflow cells, are copied into the child. The root
55071 ** page is then overwritten to make it an empty page with the right-child
55072 ** pointer pointing to the new page.
55073 **
55074 ** Before returning, all pointer-map entries corresponding to pages
55075 ** that the new child-page now contains pointers to are updated. The
55076 ** entry corresponding to the new right-child pointer of the root
55077 ** page is also updated.
55078 **
55079 ** If successful, *ppChild is set to contain a reference to the child
55080 ** page and SQLITE_OK is returned. In this case the caller is required
55081 ** to call releasePage() on *ppChild exactly once. If an error occurs,
55082 ** an error code is returned and *ppChild is set to 0.
55083 */
55084 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
55085   int rc;                        /* Return value from subprocedures */
55086   MemPage *pChild = 0;           /* Pointer to a new child page */
55087   Pgno pgnoChild = 0;            /* Page number of the new child page */
55088   BtShared *pBt = pRoot->pBt;    /* The BTree */
55089 
55090   assert( pRoot->nOverflow>0 );
55091   assert( sqlite3_mutex_held(pBt->mutex) );
55092 
55093   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
55094   ** page that will become the new right-child of pPage. Copy the contents
55095   ** of the node stored on pRoot into the new child page.
55096   */
55097   rc = sqlite3PagerWrite(pRoot->pDbPage);
55098   if( rc==SQLITE_OK ){
55099     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
55100     copyNodeContent(pRoot, pChild, &rc);
55101     if( ISAUTOVACUUM ){
55102       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
55103     }
55104   }
55105   if( rc ){
55106     *ppChild = 0;
55107     releasePage(pChild);
55108     return rc;
55109   }
55110   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
55111   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55112   assert( pChild->nCell==pRoot->nCell );
55113 
55114   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
55115 
55116   /* Copy the overflow cells from pRoot to pChild */
55117   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
55118          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
55119   memcpy(pChild->apOvfl, pRoot->apOvfl,
55120          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
55121   pChild->nOverflow = pRoot->nOverflow;
55122 
55123   /* Zero the contents of pRoot. Then install pChild as the right-child. */
55124   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
55125   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
55126 
55127   *ppChild = pChild;
55128   return SQLITE_OK;
55129 }
55130 
55131 /*
55132 ** The page that pCur currently points to has just been modified in
55133 ** some way. This function figures out if this modification means the
55134 ** tree needs to be balanced, and if so calls the appropriate balancing
55135 ** routine. Balancing routines are:
55136 **
55137 **   balance_quick()
55138 **   balance_deeper()
55139 **   balance_nonroot()
55140 */
55141 static int balance(BtCursor *pCur){
55142   int rc = SQLITE_OK;
55143   const int nMin = pCur->pBt->usableSize * 2 / 3;
55144   u8 aBalanceQuickSpace[13];
55145   u8 *pFree = 0;
55146 
55147   TESTONLY( int balance_quick_called = 0 );
55148   TESTONLY( int balance_deeper_called = 0 );
55149 
55150   do {
55151     int iPage = pCur->iPage;
55152     MemPage *pPage = pCur->apPage[iPage];
55153 
55154     if( iPage==0 ){
55155       if( pPage->nOverflow ){
55156         /* The root page of the b-tree is overfull. In this case call the
55157         ** balance_deeper() function to create a new child for the root-page
55158         ** and copy the current contents of the root-page to it. The
55159         ** next iteration of the do-loop will balance the child page.
55160         */
55161         assert( (balance_deeper_called++)==0 );
55162         rc = balance_deeper(pPage, &pCur->apPage[1]);
55163         if( rc==SQLITE_OK ){
55164           pCur->iPage = 1;
55165           pCur->aiIdx[0] = 0;
55166           pCur->aiIdx[1] = 0;
55167           assert( pCur->apPage[1]->nOverflow );
55168         }
55169       }else{
55170         break;
55171       }
55172     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
55173       break;
55174     }else{
55175       MemPage * const pParent = pCur->apPage[iPage-1];
55176       int const iIdx = pCur->aiIdx[iPage-1];
55177 
55178       rc = sqlite3PagerWrite(pParent->pDbPage);
55179       if( rc==SQLITE_OK ){
55180 #ifndef SQLITE_OMIT_QUICKBALANCE
55181         if( pPage->hasData
55182          && pPage->nOverflow==1
55183          && pPage->aiOvfl[0]==pPage->nCell
55184          && pParent->pgno!=1
55185          && pParent->nCell==iIdx
55186         ){
55187           /* Call balance_quick() to create a new sibling of pPage on which
55188           ** to store the overflow cell. balance_quick() inserts a new cell
55189           ** into pParent, which may cause pParent overflow. If this
55190           ** happens, the next interation of the do-loop will balance pParent
55191           ** use either balance_nonroot() or balance_deeper(). Until this
55192           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
55193           ** buffer.
55194           **
55195           ** The purpose of the following assert() is to check that only a
55196           ** single call to balance_quick() is made for each call to this
55197           ** function. If this were not verified, a subtle bug involving reuse
55198           ** of the aBalanceQuickSpace[] might sneak in.
55199           */
55200           assert( (balance_quick_called++)==0 );
55201           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
55202         }else
55203 #endif
55204         {
55205           /* In this case, call balance_nonroot() to redistribute cells
55206           ** between pPage and up to 2 of its sibling pages. This involves
55207           ** modifying the contents of pParent, which may cause pParent to
55208           ** become overfull or underfull. The next iteration of the do-loop
55209           ** will balance the parent page to correct this.
55210           **
55211           ** If the parent page becomes overfull, the overflow cell or cells
55212           ** are stored in the pSpace buffer allocated immediately below.
55213           ** A subsequent iteration of the do-loop will deal with this by
55214           ** calling balance_nonroot() (balance_deeper() may be called first,
55215           ** but it doesn't deal with overflow cells - just moves them to a
55216           ** different page). Once this subsequent call to balance_nonroot()
55217           ** has completed, it is safe to release the pSpace buffer used by
55218           ** the previous call, as the overflow cell data will have been
55219           ** copied either into the body of a database page or into the new
55220           ** pSpace buffer passed to the latter call to balance_nonroot().
55221           */
55222           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
55223           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
55224           if( pFree ){
55225             /* If pFree is not NULL, it points to the pSpace buffer used
55226             ** by a previous call to balance_nonroot(). Its contents are
55227             ** now stored either on real database pages or within the
55228             ** new pSpace buffer, so it may be safely freed here. */
55229             sqlite3PageFree(pFree);
55230           }
55231 
55232           /* The pSpace buffer will be freed after the next call to
55233           ** balance_nonroot(), or just before this function returns, whichever
55234           ** comes first. */
55235           pFree = pSpace;
55236         }
55237       }
55238 
55239       pPage->nOverflow = 0;
55240 
55241       /* The next iteration of the do-loop balances the parent page. */
55242       releasePage(pPage);
55243       pCur->iPage--;
55244     }
55245   }while( rc==SQLITE_OK );
55246 
55247   if( pFree ){
55248     sqlite3PageFree(pFree);
55249   }
55250   return rc;
55251 }
55252 
55253 
55254 /*
55255 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
55256 ** and the data is given by (pData,nData).  The cursor is used only to
55257 ** define what table the record should be inserted into.  The cursor
55258 ** is left pointing at a random location.
55259 **
55260 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
55261 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
55262 **
55263 ** If the seekResult parameter is non-zero, then a successful call to
55264 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
55265 ** been performed. seekResult is the search result returned (a negative
55266 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
55267 ** a positive value if pCur points at an etry that is larger than
55268 ** (pKey, nKey)).
55269 **
55270 ** If the seekResult parameter is non-zero, then the caller guarantees that
55271 ** cursor pCur is pointing at the existing copy of a row that is to be
55272 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
55273 ** point to any entry or to no entry at all and so this function has to seek
55274 ** the cursor before the new key can be inserted.
55275 */
55276 SQLITE_PRIVATE int sqlite3BtreeInsert(
55277   BtCursor *pCur,                /* Insert data into the table of this cursor */
55278   const void *pKey, i64 nKey,    /* The key of the new record */
55279   const void *pData, int nData,  /* The data of the new record */
55280   int nZero,                     /* Number of extra 0 bytes to append to data */
55281   int appendBias,                /* True if this is likely an append */
55282   int seekResult                 /* Result of prior MovetoUnpacked() call */
55283 ){
55284   int rc;
55285   int loc = seekResult;          /* -1: before desired location  +1: after */
55286   int szNew = 0;
55287   int idx;
55288   MemPage *pPage;
55289   Btree *p = pCur->pBtree;
55290   BtShared *pBt = p->pBt;
55291   unsigned char *oldCell;
55292   unsigned char *newCell = 0;
55293 
55294   if( pCur->eState==CURSOR_FAULT ){
55295     assert( pCur->skipNext!=SQLITE_OK );
55296     return pCur->skipNext;
55297   }
55298 
55299   assert( cursorHoldsMutex(pCur) );
55300   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
55301               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
55302   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55303 
55304   /* Assert that the caller has been consistent. If this cursor was opened
55305   ** expecting an index b-tree, then the caller should be inserting blob
55306   ** keys with no associated data. If the cursor was opened expecting an
55307   ** intkey table, the caller should be inserting integer keys with a
55308   ** blob of associated data.  */
55309   assert( (pKey==0)==(pCur->pKeyInfo==0) );
55310 
55311   /* Save the positions of any other cursors open on this table.
55312   **
55313   ** In some cases, the call to btreeMoveto() below is a no-op. For
55314   ** example, when inserting data into a table with auto-generated integer
55315   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
55316   ** integer key to use. It then calls this function to actually insert the
55317   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
55318   ** that the cursor is already where it needs to be and returns without
55319   ** doing any work. To avoid thwarting these optimizations, it is important
55320   ** not to clear the cursor here.
55321   */
55322   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55323   if( rc ) return rc;
55324 
55325   /* If this is an insert into a table b-tree, invalidate any incrblob
55326   ** cursors open on the row being replaced (assuming this is a replace
55327   ** operation - if it is not, the following is a no-op).  */
55328   if( pCur->pKeyInfo==0 ){
55329     invalidateIncrblobCursors(p, nKey, 0);
55330   }
55331 
55332   if( !loc ){
55333     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
55334     if( rc ) return rc;
55335   }
55336   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
55337 
55338   pPage = pCur->apPage[pCur->iPage];
55339   assert( pPage->intKey || nKey>=0 );
55340   assert( pPage->leaf || !pPage->intKey );
55341 
55342   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
55343           pCur->pgnoRoot, nKey, nData, pPage->pgno,
55344           loc==0 ? "overwrite" : "new entry"));
55345   assert( pPage->isInit );
55346   allocateTempSpace(pBt);
55347   newCell = pBt->pTmpSpace;
55348   if( newCell==0 ) return SQLITE_NOMEM;
55349   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
55350   if( rc ) goto end_insert;
55351   assert( szNew==cellSizePtr(pPage, newCell) );
55352   assert( szNew <= MX_CELL_SIZE(pBt) );
55353   idx = pCur->aiIdx[pCur->iPage];
55354   if( loc==0 ){
55355     u16 szOld;
55356     assert( idx<pPage->nCell );
55357     rc = sqlite3PagerWrite(pPage->pDbPage);
55358     if( rc ){
55359       goto end_insert;
55360     }
55361     oldCell = findCell(pPage, idx);
55362     if( !pPage->leaf ){
55363       memcpy(newCell, oldCell, 4);
55364     }
55365     szOld = cellSizePtr(pPage, oldCell);
55366     rc = clearCell(pPage, oldCell);
55367     dropCell(pPage, idx, szOld, &rc);
55368     if( rc ) goto end_insert;
55369   }else if( loc<0 && pPage->nCell>0 ){
55370     assert( pPage->leaf );
55371     idx = ++pCur->aiIdx[pCur->iPage];
55372   }else{
55373     assert( pPage->leaf );
55374   }
55375   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
55376   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
55377 
55378   /* If no error has occurred and pPage has an overflow cell, call balance()
55379   ** to redistribute the cells within the tree. Since balance() may move
55380   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
55381   ** variables.
55382   **
55383   ** Previous versions of SQLite called moveToRoot() to move the cursor
55384   ** back to the root page as balance() used to invalidate the contents
55385   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
55386   ** set the cursor state to "invalid". This makes common insert operations
55387   ** slightly faster.
55388   **
55389   ** There is a subtle but important optimization here too. When inserting
55390   ** multiple records into an intkey b-tree using a single cursor (as can
55391   ** happen while processing an "INSERT INTO ... SELECT" statement), it
55392   ** is advantageous to leave the cursor pointing to the last entry in
55393   ** the b-tree if possible. If the cursor is left pointing to the last
55394   ** entry in the table, and the next row inserted has an integer key
55395   ** larger than the largest existing key, it is possible to insert the
55396   ** row without seeking the cursor. This can be a big performance boost.
55397   */
55398   pCur->info.nSize = 0;
55399   pCur->validNKey = 0;
55400   if( rc==SQLITE_OK && pPage->nOverflow ){
55401     rc = balance(pCur);
55402 
55403     /* Must make sure nOverflow is reset to zero even if the balance()
55404     ** fails. Internal data structure corruption will result otherwise.
55405     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
55406     ** from trying to save the current position of the cursor.  */
55407     pCur->apPage[pCur->iPage]->nOverflow = 0;
55408     pCur->eState = CURSOR_INVALID;
55409   }
55410   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
55411 
55412 end_insert:
55413   return rc;
55414 }
55415 
55416 /*
55417 ** Delete the entry that the cursor is pointing to.  The cursor
55418 ** is left pointing at a arbitrary location.
55419 */
55420 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
55421   Btree *p = pCur->pBtree;
55422   BtShared *pBt = p->pBt;
55423   int rc;                              /* Return code */
55424   MemPage *pPage;                      /* Page to delete cell from */
55425   unsigned char *pCell;                /* Pointer to cell to delete */
55426   int iCellIdx;                        /* Index of cell to delete */
55427   int iCellDepth;                      /* Depth of node containing pCell */
55428 
55429   assert( cursorHoldsMutex(pCur) );
55430   assert( pBt->inTransaction==TRANS_WRITE );
55431   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55432   assert( pCur->wrFlag );
55433   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55434   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
55435 
55436   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
55437    || NEVER(pCur->eState!=CURSOR_VALID)
55438   ){
55439     return SQLITE_ERROR;  /* Something has gone awry. */
55440   }
55441 
55442   iCellDepth = pCur->iPage;
55443   iCellIdx = pCur->aiIdx[iCellDepth];
55444   pPage = pCur->apPage[iCellDepth];
55445   pCell = findCell(pPage, iCellIdx);
55446 
55447   /* If the page containing the entry to delete is not a leaf page, move
55448   ** the cursor to the largest entry in the tree that is smaller than
55449   ** the entry being deleted. This cell will replace the cell being deleted
55450   ** from the internal node. The 'previous' entry is used for this instead
55451   ** of the 'next' entry, as the previous entry is always a part of the
55452   ** sub-tree headed by the child page of the cell being deleted. This makes
55453   ** balancing the tree following the delete operation easier.  */
55454   if( !pPage->leaf ){
55455     int notUsed;
55456     rc = sqlite3BtreePrevious(pCur, &notUsed);
55457     if( rc ) return rc;
55458   }
55459 
55460   /* Save the positions of any other cursors open on this table before
55461   ** making any modifications. Make the page containing the entry to be
55462   ** deleted writable. Then free any overflow pages associated with the
55463   ** entry and finally remove the cell itself from within the page.
55464   */
55465   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55466   if( rc ) return rc;
55467 
55468   /* If this is a delete operation to remove a row from a table b-tree,
55469   ** invalidate any incrblob cursors open on the row being deleted.  */
55470   if( pCur->pKeyInfo==0 ){
55471     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
55472   }
55473 
55474   rc = sqlite3PagerWrite(pPage->pDbPage);
55475   if( rc ) return rc;
55476   rc = clearCell(pPage, pCell);
55477   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
55478   if( rc ) return rc;
55479 
55480   /* If the cell deleted was not located on a leaf page, then the cursor
55481   ** is currently pointing to the largest entry in the sub-tree headed
55482   ** by the child-page of the cell that was just deleted from an internal
55483   ** node. The cell from the leaf node needs to be moved to the internal
55484   ** node to replace the deleted cell.  */
55485   if( !pPage->leaf ){
55486     MemPage *pLeaf = pCur->apPage[pCur->iPage];
55487     int nCell;
55488     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
55489     unsigned char *pTmp;
55490 
55491     pCell = findCell(pLeaf, pLeaf->nCell-1);
55492     nCell = cellSizePtr(pLeaf, pCell);
55493     assert( MX_CELL_SIZE(pBt) >= nCell );
55494 
55495     allocateTempSpace(pBt);
55496     pTmp = pBt->pTmpSpace;
55497 
55498     rc = sqlite3PagerWrite(pLeaf->pDbPage);
55499     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
55500     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
55501     if( rc ) return rc;
55502   }
55503 
55504   /* Balance the tree. If the entry deleted was located on a leaf page,
55505   ** then the cursor still points to that page. In this case the first
55506   ** call to balance() repairs the tree, and the if(...) condition is
55507   ** never true.
55508   **
55509   ** Otherwise, if the entry deleted was on an internal node page, then
55510   ** pCur is pointing to the leaf page from which a cell was removed to
55511   ** replace the cell deleted from the internal node. This is slightly
55512   ** tricky as the leaf node may be underfull, and the internal node may
55513   ** be either under or overfull. In this case run the balancing algorithm
55514   ** on the leaf node first. If the balance proceeds far enough up the
55515   ** tree that we can be sure that any problem in the internal node has
55516   ** been corrected, so be it. Otherwise, after balancing the leaf node,
55517   ** walk the cursor up the tree to the internal node and balance it as
55518   ** well.  */
55519   rc = balance(pCur);
55520   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
55521     while( pCur->iPage>iCellDepth ){
55522       releasePage(pCur->apPage[pCur->iPage--]);
55523     }
55524     rc = balance(pCur);
55525   }
55526 
55527   if( rc==SQLITE_OK ){
55528     moveToRoot(pCur);
55529   }
55530   return rc;
55531 }
55532 
55533 /*
55534 ** Create a new BTree table.  Write into *piTable the page
55535 ** number for the root page of the new table.
55536 **
55537 ** The type of type is determined by the flags parameter.  Only the
55538 ** following values of flags are currently in use.  Other values for
55539 ** flags might not work:
55540 **
55541 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
55542 **     BTREE_ZERODATA                  Used for SQL indices
55543 */
55544 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
55545   BtShared *pBt = p->pBt;
55546   MemPage *pRoot;
55547   Pgno pgnoRoot;
55548   int rc;
55549   int ptfFlags;          /* Page-type flage for the root page of new table */
55550 
55551   assert( sqlite3BtreeHoldsMutex(p) );
55552   assert( pBt->inTransaction==TRANS_WRITE );
55553   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55554 
55555 #ifdef SQLITE_OMIT_AUTOVACUUM
55556   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55557   if( rc ){
55558     return rc;
55559   }
55560 #else
55561   if( pBt->autoVacuum ){
55562     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
55563     MemPage *pPageMove; /* The page to move to. */
55564 
55565     /* Creating a new table may probably require moving an existing database
55566     ** to make room for the new tables root page. In case this page turns
55567     ** out to be an overflow page, delete all overflow page-map caches
55568     ** held by open cursors.
55569     */
55570     invalidateAllOverflowCache(pBt);
55571 
55572     /* Read the value of meta[3] from the database to determine where the
55573     ** root page of the new table should go. meta[3] is the largest root-page
55574     ** created so far, so the new root-page is (meta[3]+1).
55575     */
55576     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
55577     pgnoRoot++;
55578 
55579     /* The new root-page may not be allocated on a pointer-map page, or the
55580     ** PENDING_BYTE page.
55581     */
55582     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
55583         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
55584       pgnoRoot++;
55585     }
55586     assert( pgnoRoot>=3 );
55587 
55588     /* Allocate a page. The page that currently resides at pgnoRoot will
55589     ** be moved to the allocated page (unless the allocated page happens
55590     ** to reside at pgnoRoot).
55591     */
55592     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
55593     if( rc!=SQLITE_OK ){
55594       return rc;
55595     }
55596 
55597     if( pgnoMove!=pgnoRoot ){
55598       /* pgnoRoot is the page that will be used for the root-page of
55599       ** the new table (assuming an error did not occur). But we were
55600       ** allocated pgnoMove. If required (i.e. if it was not allocated
55601       ** by extending the file), the current page at position pgnoMove
55602       ** is already journaled.
55603       */
55604       u8 eType = 0;
55605       Pgno iPtrPage = 0;
55606 
55607       releasePage(pPageMove);
55608 
55609       /* Move the page currently at pgnoRoot to pgnoMove. */
55610       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55611       if( rc!=SQLITE_OK ){
55612         return rc;
55613       }
55614       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
55615       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
55616         rc = SQLITE_CORRUPT_BKPT;
55617       }
55618       if( rc!=SQLITE_OK ){
55619         releasePage(pRoot);
55620         return rc;
55621       }
55622       assert( eType!=PTRMAP_ROOTPAGE );
55623       assert( eType!=PTRMAP_FREEPAGE );
55624       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
55625       releasePage(pRoot);
55626 
55627       /* Obtain the page at pgnoRoot */
55628       if( rc!=SQLITE_OK ){
55629         return rc;
55630       }
55631       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55632       if( rc!=SQLITE_OK ){
55633         return rc;
55634       }
55635       rc = sqlite3PagerWrite(pRoot->pDbPage);
55636       if( rc!=SQLITE_OK ){
55637         releasePage(pRoot);
55638         return rc;
55639       }
55640     }else{
55641       pRoot = pPageMove;
55642     }
55643 
55644     /* Update the pointer-map and meta-data with the new root-page number. */
55645     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
55646     if( rc ){
55647       releasePage(pRoot);
55648       return rc;
55649     }
55650 
55651     /* When the new root page was allocated, page 1 was made writable in
55652     ** order either to increase the database filesize, or to decrement the
55653     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
55654     */
55655     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
55656     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
55657     if( NEVER(rc) ){
55658       releasePage(pRoot);
55659       return rc;
55660     }
55661 
55662   }else{
55663     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55664     if( rc ) return rc;
55665   }
55666 #endif
55667   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55668   if( createTabFlags & BTREE_INTKEY ){
55669     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
55670   }else{
55671     ptfFlags = PTF_ZERODATA | PTF_LEAF;
55672   }
55673   zeroPage(pRoot, ptfFlags);
55674   sqlite3PagerUnref(pRoot->pDbPage);
55675   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
55676   *piTable = (int)pgnoRoot;
55677   return SQLITE_OK;
55678 }
55679 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
55680   int rc;
55681   sqlite3BtreeEnter(p);
55682   rc = btreeCreateTable(p, piTable, flags);
55683   sqlite3BtreeLeave(p);
55684   return rc;
55685 }
55686 
55687 /*
55688 ** Erase the given database page and all its children.  Return
55689 ** the page to the freelist.
55690 */
55691 static int clearDatabasePage(
55692   BtShared *pBt,           /* The BTree that contains the table */
55693   Pgno pgno,               /* Page number to clear */
55694   int freePageFlag,        /* Deallocate page if true */
55695   int *pnChange            /* Add number of Cells freed to this counter */
55696 ){
55697   MemPage *pPage;
55698   int rc;
55699   unsigned char *pCell;
55700   int i;
55701 
55702   assert( sqlite3_mutex_held(pBt->mutex) );
55703   if( pgno>btreePagecount(pBt) ){
55704     return SQLITE_CORRUPT_BKPT;
55705   }
55706 
55707   rc = getAndInitPage(pBt, pgno, &pPage);
55708   if( rc ) return rc;
55709   for(i=0; i<pPage->nCell; i++){
55710     pCell = findCell(pPage, i);
55711     if( !pPage->leaf ){
55712       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
55713       if( rc ) goto cleardatabasepage_out;
55714     }
55715     rc = clearCell(pPage, pCell);
55716     if( rc ) goto cleardatabasepage_out;
55717   }
55718   if( !pPage->leaf ){
55719     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
55720     if( rc ) goto cleardatabasepage_out;
55721   }else if( pnChange ){
55722     assert( pPage->intKey );
55723     *pnChange += pPage->nCell;
55724   }
55725   if( freePageFlag ){
55726     freePage(pPage, &rc);
55727   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
55728     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
55729   }
55730 
55731 cleardatabasepage_out:
55732   releasePage(pPage);
55733   return rc;
55734 }
55735 
55736 /*
55737 ** Delete all information from a single table in the database.  iTable is
55738 ** the page number of the root of the table.  After this routine returns,
55739 ** the root page is empty, but still exists.
55740 **
55741 ** This routine will fail with SQLITE_LOCKED if there are any open
55742 ** read cursors on the table.  Open write cursors are moved to the
55743 ** root of the table.
55744 **
55745 ** If pnChange is not NULL, then table iTable must be an intkey table. The
55746 ** integer value pointed to by pnChange is incremented by the number of
55747 ** entries in the table.
55748 */
55749 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
55750   int rc;
55751   BtShared *pBt = p->pBt;
55752   sqlite3BtreeEnter(p);
55753   assert( p->inTrans==TRANS_WRITE );
55754 
55755   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
55756 
55757   if( SQLITE_OK==rc ){
55758     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
55759     ** is the root of a table b-tree - if it is not, the following call is
55760     ** a no-op).  */
55761     invalidateIncrblobCursors(p, 0, 1);
55762     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
55763   }
55764   sqlite3BtreeLeave(p);
55765   return rc;
55766 }
55767 
55768 /*
55769 ** Erase all information in a table and add the root of the table to
55770 ** the freelist.  Except, the root of the principle table (the one on
55771 ** page 1) is never added to the freelist.
55772 **
55773 ** This routine will fail with SQLITE_LOCKED if there are any open
55774 ** cursors on the table.
55775 **
55776 ** If AUTOVACUUM is enabled and the page at iTable is not the last
55777 ** root page in the database file, then the last root page
55778 ** in the database file is moved into the slot formerly occupied by
55779 ** iTable and that last slot formerly occupied by the last root page
55780 ** is added to the freelist instead of iTable.  In this say, all
55781 ** root pages are kept at the beginning of the database file, which
55782 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
55783 ** page number that used to be the last root page in the file before
55784 ** the move.  If no page gets moved, *piMoved is set to 0.
55785 ** The last root page is recorded in meta[3] and the value of
55786 ** meta[3] is updated by this procedure.
55787 */
55788 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
55789   int rc;
55790   MemPage *pPage = 0;
55791   BtShared *pBt = p->pBt;
55792 
55793   assert( sqlite3BtreeHoldsMutex(p) );
55794   assert( p->inTrans==TRANS_WRITE );
55795 
55796   /* It is illegal to drop a table if any cursors are open on the
55797   ** database. This is because in auto-vacuum mode the backend may
55798   ** need to move another root-page to fill a gap left by the deleted
55799   ** root page. If an open cursor was using this page a problem would
55800   ** occur.
55801   **
55802   ** This error is caught long before control reaches this point.
55803   */
55804   if( NEVER(pBt->pCursor) ){
55805     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
55806     return SQLITE_LOCKED_SHAREDCACHE;
55807   }
55808 
55809   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
55810   if( rc ) return rc;
55811   rc = sqlite3BtreeClearTable(p, iTable, 0);
55812   if( rc ){
55813     releasePage(pPage);
55814     return rc;
55815   }
55816 
55817   *piMoved = 0;
55818 
55819   if( iTable>1 ){
55820 #ifdef SQLITE_OMIT_AUTOVACUUM
55821     freePage(pPage, &rc);
55822     releasePage(pPage);
55823 #else
55824     if( pBt->autoVacuum ){
55825       Pgno maxRootPgno;
55826       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
55827 
55828       if( iTable==maxRootPgno ){
55829         /* If the table being dropped is the table with the largest root-page
55830         ** number in the database, put the root page on the free list.
55831         */
55832         freePage(pPage, &rc);
55833         releasePage(pPage);
55834         if( rc!=SQLITE_OK ){
55835           return rc;
55836         }
55837       }else{
55838         /* The table being dropped does not have the largest root-page
55839         ** number in the database. So move the page that does into the
55840         ** gap left by the deleted root-page.
55841         */
55842         MemPage *pMove;
55843         releasePage(pPage);
55844         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55845         if( rc!=SQLITE_OK ){
55846           return rc;
55847         }
55848         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
55849         releasePage(pMove);
55850         if( rc!=SQLITE_OK ){
55851           return rc;
55852         }
55853         pMove = 0;
55854         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55855         freePage(pMove, &rc);
55856         releasePage(pMove);
55857         if( rc!=SQLITE_OK ){
55858           return rc;
55859         }
55860         *piMoved = maxRootPgno;
55861       }
55862 
55863       /* Set the new 'max-root-page' value in the database header. This
55864       ** is the old value less one, less one more if that happens to
55865       ** be a root-page number, less one again if that is the
55866       ** PENDING_BYTE_PAGE.
55867       */
55868       maxRootPgno--;
55869       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
55870              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
55871         maxRootPgno--;
55872       }
55873       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
55874 
55875       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
55876     }else{
55877       freePage(pPage, &rc);
55878       releasePage(pPage);
55879     }
55880 #endif
55881   }else{
55882     /* If sqlite3BtreeDropTable was called on page 1.
55883     ** This really never should happen except in a corrupt
55884     ** database.
55885     */
55886     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
55887     releasePage(pPage);
55888   }
55889   return rc;
55890 }
55891 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
55892   int rc;
55893   sqlite3BtreeEnter(p);
55894   rc = btreeDropTable(p, iTable, piMoved);
55895   sqlite3BtreeLeave(p);
55896   return rc;
55897 }
55898 
55899 
55900 /*
55901 ** This function may only be called if the b-tree connection already
55902 ** has a read or write transaction open on the database.
55903 **
55904 ** Read the meta-information out of a database file.  Meta[0]
55905 ** is the number of free pages currently in the database.  Meta[1]
55906 ** through meta[15] are available for use by higher layers.  Meta[0]
55907 ** is read-only, the others are read/write.
55908 **
55909 ** The schema layer numbers meta values differently.  At the schema
55910 ** layer (and the SetCookie and ReadCookie opcodes) the number of
55911 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
55912 */
55913 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
55914   BtShared *pBt = p->pBt;
55915 
55916   sqlite3BtreeEnter(p);
55917   assert( p->inTrans>TRANS_NONE );
55918   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
55919   assert( pBt->pPage1 );
55920   assert( idx>=0 && idx<=15 );
55921 
55922   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
55923 
55924   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
55925   ** database, mark the database as read-only.  */
55926 #ifdef SQLITE_OMIT_AUTOVACUUM
55927   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
55928     pBt->btsFlags |= BTS_READ_ONLY;
55929   }
55930 #endif
55931 
55932   sqlite3BtreeLeave(p);
55933 }
55934 
55935 /*
55936 ** Write meta-information back into the database.  Meta[0] is
55937 ** read-only and may not be written.
55938 */
55939 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
55940   BtShared *pBt = p->pBt;
55941   unsigned char *pP1;
55942   int rc;
55943   assert( idx>=1 && idx<=15 );
55944   sqlite3BtreeEnter(p);
55945   assert( p->inTrans==TRANS_WRITE );
55946   assert( pBt->pPage1!=0 );
55947   pP1 = pBt->pPage1->aData;
55948   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55949   if( rc==SQLITE_OK ){
55950     put4byte(&pP1[36 + idx*4], iMeta);
55951 #ifndef SQLITE_OMIT_AUTOVACUUM
55952     if( idx==BTREE_INCR_VACUUM ){
55953       assert( pBt->autoVacuum || iMeta==0 );
55954       assert( iMeta==0 || iMeta==1 );
55955       pBt->incrVacuum = (u8)iMeta;
55956     }
55957 #endif
55958   }
55959   sqlite3BtreeLeave(p);
55960   return rc;
55961 }
55962 
55963 #ifndef SQLITE_OMIT_BTREECOUNT
55964 /*
55965 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
55966 ** number of entries in the b-tree and write the result to *pnEntry.
55967 **
55968 ** SQLITE_OK is returned if the operation is successfully executed.
55969 ** Otherwise, if an error is encountered (i.e. an IO error or database
55970 ** corruption) an SQLite error code is returned.
55971 */
55972 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
55973   i64 nEntry = 0;                      /* Value to return in *pnEntry */
55974   int rc;                              /* Return code */
55975 
55976   if( pCur->pgnoRoot==0 ){
55977     *pnEntry = 0;
55978     return SQLITE_OK;
55979   }
55980   rc = moveToRoot(pCur);
55981 
55982   /* Unless an error occurs, the following loop runs one iteration for each
55983   ** page in the B-Tree structure (not including overflow pages).
55984   */
55985   while( rc==SQLITE_OK ){
55986     int iIdx;                          /* Index of child node in parent */
55987     MemPage *pPage;                    /* Current page of the b-tree */
55988 
55989     /* If this is a leaf page or the tree is not an int-key tree, then
55990     ** this page contains countable entries. Increment the entry counter
55991     ** accordingly.
55992     */
55993     pPage = pCur->apPage[pCur->iPage];
55994     if( pPage->leaf || !pPage->intKey ){
55995       nEntry += pPage->nCell;
55996     }
55997 
55998     /* pPage is a leaf node. This loop navigates the cursor so that it
55999     ** points to the first interior cell that it points to the parent of
56000     ** the next page in the tree that has not yet been visited. The
56001     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
56002     ** of the page, or to the number of cells in the page if the next page
56003     ** to visit is the right-child of its parent.
56004     **
56005     ** If all pages in the tree have been visited, return SQLITE_OK to the
56006     ** caller.
56007     */
56008     if( pPage->leaf ){
56009       do {
56010         if( pCur->iPage==0 ){
56011           /* All pages of the b-tree have been visited. Return successfully. */
56012           *pnEntry = nEntry;
56013           return SQLITE_OK;
56014         }
56015         moveToParent(pCur);
56016       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
56017 
56018       pCur->aiIdx[pCur->iPage]++;
56019       pPage = pCur->apPage[pCur->iPage];
56020     }
56021 
56022     /* Descend to the child node of the cell that the cursor currently
56023     ** points at. This is the right-child if (iIdx==pPage->nCell).
56024     */
56025     iIdx = pCur->aiIdx[pCur->iPage];
56026     if( iIdx==pPage->nCell ){
56027       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56028     }else{
56029       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
56030     }
56031   }
56032 
56033   /* An error has occurred. Return an error code. */
56034   return rc;
56035 }
56036 #endif
56037 
56038 /*
56039 ** Return the pager associated with a BTree.  This routine is used for
56040 ** testing and debugging only.
56041 */
56042 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
56043   return p->pBt->pPager;
56044 }
56045 
56046 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56047 /*
56048 ** Append a message to the error message string.
56049 */
56050 static void checkAppendMsg(
56051   IntegrityCk *pCheck,
56052   char *zMsg1,
56053   const char *zFormat,
56054   ...
56055 ){
56056   va_list ap;
56057   if( !pCheck->mxErr ) return;
56058   pCheck->mxErr--;
56059   pCheck->nErr++;
56060   va_start(ap, zFormat);
56061   if( pCheck->errMsg.nChar ){
56062     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
56063   }
56064   if( zMsg1 ){
56065     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
56066   }
56067   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
56068   va_end(ap);
56069   if( pCheck->errMsg.mallocFailed ){
56070     pCheck->mallocFailed = 1;
56071   }
56072 }
56073 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56074 
56075 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56076 
56077 /*
56078 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
56079 ** corresponds to page iPg is already set.
56080 */
56081 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
56082   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
56083   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
56084 }
56085 
56086 /*
56087 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
56088 */
56089 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
56090   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
56091   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
56092 }
56093 
56094 
56095 /*
56096 ** Add 1 to the reference count for page iPage.  If this is the second
56097 ** reference to the page, add an error message to pCheck->zErrMsg.
56098 ** Return 1 if there are 2 ore more references to the page and 0 if
56099 ** if this is the first reference to the page.
56100 **
56101 ** Also check that the page number is in bounds.
56102 */
56103 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
56104   if( iPage==0 ) return 1;
56105   if( iPage>pCheck->nPage ){
56106     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
56107     return 1;
56108   }
56109   if( getPageReferenced(pCheck, iPage) ){
56110     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
56111     return 1;
56112   }
56113   setPageReferenced(pCheck, iPage);
56114   return 0;
56115 }
56116 
56117 #ifndef SQLITE_OMIT_AUTOVACUUM
56118 /*
56119 ** Check that the entry in the pointer-map for page iChild maps to
56120 ** page iParent, pointer type ptrType. If not, append an error message
56121 ** to pCheck.
56122 */
56123 static void checkPtrmap(
56124   IntegrityCk *pCheck,   /* Integrity check context */
56125   Pgno iChild,           /* Child page number */
56126   u8 eType,              /* Expected pointer map type */
56127   Pgno iParent,          /* Expected pointer map parent page number */
56128   char *zContext         /* Context description (used for error msg) */
56129 ){
56130   int rc;
56131   u8 ePtrmapType;
56132   Pgno iPtrmapParent;
56133 
56134   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
56135   if( rc!=SQLITE_OK ){
56136     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
56137     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
56138     return;
56139   }
56140 
56141   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
56142     checkAppendMsg(pCheck, zContext,
56143       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
56144       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
56145   }
56146 }
56147 #endif
56148 
56149 /*
56150 ** Check the integrity of the freelist or of an overflow page list.
56151 ** Verify that the number of pages on the list is N.
56152 */
56153 static void checkList(
56154   IntegrityCk *pCheck,  /* Integrity checking context */
56155   int isFreeList,       /* True for a freelist.  False for overflow page list */
56156   int iPage,            /* Page number for first page in the list */
56157   int N,                /* Expected number of pages in the list */
56158   char *zContext        /* Context for error messages */
56159 ){
56160   int i;
56161   int expected = N;
56162   int iFirst = iPage;
56163   while( N-- > 0 && pCheck->mxErr ){
56164     DbPage *pOvflPage;
56165     unsigned char *pOvflData;
56166     if( iPage<1 ){
56167       checkAppendMsg(pCheck, zContext,
56168          "%d of %d pages missing from overflow list starting at %d",
56169           N+1, expected, iFirst);
56170       break;
56171     }
56172     if( checkRef(pCheck, iPage, zContext) ) break;
56173     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
56174       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
56175       break;
56176     }
56177     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
56178     if( isFreeList ){
56179       int n = get4byte(&pOvflData[4]);
56180 #ifndef SQLITE_OMIT_AUTOVACUUM
56181       if( pCheck->pBt->autoVacuum ){
56182         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
56183       }
56184 #endif
56185       if( n>(int)pCheck->pBt->usableSize/4-2 ){
56186         checkAppendMsg(pCheck, zContext,
56187            "freelist leaf count too big on page %d", iPage);
56188         N--;
56189       }else{
56190         for(i=0; i<n; i++){
56191           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
56192 #ifndef SQLITE_OMIT_AUTOVACUUM
56193           if( pCheck->pBt->autoVacuum ){
56194             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
56195           }
56196 #endif
56197           checkRef(pCheck, iFreePage, zContext);
56198         }
56199         N -= n;
56200       }
56201     }
56202 #ifndef SQLITE_OMIT_AUTOVACUUM
56203     else{
56204       /* If this database supports auto-vacuum and iPage is not the last
56205       ** page in this overflow list, check that the pointer-map entry for
56206       ** the following page matches iPage.
56207       */
56208       if( pCheck->pBt->autoVacuum && N>0 ){
56209         i = get4byte(pOvflData);
56210         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
56211       }
56212     }
56213 #endif
56214     iPage = get4byte(pOvflData);
56215     sqlite3PagerUnref(pOvflPage);
56216   }
56217 }
56218 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56219 
56220 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56221 /*
56222 ** Do various sanity checks on a single page of a tree.  Return
56223 ** the tree depth.  Root pages return 0.  Parents of root pages
56224 ** return 1, and so forth.
56225 **
56226 ** These checks are done:
56227 **
56228 **      1.  Make sure that cells and freeblocks do not overlap
56229 **          but combine to completely cover the page.
56230 **  NO  2.  Make sure cell keys are in order.
56231 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
56232 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
56233 **      5.  Check the integrity of overflow pages.
56234 **      6.  Recursively call checkTreePage on all children.
56235 **      7.  Verify that the depth of all children is the same.
56236 **      8.  Make sure this page is at least 33% full or else it is
56237 **          the root of the tree.
56238 */
56239 static int checkTreePage(
56240   IntegrityCk *pCheck,  /* Context for the sanity check */
56241   int iPage,            /* Page number of the page to check */
56242   char *zParentContext, /* Parent context */
56243   i64 *pnParentMinKey,
56244   i64 *pnParentMaxKey
56245 ){
56246   MemPage *pPage;
56247   int i, rc, depth, d2, pgno, cnt;
56248   int hdr, cellStart;
56249   int nCell;
56250   u8 *data;
56251   BtShared *pBt;
56252   int usableSize;
56253   char zContext[100];
56254   char *hit = 0;
56255   i64 nMinKey = 0;
56256   i64 nMaxKey = 0;
56257 
56258   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
56259 
56260   /* Check that the page exists
56261   */
56262   pBt = pCheck->pBt;
56263   usableSize = pBt->usableSize;
56264   if( iPage==0 ) return 0;
56265   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
56266   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
56267     checkAppendMsg(pCheck, zContext,
56268        "unable to get the page. error code=%d", rc);
56269     return 0;
56270   }
56271 
56272   /* Clear MemPage.isInit to make sure the corruption detection code in
56273   ** btreeInitPage() is executed.  */
56274   pPage->isInit = 0;
56275   if( (rc = btreeInitPage(pPage))!=0 ){
56276     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
56277     checkAppendMsg(pCheck, zContext,
56278                    "btreeInitPage() returns error code %d", rc);
56279     releasePage(pPage);
56280     return 0;
56281   }
56282 
56283   /* Check out all the cells.
56284   */
56285   depth = 0;
56286   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
56287     u8 *pCell;
56288     u32 sz;
56289     CellInfo info;
56290 
56291     /* Check payload overflow pages
56292     */
56293     sqlite3_snprintf(sizeof(zContext), zContext,
56294              "On tree page %d cell %d: ", iPage, i);
56295     pCell = findCell(pPage,i);
56296     btreeParseCellPtr(pPage, pCell, &info);
56297     sz = info.nData;
56298     if( !pPage->intKey ) sz += (int)info.nKey;
56299     /* For intKey pages, check that the keys are in order.
56300     */
56301     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
56302     else{
56303       if( info.nKey <= nMaxKey ){
56304         checkAppendMsg(pCheck, zContext,
56305             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
56306       }
56307       nMaxKey = info.nKey;
56308     }
56309     assert( sz==info.nPayload );
56310     if( (sz>info.nLocal)
56311      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
56312     ){
56313       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
56314       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
56315 #ifndef SQLITE_OMIT_AUTOVACUUM
56316       if( pBt->autoVacuum ){
56317         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
56318       }
56319 #endif
56320       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
56321     }
56322 
56323     /* Check sanity of left child page.
56324     */
56325     if( !pPage->leaf ){
56326       pgno = get4byte(pCell);
56327 #ifndef SQLITE_OMIT_AUTOVACUUM
56328       if( pBt->autoVacuum ){
56329         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
56330       }
56331 #endif
56332       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
56333       if( i>0 && d2!=depth ){
56334         checkAppendMsg(pCheck, zContext, "Child page depth differs");
56335       }
56336       depth = d2;
56337     }
56338   }
56339 
56340   if( !pPage->leaf ){
56341     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56342     sqlite3_snprintf(sizeof(zContext), zContext,
56343                      "On page %d at right child: ", iPage);
56344 #ifndef SQLITE_OMIT_AUTOVACUUM
56345     if( pBt->autoVacuum ){
56346       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
56347     }
56348 #endif
56349     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
56350   }
56351 
56352   /* For intKey leaf pages, check that the min/max keys are in order
56353   ** with any left/parent/right pages.
56354   */
56355   if( pPage->leaf && pPage->intKey ){
56356     /* if we are a left child page */
56357     if( pnParentMinKey ){
56358       /* if we are the left most child page */
56359       if( !pnParentMaxKey ){
56360         if( nMaxKey > *pnParentMinKey ){
56361           checkAppendMsg(pCheck, zContext,
56362               "Rowid %lld out of order (max larger than parent min of %lld)",
56363               nMaxKey, *pnParentMinKey);
56364         }
56365       }else{
56366         if( nMinKey <= *pnParentMinKey ){
56367           checkAppendMsg(pCheck, zContext,
56368               "Rowid %lld out of order (min less than parent min of %lld)",
56369               nMinKey, *pnParentMinKey);
56370         }
56371         if( nMaxKey > *pnParentMaxKey ){
56372           checkAppendMsg(pCheck, zContext,
56373               "Rowid %lld out of order (max larger than parent max of %lld)",
56374               nMaxKey, *pnParentMaxKey);
56375         }
56376         *pnParentMinKey = nMaxKey;
56377       }
56378     /* else if we're a right child page */
56379     } else if( pnParentMaxKey ){
56380       if( nMinKey <= *pnParentMaxKey ){
56381         checkAppendMsg(pCheck, zContext,
56382             "Rowid %lld out of order (min less than parent max of %lld)",
56383             nMinKey, *pnParentMaxKey);
56384       }
56385     }
56386   }
56387 
56388   /* Check for complete coverage of the page
56389   */
56390   data = pPage->aData;
56391   hdr = pPage->hdrOffset;
56392   hit = sqlite3PageMalloc( pBt->pageSize );
56393   if( hit==0 ){
56394     pCheck->mallocFailed = 1;
56395   }else{
56396     int contentOffset = get2byteNotZero(&data[hdr+5]);
56397     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
56398     memset(hit+contentOffset, 0, usableSize-contentOffset);
56399     memset(hit, 1, contentOffset);
56400     nCell = get2byte(&data[hdr+3]);
56401     cellStart = hdr + 12 - 4*pPage->leaf;
56402     for(i=0; i<nCell; i++){
56403       int pc = get2byte(&data[cellStart+i*2]);
56404       u32 size = 65536;
56405       int j;
56406       if( pc<=usableSize-4 ){
56407         size = cellSizePtr(pPage, &data[pc]);
56408       }
56409       if( (int)(pc+size-1)>=usableSize ){
56410         checkAppendMsg(pCheck, 0,
56411             "Corruption detected in cell %d on page %d",i,iPage);
56412       }else{
56413         for(j=pc+size-1; j>=pc; j--) hit[j]++;
56414       }
56415     }
56416     i = get2byte(&data[hdr+1]);
56417     while( i>0 ){
56418       int size, j;
56419       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
56420       size = get2byte(&data[i+2]);
56421       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
56422       for(j=i+size-1; j>=i; j--) hit[j]++;
56423       j = get2byte(&data[i]);
56424       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
56425       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
56426       i = j;
56427     }
56428     for(i=cnt=0; i<usableSize; i++){
56429       if( hit[i]==0 ){
56430         cnt++;
56431       }else if( hit[i]>1 ){
56432         checkAppendMsg(pCheck, 0,
56433           "Multiple uses for byte %d of page %d", i, iPage);
56434         break;
56435       }
56436     }
56437     if( cnt!=data[hdr+7] ){
56438       checkAppendMsg(pCheck, 0,
56439           "Fragmentation of %d bytes reported as %d on page %d",
56440           cnt, data[hdr+7], iPage);
56441     }
56442   }
56443   sqlite3PageFree(hit);
56444   releasePage(pPage);
56445   return depth+1;
56446 }
56447 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56448 
56449 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56450 /*
56451 ** This routine does a complete check of the given BTree file.  aRoot[] is
56452 ** an array of pages numbers were each page number is the root page of
56453 ** a table.  nRoot is the number of entries in aRoot.
56454 **
56455 ** A read-only or read-write transaction must be opened before calling
56456 ** this function.
56457 **
56458 ** Write the number of error seen in *pnErr.  Except for some memory
56459 ** allocation errors,  an error message held in memory obtained from
56460 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
56461 ** returned.  If a memory allocation error occurs, NULL is returned.
56462 */
56463 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
56464   Btree *p,     /* The btree to be checked */
56465   int *aRoot,   /* An array of root pages numbers for individual trees */
56466   int nRoot,    /* Number of entries in aRoot[] */
56467   int mxErr,    /* Stop reporting errors after this many */
56468   int *pnErr    /* Write number of errors seen to this variable */
56469 ){
56470   Pgno i;
56471   int nRef;
56472   IntegrityCk sCheck;
56473   BtShared *pBt = p->pBt;
56474   char zErr[100];
56475 
56476   sqlite3BtreeEnter(p);
56477   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
56478   nRef = sqlite3PagerRefcount(pBt->pPager);
56479   sCheck.pBt = pBt;
56480   sCheck.pPager = pBt->pPager;
56481   sCheck.nPage = btreePagecount(sCheck.pBt);
56482   sCheck.mxErr = mxErr;
56483   sCheck.nErr = 0;
56484   sCheck.mallocFailed = 0;
56485   *pnErr = 0;
56486   if( sCheck.nPage==0 ){
56487     sqlite3BtreeLeave(p);
56488     return 0;
56489   }
56490 
56491   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
56492   if( !sCheck.aPgRef ){
56493     *pnErr = 1;
56494     sqlite3BtreeLeave(p);
56495     return 0;
56496   }
56497   i = PENDING_BYTE_PAGE(pBt);
56498   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
56499   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
56500   sCheck.errMsg.useMalloc = 2;
56501 
56502   /* Check the integrity of the freelist
56503   */
56504   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
56505             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
56506 
56507   /* Check all the tables.
56508   */
56509   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
56510     if( aRoot[i]==0 ) continue;
56511 #ifndef SQLITE_OMIT_AUTOVACUUM
56512     if( pBt->autoVacuum && aRoot[i]>1 ){
56513       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
56514     }
56515 #endif
56516     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
56517   }
56518 
56519   /* Make sure every page in the file is referenced
56520   */
56521   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
56522 #ifdef SQLITE_OMIT_AUTOVACUUM
56523     if( getPageReferenced(&sCheck, i)==0 ){
56524       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56525     }
56526 #else
56527     /* If the database supports auto-vacuum, make sure no tables contain
56528     ** references to pointer-map pages.
56529     */
56530     if( getPageReferenced(&sCheck, i)==0 &&
56531        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
56532       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56533     }
56534     if( getPageReferenced(&sCheck, i)!=0 &&
56535        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
56536       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
56537     }
56538 #endif
56539   }
56540 
56541   /* Make sure this analysis did not leave any unref() pages.
56542   ** This is an internal consistency check; an integrity check
56543   ** of the integrity check.
56544   */
56545   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
56546     checkAppendMsg(&sCheck, 0,
56547       "Outstanding page count goes from %d to %d during this analysis",
56548       nRef, sqlite3PagerRefcount(pBt->pPager)
56549     );
56550   }
56551 
56552   /* Clean  up and report errors.
56553   */
56554   sqlite3BtreeLeave(p);
56555   sqlite3_free(sCheck.aPgRef);
56556   if( sCheck.mallocFailed ){
56557     sqlite3StrAccumReset(&sCheck.errMsg);
56558     *pnErr = sCheck.nErr+1;
56559     return 0;
56560   }
56561   *pnErr = sCheck.nErr;
56562   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
56563   return sqlite3StrAccumFinish(&sCheck.errMsg);
56564 }
56565 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56566 
56567 /*
56568 ** Return the full pathname of the underlying database file.  Return
56569 ** an empty string if the database is in-memory or a TEMP database.
56570 **
56571 ** The pager filename is invariant as long as the pager is
56572 ** open so it is safe to access without the BtShared mutex.
56573 */
56574 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
56575   assert( p->pBt->pPager!=0 );
56576   return sqlite3PagerFilename(p->pBt->pPager, 1);
56577 }
56578 
56579 /*
56580 ** Return the pathname of the journal file for this database. The return
56581 ** value of this routine is the same regardless of whether the journal file
56582 ** has been created or not.
56583 **
56584 ** The pager journal filename is invariant as long as the pager is
56585 ** open so it is safe to access without the BtShared mutex.
56586 */
56587 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
56588   assert( p->pBt->pPager!=0 );
56589   return sqlite3PagerJournalname(p->pBt->pPager);
56590 }
56591 
56592 /*
56593 ** Return non-zero if a transaction is active.
56594 */
56595 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
56596   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
56597   return (p && (p->inTrans==TRANS_WRITE));
56598 }
56599 
56600 #ifndef SQLITE_OMIT_WAL
56601 /*
56602 ** Run a checkpoint on the Btree passed as the first argument.
56603 **
56604 ** Return SQLITE_LOCKED if this or any other connection has an open
56605 ** transaction on the shared-cache the argument Btree is connected to.
56606 **
56607 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
56608 */
56609 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
56610   int rc = SQLITE_OK;
56611   if( p ){
56612     BtShared *pBt = p->pBt;
56613     sqlite3BtreeEnter(p);
56614     if( pBt->inTransaction!=TRANS_NONE ){
56615       rc = SQLITE_LOCKED;
56616     }else{
56617       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
56618     }
56619     sqlite3BtreeLeave(p);
56620   }
56621   return rc;
56622 }
56623 #endif
56624 
56625 /*
56626 ** Return non-zero if a read (or write) transaction is active.
56627 */
56628 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
56629   assert( p );
56630   assert( sqlite3_mutex_held(p->db->mutex) );
56631   return p->inTrans!=TRANS_NONE;
56632 }
56633 
56634 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
56635   assert( p );
56636   assert( sqlite3_mutex_held(p->db->mutex) );
56637   return p->nBackup!=0;
56638 }
56639 
56640 /*
56641 ** This function returns a pointer to a blob of memory associated with
56642 ** a single shared-btree. The memory is used by client code for its own
56643 ** purposes (for example, to store a high-level schema associated with
56644 ** the shared-btree). The btree layer manages reference counting issues.
56645 **
56646 ** The first time this is called on a shared-btree, nBytes bytes of memory
56647 ** are allocated, zeroed, and returned to the caller. For each subsequent
56648 ** call the nBytes parameter is ignored and a pointer to the same blob
56649 ** of memory returned.
56650 **
56651 ** If the nBytes parameter is 0 and the blob of memory has not yet been
56652 ** allocated, a null pointer is returned. If the blob has already been
56653 ** allocated, it is returned as normal.
56654 **
56655 ** Just before the shared-btree is closed, the function passed as the
56656 ** xFree argument when the memory allocation was made is invoked on the
56657 ** blob of allocated memory. The xFree function should not call sqlite3_free()
56658 ** on the memory, the btree layer does that.
56659 */
56660 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
56661   BtShared *pBt = p->pBt;
56662   sqlite3BtreeEnter(p);
56663   if( !pBt->pSchema && nBytes ){
56664     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
56665     pBt->xFreeSchema = xFree;
56666   }
56667   sqlite3BtreeLeave(p);
56668   return pBt->pSchema;
56669 }
56670 
56671 /*
56672 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
56673 ** btree as the argument handle holds an exclusive lock on the
56674 ** sqlite_master table. Otherwise SQLITE_OK.
56675 */
56676 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
56677   int rc;
56678   assert( sqlite3_mutex_held(p->db->mutex) );
56679   sqlite3BtreeEnter(p);
56680   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
56681   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
56682   sqlite3BtreeLeave(p);
56683   return rc;
56684 }
56685 
56686 
56687 #ifndef SQLITE_OMIT_SHARED_CACHE
56688 /*
56689 ** Obtain a lock on the table whose root page is iTab.  The
56690 ** lock is a write lock if isWritelock is true or a read lock
56691 ** if it is false.
56692 */
56693 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
56694   int rc = SQLITE_OK;
56695   assert( p->inTrans!=TRANS_NONE );
56696   if( p->sharable ){
56697     u8 lockType = READ_LOCK + isWriteLock;
56698     assert( READ_LOCK+1==WRITE_LOCK );
56699     assert( isWriteLock==0 || isWriteLock==1 );
56700 
56701     sqlite3BtreeEnter(p);
56702     rc = querySharedCacheTableLock(p, iTab, lockType);
56703     if( rc==SQLITE_OK ){
56704       rc = setSharedCacheTableLock(p, iTab, lockType);
56705     }
56706     sqlite3BtreeLeave(p);
56707   }
56708   return rc;
56709 }
56710 #endif
56711 
56712 #ifndef SQLITE_OMIT_INCRBLOB
56713 /*
56714 ** Argument pCsr must be a cursor opened for writing on an
56715 ** INTKEY table currently pointing at a valid table entry.
56716 ** This function modifies the data stored as part of that entry.
56717 **
56718 ** Only the data content may only be modified, it is not possible to
56719 ** change the length of the data stored. If this function is called with
56720 ** parameters that attempt to write past the end of the existing data,
56721 ** no modifications are made and SQLITE_CORRUPT is returned.
56722 */
56723 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
56724   int rc;
56725   assert( cursorHoldsMutex(pCsr) );
56726   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
56727   assert( pCsr->isIncrblobHandle );
56728 
56729   rc = restoreCursorPosition(pCsr);
56730   if( rc!=SQLITE_OK ){
56731     return rc;
56732   }
56733   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
56734   if( pCsr->eState!=CURSOR_VALID ){
56735     return SQLITE_ABORT;
56736   }
56737 
56738   /* Check some assumptions:
56739   **   (a) the cursor is open for writing,
56740   **   (b) there is a read/write transaction open,
56741   **   (c) the connection holds a write-lock on the table (if required),
56742   **   (d) there are no conflicting read-locks, and
56743   **   (e) the cursor points at a valid row of an intKey table.
56744   */
56745   if( !pCsr->wrFlag ){
56746     return SQLITE_READONLY;
56747   }
56748   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
56749               && pCsr->pBt->inTransaction==TRANS_WRITE );
56750   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
56751   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
56752   assert( pCsr->apPage[pCsr->iPage]->intKey );
56753 
56754   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
56755 }
56756 
56757 /*
56758 ** Set a flag on this cursor to cache the locations of pages from the
56759 ** overflow list for the current row. This is used by cursors opened
56760 ** for incremental blob IO only.
56761 **
56762 ** This function sets a flag only. The actual page location cache
56763 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
56764 ** accessPayload() (the worker function for sqlite3BtreeData() and
56765 ** sqlite3BtreePutData()).
56766 */
56767 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
56768   assert( cursorHoldsMutex(pCur) );
56769   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56770   invalidateOverflowCache(pCur);
56771   pCur->isIncrblobHandle = 1;
56772 }
56773 #endif
56774 
56775 /*
56776 ** Set both the "read version" (single byte at byte offset 18) and
56777 ** "write version" (single byte at byte offset 19) fields in the database
56778 ** header to iVersion.
56779 */
56780 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
56781   BtShared *pBt = pBtree->pBt;
56782   int rc;                         /* Return code */
56783 
56784   assert( iVersion==1 || iVersion==2 );
56785 
56786   /* If setting the version fields to 1, do not automatically open the
56787   ** WAL connection, even if the version fields are currently set to 2.
56788   */
56789   pBt->btsFlags &= ~BTS_NO_WAL;
56790   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
56791 
56792   rc = sqlite3BtreeBeginTrans(pBtree, 0);
56793   if( rc==SQLITE_OK ){
56794     u8 *aData = pBt->pPage1->aData;
56795     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
56796       rc = sqlite3BtreeBeginTrans(pBtree, 2);
56797       if( rc==SQLITE_OK ){
56798         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56799         if( rc==SQLITE_OK ){
56800           aData[18] = (u8)iVersion;
56801           aData[19] = (u8)iVersion;
56802         }
56803       }
56804     }
56805   }
56806 
56807   pBt->btsFlags &= ~BTS_NO_WAL;
56808   return rc;
56809 }
56810 
56811 /*
56812 ** set the mask of hint flags for cursor pCsr. Currently the only valid
56813 ** values are 0 and BTREE_BULKLOAD.
56814 */
56815 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
56816   assert( mask==BTREE_BULKLOAD || mask==0 );
56817   pCsr->hints = mask;
56818 }
56819 
56820 /************** End of btree.c ***********************************************/
56821 /************** Begin file backup.c ******************************************/
56822 /*
56823 ** 2009 January 28
56824 **
56825 ** The author disclaims copyright to this source code.  In place of
56826 ** a legal notice, here is a blessing:
56827 **
56828 **    May you do good and not evil.
56829 **    May you find forgiveness for yourself and forgive others.
56830 **    May you share freely, never taking more than you give.
56831 **
56832 *************************************************************************
56833 ** This file contains the implementation of the sqlite3_backup_XXX()
56834 ** API functions and the related features.
56835 */
56836 
56837 /* Macro to find the minimum of two numeric values.
56838 */
56839 #ifndef MIN
56840 # define MIN(x,y) ((x)<(y)?(x):(y))
56841 #endif
56842 
56843 /*
56844 ** Structure allocated for each backup operation.
56845 */
56846 struct sqlite3_backup {
56847   sqlite3* pDestDb;        /* Destination database handle */
56848   Btree *pDest;            /* Destination b-tree file */
56849   u32 iDestSchema;         /* Original schema cookie in destination */
56850   int bDestLocked;         /* True once a write-transaction is open on pDest */
56851 
56852   Pgno iNext;              /* Page number of the next source page to copy */
56853   sqlite3* pSrcDb;         /* Source database handle */
56854   Btree *pSrc;             /* Source b-tree file */
56855 
56856   int rc;                  /* Backup process error code */
56857 
56858   /* These two variables are set by every call to backup_step(). They are
56859   ** read by calls to backup_remaining() and backup_pagecount().
56860   */
56861   Pgno nRemaining;         /* Number of pages left to copy */
56862   Pgno nPagecount;         /* Total number of pages to copy */
56863 
56864   int isAttached;          /* True once backup has been registered with pager */
56865   sqlite3_backup *pNext;   /* Next backup associated with source pager */
56866 };
56867 
56868 /*
56869 ** THREAD SAFETY NOTES:
56870 **
56871 **   Once it has been created using backup_init(), a single sqlite3_backup
56872 **   structure may be accessed via two groups of thread-safe entry points:
56873 **
56874 **     * Via the sqlite3_backup_XXX() API function backup_step() and
56875 **       backup_finish(). Both these functions obtain the source database
56876 **       handle mutex and the mutex associated with the source BtShared
56877 **       structure, in that order.
56878 **
56879 **     * Via the BackupUpdate() and BackupRestart() functions, which are
56880 **       invoked by the pager layer to report various state changes in
56881 **       the page cache associated with the source database. The mutex
56882 **       associated with the source database BtShared structure will always
56883 **       be held when either of these functions are invoked.
56884 **
56885 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
56886 **   backup_pagecount() are not thread-safe functions. If they are called
56887 **   while some other thread is calling backup_step() or backup_finish(),
56888 **   the values returned may be invalid. There is no way for a call to
56889 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
56890 **   or backup_pagecount().
56891 **
56892 **   Depending on the SQLite configuration, the database handles and/or
56893 **   the Btree objects may have their own mutexes that require locking.
56894 **   Non-sharable Btrees (in-memory databases for example), do not have
56895 **   associated mutexes.
56896 */
56897 
56898 /*
56899 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
56900 ** in connection handle pDb. If such a database cannot be found, return
56901 ** a NULL pointer and write an error message to pErrorDb.
56902 **
56903 ** If the "temp" database is requested, it may need to be opened by this
56904 ** function. If an error occurs while doing so, return 0 and write an
56905 ** error message to pErrorDb.
56906 */
56907 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
56908   int i = sqlite3FindDbName(pDb, zDb);
56909 
56910   if( i==1 ){
56911     Parse *pParse;
56912     int rc = 0;
56913     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
56914     if( pParse==0 ){
56915       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
56916       rc = SQLITE_NOMEM;
56917     }else{
56918       pParse->db = pDb;
56919       if( sqlite3OpenTempDatabase(pParse) ){
56920         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
56921         rc = SQLITE_ERROR;
56922       }
56923       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
56924       sqlite3StackFree(pErrorDb, pParse);
56925     }
56926     if( rc ){
56927       return 0;
56928     }
56929   }
56930 
56931   if( i<0 ){
56932     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
56933     return 0;
56934   }
56935 
56936   return pDb->aDb[i].pBt;
56937 }
56938 
56939 /*
56940 ** Attempt to set the page size of the destination to match the page size
56941 ** of the source.
56942 */
56943 static int setDestPgsz(sqlite3_backup *p){
56944   int rc;
56945   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
56946   return rc;
56947 }
56948 
56949 /*
56950 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
56951 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
56952 ** a pointer to the new sqlite3_backup object.
56953 **
56954 ** If an error occurs, NULL is returned and an error code and error message
56955 ** stored in database handle pDestDb.
56956 */
56957 SQLITE_API sqlite3_backup *sqlite3_backup_init(
56958   sqlite3* pDestDb,                     /* Database to write to */
56959   const char *zDestDb,                  /* Name of database within pDestDb */
56960   sqlite3* pSrcDb,                      /* Database connection to read from */
56961   const char *zSrcDb                    /* Name of database within pSrcDb */
56962 ){
56963   sqlite3_backup *p;                    /* Value to return */
56964 
56965   /* Lock the source database handle. The destination database
56966   ** handle is not locked in this routine, but it is locked in
56967   ** sqlite3_backup_step(). The user is required to ensure that no
56968   ** other thread accesses the destination handle for the duration
56969   ** of the backup operation.  Any attempt to use the destination
56970   ** database connection while a backup is in progress may cause
56971   ** a malfunction or a deadlock.
56972   */
56973   sqlite3_mutex_enter(pSrcDb->mutex);
56974   sqlite3_mutex_enter(pDestDb->mutex);
56975 
56976   if( pSrcDb==pDestDb ){
56977     sqlite3Error(
56978         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
56979     );
56980     p = 0;
56981   }else {
56982     /* Allocate space for a new sqlite3_backup object...
56983     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56984     ** call to sqlite3_backup_init() and is destroyed by a call to
56985     ** sqlite3_backup_finish(). */
56986     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
56987     if( !p ){
56988       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
56989     }
56990   }
56991 
56992   /* If the allocation succeeded, populate the new object. */
56993   if( p ){
56994     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
56995     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
56996     p->pDestDb = pDestDb;
56997     p->pSrcDb = pSrcDb;
56998     p->iNext = 1;
56999     p->isAttached = 0;
57000 
57001     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
57002       /* One (or both) of the named databases did not exist or an OOM
57003       ** error was hit.  The error has already been written into the
57004       ** pDestDb handle.  All that is left to do here is free the
57005       ** sqlite3_backup structure.
57006       */
57007       sqlite3_free(p);
57008       p = 0;
57009     }
57010   }
57011   if( p ){
57012     p->pSrc->nBackup++;
57013   }
57014 
57015   sqlite3_mutex_leave(pDestDb->mutex);
57016   sqlite3_mutex_leave(pSrcDb->mutex);
57017   return p;
57018 }
57019 
57020 /*
57021 ** Argument rc is an SQLite error code. Return true if this error is
57022 ** considered fatal if encountered during a backup operation. All errors
57023 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
57024 */
57025 static int isFatalError(int rc){
57026   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
57027 }
57028 
57029 /*
57030 ** Parameter zSrcData points to a buffer containing the data for
57031 ** page iSrcPg from the source database. Copy this data into the
57032 ** destination database.
57033 */
57034 static int backupOnePage(
57035   sqlite3_backup *p,              /* Backup handle */
57036   Pgno iSrcPg,                    /* Source database page to backup */
57037   const u8 *zSrcData,             /* Source database page data */
57038   int bUpdate                     /* True for an update, false otherwise */
57039 ){
57040   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
57041   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
57042   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
57043   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
57044   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
57045 #ifdef SQLITE_HAS_CODEC
57046   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
57047   ** guaranteed that the shared-mutex is held by this thread, handle
57048   ** p->pSrc may not actually be the owner.  */
57049   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
57050   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
57051 #endif
57052   int rc = SQLITE_OK;
57053   i64 iOff;
57054 
57055   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
57056   assert( p->bDestLocked );
57057   assert( !isFatalError(p->rc) );
57058   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
57059   assert( zSrcData );
57060 
57061   /* Catch the case where the destination is an in-memory database and the
57062   ** page sizes of the source and destination differ.
57063   */
57064   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
57065     rc = SQLITE_READONLY;
57066   }
57067 
57068 #ifdef SQLITE_HAS_CODEC
57069   /* Backup is not possible if the page size of the destination is changing
57070   ** and a codec is in use.
57071   */
57072   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
57073     rc = SQLITE_READONLY;
57074   }
57075 
57076   /* Backup is not possible if the number of bytes of reserve space differ
57077   ** between source and destination.  If there is a difference, try to
57078   ** fix the destination to agree with the source.  If that is not possible,
57079   ** then the backup cannot proceed.
57080   */
57081   if( nSrcReserve!=nDestReserve ){
57082     u32 newPgsz = nSrcPgsz;
57083     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
57084     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
57085   }
57086 #endif
57087 
57088   /* This loop runs once for each destination page spanned by the source
57089   ** page. For each iteration, variable iOff is set to the byte offset
57090   ** of the destination page.
57091   */
57092   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
57093     DbPage *pDestPg = 0;
57094     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
57095     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
57096     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
57097      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
57098     ){
57099       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
57100       u8 *zDestData = sqlite3PagerGetData(pDestPg);
57101       u8 *zOut = &zDestData[iOff%nDestPgsz];
57102 
57103       /* Copy the data from the source page into the destination page.
57104       ** Then clear the Btree layer MemPage.isInit flag. Both this module
57105       ** and the pager code use this trick (clearing the first byte
57106       ** of the page 'extra' space to invalidate the Btree layers
57107       ** cached parse of the page). MemPage.isInit is marked
57108       ** "MUST BE FIRST" for this purpose.
57109       */
57110       memcpy(zOut, zIn, nCopy);
57111       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
57112       if( iOff==0 && bUpdate==0 ){
57113         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
57114       }
57115     }
57116     sqlite3PagerUnref(pDestPg);
57117   }
57118 
57119   return rc;
57120 }
57121 
57122 /*
57123 ** If pFile is currently larger than iSize bytes, then truncate it to
57124 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
57125 ** this function is a no-op.
57126 **
57127 ** Return SQLITE_OK if everything is successful, or an SQLite error
57128 ** code if an error occurs.
57129 */
57130 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
57131   i64 iCurrent;
57132   int rc = sqlite3OsFileSize(pFile, &iCurrent);
57133   if( rc==SQLITE_OK && iCurrent>iSize ){
57134     rc = sqlite3OsTruncate(pFile, iSize);
57135   }
57136   return rc;
57137 }
57138 
57139 /*
57140 ** Register this backup object with the associated source pager for
57141 ** callbacks when pages are changed or the cache invalidated.
57142 */
57143 static void attachBackupObject(sqlite3_backup *p){
57144   sqlite3_backup **pp;
57145   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
57146   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57147   p->pNext = *pp;
57148   *pp = p;
57149   p->isAttached = 1;
57150 }
57151 
57152 /*
57153 ** Copy nPage pages from the source b-tree to the destination.
57154 */
57155 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
57156   int rc;
57157   int destMode;       /* Destination journal mode */
57158   int pgszSrc = 0;    /* Source page size */
57159   int pgszDest = 0;   /* Destination page size */
57160 
57161   sqlite3_mutex_enter(p->pSrcDb->mutex);
57162   sqlite3BtreeEnter(p->pSrc);
57163   if( p->pDestDb ){
57164     sqlite3_mutex_enter(p->pDestDb->mutex);
57165   }
57166 
57167   rc = p->rc;
57168   if( !isFatalError(rc) ){
57169     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
57170     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
57171     int ii;                            /* Iterator variable */
57172     int nSrcPage = -1;                 /* Size of source db in pages */
57173     int bCloseTrans = 0;               /* True if src db requires unlocking */
57174 
57175     /* If the source pager is currently in a write-transaction, return
57176     ** SQLITE_BUSY immediately.
57177     */
57178     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
57179       rc = SQLITE_BUSY;
57180     }else{
57181       rc = SQLITE_OK;
57182     }
57183 
57184     /* Lock the destination database, if it is not locked already. */
57185     if( SQLITE_OK==rc && p->bDestLocked==0
57186      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
57187     ){
57188       p->bDestLocked = 1;
57189       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
57190     }
57191 
57192     /* If there is no open read-transaction on the source database, open
57193     ** one now. If a transaction is opened here, then it will be closed
57194     ** before this function exits.
57195     */
57196     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
57197       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
57198       bCloseTrans = 1;
57199     }
57200 
57201     /* Do not allow backup if the destination database is in WAL mode
57202     ** and the page sizes are different between source and destination */
57203     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
57204     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
57205     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
57206     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
57207       rc = SQLITE_READONLY;
57208     }
57209 
57210     /* Now that there is a read-lock on the source database, query the
57211     ** source pager for the number of pages in the database.
57212     */
57213     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
57214     assert( nSrcPage>=0 );
57215     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
57216       const Pgno iSrcPg = p->iNext;                 /* Source page number */
57217       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
57218         DbPage *pSrcPg;                             /* Source page object */
57219         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
57220         if( rc==SQLITE_OK ){
57221           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
57222           sqlite3PagerUnref(pSrcPg);
57223         }
57224       }
57225       p->iNext++;
57226     }
57227     if( rc==SQLITE_OK ){
57228       p->nPagecount = nSrcPage;
57229       p->nRemaining = nSrcPage+1-p->iNext;
57230       if( p->iNext>(Pgno)nSrcPage ){
57231         rc = SQLITE_DONE;
57232       }else if( !p->isAttached ){
57233         attachBackupObject(p);
57234       }
57235     }
57236 
57237     /* Update the schema version field in the destination database. This
57238     ** is to make sure that the schema-version really does change in
57239     ** the case where the source and destination databases have the
57240     ** same schema version.
57241     */
57242     if( rc==SQLITE_DONE ){
57243       if( nSrcPage==0 ){
57244         rc = sqlite3BtreeNewDb(p->pDest);
57245         nSrcPage = 1;
57246       }
57247       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
57248         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
57249       }
57250       if( rc==SQLITE_OK ){
57251         if( p->pDestDb ){
57252           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
57253         }
57254         if( destMode==PAGER_JOURNALMODE_WAL ){
57255           rc = sqlite3BtreeSetVersion(p->pDest, 2);
57256         }
57257       }
57258       if( rc==SQLITE_OK ){
57259         int nDestTruncate;
57260         /* Set nDestTruncate to the final number of pages in the destination
57261         ** database. The complication here is that the destination page
57262         ** size may be different to the source page size.
57263         **
57264         ** If the source page size is smaller than the destination page size,
57265         ** round up. In this case the call to sqlite3OsTruncate() below will
57266         ** fix the size of the file. However it is important to call
57267         ** sqlite3PagerTruncateImage() here so that any pages in the
57268         ** destination file that lie beyond the nDestTruncate page mark are
57269         ** journalled by PagerCommitPhaseOne() before they are destroyed
57270         ** by the file truncation.
57271         */
57272         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
57273         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
57274         if( pgszSrc<pgszDest ){
57275           int ratio = pgszDest/pgszSrc;
57276           nDestTruncate = (nSrcPage+ratio-1)/ratio;
57277           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
57278             nDestTruncate--;
57279           }
57280         }else{
57281           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
57282         }
57283         assert( nDestTruncate>0 );
57284 
57285         if( pgszSrc<pgszDest ){
57286           /* If the source page-size is smaller than the destination page-size,
57287           ** two extra things may need to happen:
57288           **
57289           **   * The destination may need to be truncated, and
57290           **
57291           **   * Data stored on the pages immediately following the
57292           **     pending-byte page in the source database may need to be
57293           **     copied into the destination database.
57294           */
57295           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
57296           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
57297           Pgno iPg;
57298           int nDstPage;
57299           i64 iOff;
57300           i64 iEnd;
57301 
57302           assert( pFile );
57303           assert( nDestTruncate==0
57304               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
57305                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
57306              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
57307           ));
57308 
57309           /* This block ensures that all data required to recreate the original
57310           ** database has been stored in the journal for pDestPager and the
57311           ** journal synced to disk. So at this point we may safely modify
57312           ** the database file in any way, knowing that if a power failure
57313           ** occurs, the original database will be reconstructed from the
57314           ** journal file.  */
57315           sqlite3PagerPagecount(pDestPager, &nDstPage);
57316           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
57317             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
57318               DbPage *pPg;
57319               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
57320               if( rc==SQLITE_OK ){
57321                 rc = sqlite3PagerWrite(pPg);
57322                 sqlite3PagerUnref(pPg);
57323               }
57324             }
57325           }
57326           if( rc==SQLITE_OK ){
57327             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
57328           }
57329 
57330           /* Write the extra pages and truncate the database file as required */
57331           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
57332           for(
57333             iOff=PENDING_BYTE+pgszSrc;
57334             rc==SQLITE_OK && iOff<iEnd;
57335             iOff+=pgszSrc
57336           ){
57337             PgHdr *pSrcPg = 0;
57338             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
57339             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
57340             if( rc==SQLITE_OK ){
57341               u8 *zData = sqlite3PagerGetData(pSrcPg);
57342               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
57343             }
57344             sqlite3PagerUnref(pSrcPg);
57345           }
57346           if( rc==SQLITE_OK ){
57347             rc = backupTruncateFile(pFile, iSize);
57348           }
57349 
57350           /* Sync the database file to disk. */
57351           if( rc==SQLITE_OK ){
57352             rc = sqlite3PagerSync(pDestPager);
57353           }
57354         }else{
57355           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
57356           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
57357         }
57358 
57359         /* Finish committing the transaction to the destination database. */
57360         if( SQLITE_OK==rc
57361          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
57362         ){
57363           rc = SQLITE_DONE;
57364         }
57365       }
57366     }
57367 
57368     /* If bCloseTrans is true, then this function opened a read transaction
57369     ** on the source database. Close the read transaction here. There is
57370     ** no need to check the return values of the btree methods here, as
57371     ** "committing" a read-only transaction cannot fail.
57372     */
57373     if( bCloseTrans ){
57374       TESTONLY( int rc2 );
57375       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
57376       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
57377       assert( rc2==SQLITE_OK );
57378     }
57379 
57380     if( rc==SQLITE_IOERR_NOMEM ){
57381       rc = SQLITE_NOMEM;
57382     }
57383     p->rc = rc;
57384   }
57385   if( p->pDestDb ){
57386     sqlite3_mutex_leave(p->pDestDb->mutex);
57387   }
57388   sqlite3BtreeLeave(p->pSrc);
57389   sqlite3_mutex_leave(p->pSrcDb->mutex);
57390   return rc;
57391 }
57392 
57393 /*
57394 ** Release all resources associated with an sqlite3_backup* handle.
57395 */
57396 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
57397   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
57398   sqlite3 *pSrcDb;                     /* Source database connection */
57399   int rc;                              /* Value to return */
57400 
57401   /* Enter the mutexes */
57402   if( p==0 ) return SQLITE_OK;
57403   pSrcDb = p->pSrcDb;
57404   sqlite3_mutex_enter(pSrcDb->mutex);
57405   sqlite3BtreeEnter(p->pSrc);
57406   if( p->pDestDb ){
57407     sqlite3_mutex_enter(p->pDestDb->mutex);
57408   }
57409 
57410   /* Detach this backup from the source pager. */
57411   if( p->pDestDb ){
57412     p->pSrc->nBackup--;
57413   }
57414   if( p->isAttached ){
57415     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57416     while( *pp!=p ){
57417       pp = &(*pp)->pNext;
57418     }
57419     *pp = p->pNext;
57420   }
57421 
57422   /* If a transaction is still open on the Btree, roll it back. */
57423   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
57424 
57425   /* Set the error code of the destination database handle. */
57426   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
57427   sqlite3Error(p->pDestDb, rc, 0);
57428 
57429   /* Exit the mutexes and free the backup context structure. */
57430   if( p->pDestDb ){
57431     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
57432   }
57433   sqlite3BtreeLeave(p->pSrc);
57434   if( p->pDestDb ){
57435     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
57436     ** call to sqlite3_backup_init() and is destroyed by a call to
57437     ** sqlite3_backup_finish(). */
57438     sqlite3_free(p);
57439   }
57440   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
57441   return rc;
57442 }
57443 
57444 /*
57445 ** Return the number of pages still to be backed up as of the most recent
57446 ** call to sqlite3_backup_step().
57447 */
57448 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
57449   return p->nRemaining;
57450 }
57451 
57452 /*
57453 ** Return the total number of pages in the source database as of the most
57454 ** recent call to sqlite3_backup_step().
57455 */
57456 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
57457   return p->nPagecount;
57458 }
57459 
57460 /*
57461 ** This function is called after the contents of page iPage of the
57462 ** source database have been modified. If page iPage has already been
57463 ** copied into the destination database, then the data written to the
57464 ** destination is now invalidated. The destination copy of iPage needs
57465 ** to be updated with the new data before the backup operation is
57466 ** complete.
57467 **
57468 ** It is assumed that the mutex associated with the BtShared object
57469 ** corresponding to the source database is held when this function is
57470 ** called.
57471 */
57472 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
57473   sqlite3_backup *p;                   /* Iterator variable */
57474   for(p=pBackup; p; p=p->pNext){
57475     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57476     if( !isFatalError(p->rc) && iPage<p->iNext ){
57477       /* The backup process p has already copied page iPage. But now it
57478       ** has been modified by a transaction on the source pager. Copy
57479       ** the new data into the backup.
57480       */
57481       int rc;
57482       assert( p->pDestDb );
57483       sqlite3_mutex_enter(p->pDestDb->mutex);
57484       rc = backupOnePage(p, iPage, aData, 1);
57485       sqlite3_mutex_leave(p->pDestDb->mutex);
57486       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
57487       if( rc!=SQLITE_OK ){
57488         p->rc = rc;
57489       }
57490     }
57491   }
57492 }
57493 
57494 /*
57495 ** Restart the backup process. This is called when the pager layer
57496 ** detects that the database has been modified by an external database
57497 ** connection. In this case there is no way of knowing which of the
57498 ** pages that have been copied into the destination database are still
57499 ** valid and which are not, so the entire process needs to be restarted.
57500 **
57501 ** It is assumed that the mutex associated with the BtShared object
57502 ** corresponding to the source database is held when this function is
57503 ** called.
57504 */
57505 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
57506   sqlite3_backup *p;                   /* Iterator variable */
57507   for(p=pBackup; p; p=p->pNext){
57508     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57509     p->iNext = 1;
57510   }
57511 }
57512 
57513 #ifndef SQLITE_OMIT_VACUUM
57514 /*
57515 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
57516 ** must be active for both files.
57517 **
57518 ** The size of file pTo may be reduced by this operation. If anything
57519 ** goes wrong, the transaction on pTo is rolled back. If successful, the
57520 ** transaction is committed before returning.
57521 */
57522 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
57523   int rc;
57524   sqlite3_file *pFd;              /* File descriptor for database pTo */
57525   sqlite3_backup b;
57526   sqlite3BtreeEnter(pTo);
57527   sqlite3BtreeEnter(pFrom);
57528 
57529   assert( sqlite3BtreeIsInTrans(pTo) );
57530   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
57531   if( pFd->pMethods ){
57532     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
57533     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
57534     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
57535     if( rc ) goto copy_finished;
57536   }
57537 
57538   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
57539   ** to 0. This is used by the implementations of sqlite3_backup_step()
57540   ** and sqlite3_backup_finish() to detect that they are being called
57541   ** from this function, not directly by the user.
57542   */
57543   memset(&b, 0, sizeof(b));
57544   b.pSrcDb = pFrom->db;
57545   b.pSrc = pFrom;
57546   b.pDest = pTo;
57547   b.iNext = 1;
57548 
57549   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
57550   ** file. By passing this as the number of pages to copy to
57551   ** sqlite3_backup_step(), we can guarantee that the copy finishes
57552   ** within a single call (unless an error occurs). The assert() statement
57553   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
57554   ** or an error code.
57555   */
57556   sqlite3_backup_step(&b, 0x7FFFFFFF);
57557   assert( b.rc!=SQLITE_OK );
57558   rc = sqlite3_backup_finish(&b);
57559   if( rc==SQLITE_OK ){
57560     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
57561   }else{
57562     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
57563   }
57564 
57565   assert( sqlite3BtreeIsInTrans(pTo)==0 );
57566 copy_finished:
57567   sqlite3BtreeLeave(pFrom);
57568   sqlite3BtreeLeave(pTo);
57569   return rc;
57570 }
57571 #endif /* SQLITE_OMIT_VACUUM */
57572 
57573 /************** End of backup.c **********************************************/
57574 /************** Begin file vdbemem.c *****************************************/
57575 /*
57576 ** 2004 May 26
57577 **
57578 ** The author disclaims copyright to this source code.  In place of
57579 ** a legal notice, here is a blessing:
57580 **
57581 **    May you do good and not evil.
57582 **    May you find forgiveness for yourself and forgive others.
57583 **    May you share freely, never taking more than you give.
57584 **
57585 *************************************************************************
57586 **
57587 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
57588 ** stores a single value in the VDBE.  Mem is an opaque structure visible
57589 ** only within the VDBE.  Interface routines refer to a Mem using the
57590 ** name sqlite_value
57591 */
57592 
57593 /*
57594 ** If pMem is an object with a valid string representation, this routine
57595 ** ensures the internal encoding for the string representation is
57596 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
57597 **
57598 ** If pMem is not a string object, or the encoding of the string
57599 ** representation is already stored using the requested encoding, then this
57600 ** routine is a no-op.
57601 **
57602 ** SQLITE_OK is returned if the conversion is successful (or not required).
57603 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
57604 ** between formats.
57605 */
57606 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
57607 #ifndef SQLITE_OMIT_UTF16
57608   int rc;
57609 #endif
57610   assert( (pMem->flags&MEM_RowSet)==0 );
57611   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
57612            || desiredEnc==SQLITE_UTF16BE );
57613   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
57614     return SQLITE_OK;
57615   }
57616   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57617 #ifdef SQLITE_OMIT_UTF16
57618   return SQLITE_ERROR;
57619 #else
57620 
57621   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
57622   ** then the encoding of the value may not have changed.
57623   */
57624   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
57625   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
57626   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
57627   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
57628   return rc;
57629 #endif
57630 }
57631 
57632 /*
57633 ** Make sure pMem->z points to a writable allocation of at least
57634 ** n bytes.
57635 **
57636 ** If the third argument passed to this function is true, then memory
57637 ** cell pMem must contain a string or blob. In this case the content is
57638 ** preserved. Otherwise, if the third parameter to this function is false,
57639 ** any current string or blob value may be discarded.
57640 **
57641 ** This function sets the MEM_Dyn flag and clears any xDel callback.
57642 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
57643 ** not set, Mem.n is zeroed.
57644 */
57645 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
57646   assert( 1 >=
57647     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
57648     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
57649     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
57650     ((pMem->flags&MEM_Static) ? 1 : 0)
57651   );
57652   assert( (pMem->flags&MEM_RowSet)==0 );
57653 
57654   /* If the preserve flag is set to true, then the memory cell must already
57655   ** contain a valid string or blob value.  */
57656   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
57657 
57658   if( n<32 ) n = 32;
57659   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
57660     if( preserve && pMem->z==pMem->zMalloc ){
57661       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
57662       preserve = 0;
57663     }else{
57664       sqlite3DbFree(pMem->db, pMem->zMalloc);
57665       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
57666     }
57667   }
57668 
57669   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
57670     memcpy(pMem->zMalloc, pMem->z, pMem->n);
57671   }
57672   if( pMem->flags&MEM_Dyn && pMem->xDel ){
57673     assert( pMem->xDel!=SQLITE_DYNAMIC );
57674     pMem->xDel((void *)(pMem->z));
57675   }
57676 
57677   pMem->z = pMem->zMalloc;
57678   if( pMem->z==0 ){
57679     pMem->flags = MEM_Null;
57680   }else{
57681     pMem->flags &= ~(MEM_Ephem|MEM_Static);
57682   }
57683   pMem->xDel = 0;
57684   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
57685 }
57686 
57687 /*
57688 ** Make the given Mem object MEM_Dyn.  In other words, make it so
57689 ** that any TEXT or BLOB content is stored in memory obtained from
57690 ** malloc().  In this way, we know that the memory is safe to be
57691 ** overwritten or altered.
57692 **
57693 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
57694 */
57695 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
57696   int f;
57697   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57698   assert( (pMem->flags&MEM_RowSet)==0 );
57699   ExpandBlob(pMem);
57700   f = pMem->flags;
57701   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
57702     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
57703       return SQLITE_NOMEM;
57704     }
57705     pMem->z[pMem->n] = 0;
57706     pMem->z[pMem->n+1] = 0;
57707     pMem->flags |= MEM_Term;
57708 #ifdef SQLITE_DEBUG
57709     pMem->pScopyFrom = 0;
57710 #endif
57711   }
57712 
57713   return SQLITE_OK;
57714 }
57715 
57716 /*
57717 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
57718 ** blob stored in dynamically allocated space.
57719 */
57720 #ifndef SQLITE_OMIT_INCRBLOB
57721 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
57722   if( pMem->flags & MEM_Zero ){
57723     int nByte;
57724     assert( pMem->flags&MEM_Blob );
57725     assert( (pMem->flags&MEM_RowSet)==0 );
57726     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57727 
57728     /* Set nByte to the number of bytes required to store the expanded blob. */
57729     nByte = pMem->n + pMem->u.nZero;
57730     if( nByte<=0 ){
57731       nByte = 1;
57732     }
57733     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
57734       return SQLITE_NOMEM;
57735     }
57736 
57737     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
57738     pMem->n += pMem->u.nZero;
57739     pMem->flags &= ~(MEM_Zero|MEM_Term);
57740   }
57741   return SQLITE_OK;
57742 }
57743 #endif
57744 
57745 
57746 /*
57747 ** Make sure the given Mem is \u0000 terminated.
57748 */
57749 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
57750   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57751   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
57752     return SQLITE_OK;   /* Nothing to do */
57753   }
57754   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
57755     return SQLITE_NOMEM;
57756   }
57757   pMem->z[pMem->n] = 0;
57758   pMem->z[pMem->n+1] = 0;
57759   pMem->flags |= MEM_Term;
57760   return SQLITE_OK;
57761 }
57762 
57763 /*
57764 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
57765 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
57766 ** is a no-op.
57767 **
57768 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
57769 **
57770 ** A MEM_Null value will never be passed to this function. This function is
57771 ** used for converting values to text for returning to the user (i.e. via
57772 ** sqlite3_value_text()), or for ensuring that values to be used as btree
57773 ** keys are strings. In the former case a NULL pointer is returned the
57774 ** user and the later is an internal programming error.
57775 */
57776 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
57777   int rc = SQLITE_OK;
57778   int fg = pMem->flags;
57779   const int nByte = 32;
57780 
57781   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57782   assert( !(fg&MEM_Zero) );
57783   assert( !(fg&(MEM_Str|MEM_Blob)) );
57784   assert( fg&(MEM_Int|MEM_Real) );
57785   assert( (pMem->flags&MEM_RowSet)==0 );
57786   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57787 
57788 
57789   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57790     return SQLITE_NOMEM;
57791   }
57792 
57793   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
57794   ** string representation of the value. Then, if the required encoding
57795   ** is UTF-16le or UTF-16be do a translation.
57796   **
57797   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
57798   */
57799   if( fg & MEM_Int ){
57800     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
57801   }else{
57802     assert( fg & MEM_Real );
57803     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
57804   }
57805   pMem->n = sqlite3Strlen30(pMem->z);
57806   pMem->enc = SQLITE_UTF8;
57807   pMem->flags |= MEM_Str|MEM_Term;
57808   sqlite3VdbeChangeEncoding(pMem, enc);
57809   return rc;
57810 }
57811 
57812 /*
57813 ** Memory cell pMem contains the context of an aggregate function.
57814 ** This routine calls the finalize method for that function.  The
57815 ** result of the aggregate is stored back into pMem.
57816 **
57817 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
57818 ** otherwise.
57819 */
57820 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
57821   int rc = SQLITE_OK;
57822   if( ALWAYS(pFunc && pFunc->xFinalize) ){
57823     sqlite3_context ctx;
57824     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
57825     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57826     memset(&ctx, 0, sizeof(ctx));
57827     ctx.s.flags = MEM_Null;
57828     ctx.s.db = pMem->db;
57829     ctx.pMem = pMem;
57830     ctx.pFunc = pFunc;
57831     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
57832     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
57833     sqlite3DbFree(pMem->db, pMem->zMalloc);
57834     memcpy(pMem, &ctx.s, sizeof(ctx.s));
57835     rc = ctx.isError;
57836   }
57837   return rc;
57838 }
57839 
57840 /*
57841 ** If the memory cell contains a string value that must be freed by
57842 ** invoking an external callback, free it now. Calling this function
57843 ** does not free any Mem.zMalloc buffer.
57844 */
57845 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
57846   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
57847   if( p->flags&MEM_Agg ){
57848     sqlite3VdbeMemFinalize(p, p->u.pDef);
57849     assert( (p->flags & MEM_Agg)==0 );
57850     sqlite3VdbeMemRelease(p);
57851   }else if( p->flags&MEM_Dyn && p->xDel ){
57852     assert( (p->flags&MEM_RowSet)==0 );
57853     assert( p->xDel!=SQLITE_DYNAMIC );
57854     p->xDel((void *)p->z);
57855     p->xDel = 0;
57856   }else if( p->flags&MEM_RowSet ){
57857     sqlite3RowSetClear(p->u.pRowSet);
57858   }else if( p->flags&MEM_Frame ){
57859     sqlite3VdbeMemSetNull(p);
57860   }
57861 }
57862 
57863 /*
57864 ** Release any memory held by the Mem. This may leave the Mem in an
57865 ** inconsistent state, for example with (Mem.z==0) and
57866 ** (Mem.type==SQLITE_TEXT).
57867 */
57868 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
57869   VdbeMemRelease(p);
57870   sqlite3DbFree(p->db, p->zMalloc);
57871   p->z = 0;
57872   p->zMalloc = 0;
57873   p->xDel = 0;
57874 }
57875 
57876 /*
57877 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
57878 ** If the double is too large, return 0x8000000000000000.
57879 **
57880 ** Most systems appear to do this simply by assigning
57881 ** variables and without the extra range tests.  But
57882 ** there are reports that windows throws an expection
57883 ** if the floating point value is out of range. (See ticket #2880.)
57884 ** Because we do not completely understand the problem, we will
57885 ** take the conservative approach and always do range tests
57886 ** before attempting the conversion.
57887 */
57888 static i64 doubleToInt64(double r){
57889 #ifdef SQLITE_OMIT_FLOATING_POINT
57890   /* When floating-point is omitted, double and int64 are the same thing */
57891   return r;
57892 #else
57893   /*
57894   ** Many compilers we encounter do not define constants for the
57895   ** minimum and maximum 64-bit integers, or they define them
57896   ** inconsistently.  And many do not understand the "LL" notation.
57897   ** So we define our own static constants here using nothing
57898   ** larger than a 32-bit integer constant.
57899   */
57900   static const i64 maxInt = LARGEST_INT64;
57901   static const i64 minInt = SMALLEST_INT64;
57902 
57903   if( r<(double)minInt ){
57904     return minInt;
57905   }else if( r>(double)maxInt ){
57906     /* minInt is correct here - not maxInt.  It turns out that assigning
57907     ** a very large positive number to an integer results in a very large
57908     ** negative integer.  This makes no sense, but it is what x86 hardware
57909     ** does so for compatibility we will do the same in software. */
57910     return minInt;
57911   }else{
57912     return (i64)r;
57913   }
57914 #endif
57915 }
57916 
57917 /*
57918 ** Return some kind of integer value which is the best we can do
57919 ** at representing the value that *pMem describes as an integer.
57920 ** If pMem is an integer, then the value is exact.  If pMem is
57921 ** a floating-point then the value returned is the integer part.
57922 ** If pMem is a string or blob, then we make an attempt to convert
57923 ** it into a integer and return that.  If pMem represents an
57924 ** an SQL-NULL value, return 0.
57925 **
57926 ** If pMem represents a string value, its encoding might be changed.
57927 */
57928 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
57929   int flags;
57930   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57931   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57932   flags = pMem->flags;
57933   if( flags & MEM_Int ){
57934     return pMem->u.i;
57935   }else if( flags & MEM_Real ){
57936     return doubleToInt64(pMem->r);
57937   }else if( flags & (MEM_Str|MEM_Blob) ){
57938     i64 value = 0;
57939     assert( pMem->z || pMem->n==0 );
57940     testcase( pMem->z==0 );
57941     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
57942     return value;
57943   }else{
57944     return 0;
57945   }
57946 }
57947 
57948 /*
57949 ** Return the best representation of pMem that we can get into a
57950 ** double.  If pMem is already a double or an integer, return its
57951 ** value.  If it is a string or blob, try to convert it to a double.
57952 ** If it is a NULL, return 0.0.
57953 */
57954 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
57955   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57956   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57957   if( pMem->flags & MEM_Real ){
57958     return pMem->r;
57959   }else if( pMem->flags & MEM_Int ){
57960     return (double)pMem->u.i;
57961   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
57962     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57963     double val = (double)0;
57964     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
57965     return val;
57966   }else{
57967     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57968     return (double)0;
57969   }
57970 }
57971 
57972 /*
57973 ** The MEM structure is already a MEM_Real.  Try to also make it a
57974 ** MEM_Int if we can.
57975 */
57976 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
57977   assert( pMem->flags & MEM_Real );
57978   assert( (pMem->flags & MEM_RowSet)==0 );
57979   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57980   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57981 
57982   pMem->u.i = doubleToInt64(pMem->r);
57983 
57984   /* Only mark the value as an integer if
57985   **
57986   **    (1) the round-trip conversion real->int->real is a no-op, and
57987   **    (2) The integer is neither the largest nor the smallest
57988   **        possible integer (ticket #3922)
57989   **
57990   ** The second and third terms in the following conditional enforces
57991   ** the second condition under the assumption that addition overflow causes
57992   ** values to wrap around.  On x86 hardware, the third term is always
57993   ** true and could be omitted.  But we leave it in because other
57994   ** architectures might behave differently.
57995   */
57996   if( pMem->r==(double)pMem->u.i
57997    && pMem->u.i>SMALLEST_INT64
57998 #if defined(__i486__) || defined(__x86_64__)
57999    && ALWAYS(pMem->u.i<LARGEST_INT64)
58000 #else
58001    && pMem->u.i<LARGEST_INT64
58002 #endif
58003   ){
58004     pMem->flags |= MEM_Int;
58005   }
58006 }
58007 
58008 /*
58009 ** Convert pMem to type integer.  Invalidate any prior representations.
58010 */
58011 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
58012   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58013   assert( (pMem->flags & MEM_RowSet)==0 );
58014   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58015 
58016   pMem->u.i = sqlite3VdbeIntValue(pMem);
58017   MemSetTypeFlag(pMem, MEM_Int);
58018   return SQLITE_OK;
58019 }
58020 
58021 /*
58022 ** Convert pMem so that it is of type MEM_Real.
58023 ** Invalidate any prior representations.
58024 */
58025 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
58026   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58027   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58028 
58029   pMem->r = sqlite3VdbeRealValue(pMem);
58030   MemSetTypeFlag(pMem, MEM_Real);
58031   return SQLITE_OK;
58032 }
58033 
58034 /*
58035 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
58036 ** Invalidate any prior representations.
58037 **
58038 ** Every effort is made to force the conversion, even if the input
58039 ** is a string that does not look completely like a number.  Convert
58040 ** as much of the string as we can and ignore the rest.
58041 */
58042 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
58043   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
58044     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
58045     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58046     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
58047       MemSetTypeFlag(pMem, MEM_Int);
58048     }else{
58049       pMem->r = sqlite3VdbeRealValue(pMem);
58050       MemSetTypeFlag(pMem, MEM_Real);
58051       sqlite3VdbeIntegerAffinity(pMem);
58052     }
58053   }
58054   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
58055   pMem->flags &= ~(MEM_Str|MEM_Blob);
58056   return SQLITE_OK;
58057 }
58058 
58059 /*
58060 ** Delete any previous value and set the value stored in *pMem to NULL.
58061 */
58062 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
58063   if( pMem->flags & MEM_Frame ){
58064     VdbeFrame *pFrame = pMem->u.pFrame;
58065     pFrame->pParent = pFrame->v->pDelFrame;
58066     pFrame->v->pDelFrame = pFrame;
58067   }
58068   if( pMem->flags & MEM_RowSet ){
58069     sqlite3RowSetClear(pMem->u.pRowSet);
58070   }
58071   MemSetTypeFlag(pMem, MEM_Null);
58072   pMem->type = SQLITE_NULL;
58073 }
58074 
58075 /*
58076 ** Delete any previous value and set the value to be a BLOB of length
58077 ** n containing all zeros.
58078 */
58079 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
58080   sqlite3VdbeMemRelease(pMem);
58081   pMem->flags = MEM_Blob|MEM_Zero;
58082   pMem->type = SQLITE_BLOB;
58083   pMem->n = 0;
58084   if( n<0 ) n = 0;
58085   pMem->u.nZero = n;
58086   pMem->enc = SQLITE_UTF8;
58087 
58088 #ifdef SQLITE_OMIT_INCRBLOB
58089   sqlite3VdbeMemGrow(pMem, n, 0);
58090   if( pMem->z ){
58091     pMem->n = n;
58092     memset(pMem->z, 0, n);
58093   }
58094 #endif
58095 }
58096 
58097 /*
58098 ** Delete any previous value and set the value stored in *pMem to val,
58099 ** manifest type INTEGER.
58100 */
58101 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
58102   sqlite3VdbeMemRelease(pMem);
58103   pMem->u.i = val;
58104   pMem->flags = MEM_Int;
58105   pMem->type = SQLITE_INTEGER;
58106 }
58107 
58108 #ifndef SQLITE_OMIT_FLOATING_POINT
58109 /*
58110 ** Delete any previous value and set the value stored in *pMem to val,
58111 ** manifest type REAL.
58112 */
58113 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
58114   if( sqlite3IsNaN(val) ){
58115     sqlite3VdbeMemSetNull(pMem);
58116   }else{
58117     sqlite3VdbeMemRelease(pMem);
58118     pMem->r = val;
58119     pMem->flags = MEM_Real;
58120     pMem->type = SQLITE_FLOAT;
58121   }
58122 }
58123 #endif
58124 
58125 /*
58126 ** Delete any previous value and set the value of pMem to be an
58127 ** empty boolean index.
58128 */
58129 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
58130   sqlite3 *db = pMem->db;
58131   assert( db!=0 );
58132   assert( (pMem->flags & MEM_RowSet)==0 );
58133   sqlite3VdbeMemRelease(pMem);
58134   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
58135   if( db->mallocFailed ){
58136     pMem->flags = MEM_Null;
58137   }else{
58138     assert( pMem->zMalloc );
58139     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
58140                                        sqlite3DbMallocSize(db, pMem->zMalloc));
58141     assert( pMem->u.pRowSet!=0 );
58142     pMem->flags = MEM_RowSet;
58143   }
58144 }
58145 
58146 /*
58147 ** Return true if the Mem object contains a TEXT or BLOB that is
58148 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
58149 */
58150 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
58151   assert( p->db!=0 );
58152   if( p->flags & (MEM_Str|MEM_Blob) ){
58153     int n = p->n;
58154     if( p->flags & MEM_Zero ){
58155       n += p->u.nZero;
58156     }
58157     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
58158   }
58159   return 0;
58160 }
58161 
58162 #ifdef SQLITE_DEBUG
58163 /*
58164 ** This routine prepares a memory cell for modication by breaking
58165 ** its link to a shallow copy and by marking any current shallow
58166 ** copies of this cell as invalid.
58167 **
58168 ** This is used for testing and debugging only - to make sure shallow
58169 ** copies are not misused.
58170 */
58171 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
58172   int i;
58173   Mem *pX;
58174   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
58175     if( pX->pScopyFrom==pMem ){
58176       pX->flags |= MEM_Invalid;
58177       pX->pScopyFrom = 0;
58178     }
58179   }
58180   pMem->pScopyFrom = 0;
58181 }
58182 #endif /* SQLITE_DEBUG */
58183 
58184 /*
58185 ** Size of struct Mem not including the Mem.zMalloc member.
58186 */
58187 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
58188 
58189 /*
58190 ** Make an shallow copy of pFrom into pTo.  Prior contents of
58191 ** pTo are freed.  The pFrom->z field is not duplicated.  If
58192 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
58193 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
58194 */
58195 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
58196   assert( (pFrom->flags & MEM_RowSet)==0 );
58197   VdbeMemRelease(pTo);
58198   memcpy(pTo, pFrom, MEMCELLSIZE);
58199   pTo->xDel = 0;
58200   if( (pFrom->flags&MEM_Static)==0 ){
58201     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
58202     assert( srcType==MEM_Ephem || srcType==MEM_Static );
58203     pTo->flags |= srcType;
58204   }
58205 }
58206 
58207 /*
58208 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
58209 ** freed before the copy is made.
58210 */
58211 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
58212   int rc = SQLITE_OK;
58213 
58214   assert( (pFrom->flags & MEM_RowSet)==0 );
58215   VdbeMemRelease(pTo);
58216   memcpy(pTo, pFrom, MEMCELLSIZE);
58217   pTo->flags &= ~MEM_Dyn;
58218 
58219   if( pTo->flags&(MEM_Str|MEM_Blob) ){
58220     if( 0==(pFrom->flags&MEM_Static) ){
58221       pTo->flags |= MEM_Ephem;
58222       rc = sqlite3VdbeMemMakeWriteable(pTo);
58223     }
58224   }
58225 
58226   return rc;
58227 }
58228 
58229 /*
58230 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
58231 ** freed. If pFrom contains ephemeral data, a copy is made.
58232 **
58233 ** pFrom contains an SQL NULL when this routine returns.
58234 */
58235 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
58236   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
58237   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
58238   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
58239 
58240   sqlite3VdbeMemRelease(pTo);
58241   memcpy(pTo, pFrom, sizeof(Mem));
58242   pFrom->flags = MEM_Null;
58243   pFrom->xDel = 0;
58244   pFrom->zMalloc = 0;
58245 }
58246 
58247 /*
58248 ** Change the value of a Mem to be a string or a BLOB.
58249 **
58250 ** The memory management strategy depends on the value of the xDel
58251 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
58252 ** string is copied into a (possibly existing) buffer managed by the
58253 ** Mem structure. Otherwise, any existing buffer is freed and the
58254 ** pointer copied.
58255 **
58256 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
58257 ** size limit) then no memory allocation occurs.  If the string can be
58258 ** stored without allocating memory, then it is.  If a memory allocation
58259 ** is required to store the string, then value of pMem is unchanged.  In
58260 ** either case, SQLITE_TOOBIG is returned.
58261 */
58262 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
58263   Mem *pMem,          /* Memory cell to set to string value */
58264   const char *z,      /* String pointer */
58265   int n,              /* Bytes in string, or negative */
58266   u8 enc,             /* Encoding of z.  0 for BLOBs */
58267   void (*xDel)(void*) /* Destructor function */
58268 ){
58269   int nByte = n;      /* New value for pMem->n */
58270   int iLimit;         /* Maximum allowed string or blob size */
58271   u16 flags = 0;      /* New value for pMem->flags */
58272 
58273   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58274   assert( (pMem->flags & MEM_RowSet)==0 );
58275 
58276   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
58277   if( !z ){
58278     sqlite3VdbeMemSetNull(pMem);
58279     return SQLITE_OK;
58280   }
58281 
58282   if( pMem->db ){
58283     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
58284   }else{
58285     iLimit = SQLITE_MAX_LENGTH;
58286   }
58287   flags = (enc==0?MEM_Blob:MEM_Str);
58288   if( nByte<0 ){
58289     assert( enc!=0 );
58290     if( enc==SQLITE_UTF8 ){
58291       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
58292     }else{
58293       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
58294     }
58295     flags |= MEM_Term;
58296   }
58297 
58298   /* The following block sets the new values of Mem.z and Mem.xDel. It
58299   ** also sets a flag in local variable "flags" to indicate the memory
58300   ** management (one of MEM_Dyn or MEM_Static).
58301   */
58302   if( xDel==SQLITE_TRANSIENT ){
58303     int nAlloc = nByte;
58304     if( flags&MEM_Term ){
58305       nAlloc += (enc==SQLITE_UTF8?1:2);
58306     }
58307     if( nByte>iLimit ){
58308       return SQLITE_TOOBIG;
58309     }
58310     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
58311       return SQLITE_NOMEM;
58312     }
58313     memcpy(pMem->z, z, nAlloc);
58314   }else if( xDel==SQLITE_DYNAMIC ){
58315     sqlite3VdbeMemRelease(pMem);
58316     pMem->zMalloc = pMem->z = (char *)z;
58317     pMem->xDel = 0;
58318   }else{
58319     sqlite3VdbeMemRelease(pMem);
58320     pMem->z = (char *)z;
58321     pMem->xDel = xDel;
58322     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
58323   }
58324 
58325   pMem->n = nByte;
58326   pMem->flags = flags;
58327   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
58328   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
58329 
58330 #ifndef SQLITE_OMIT_UTF16
58331   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
58332     return SQLITE_NOMEM;
58333   }
58334 #endif
58335 
58336   if( nByte>iLimit ){
58337     return SQLITE_TOOBIG;
58338   }
58339 
58340   return SQLITE_OK;
58341 }
58342 
58343 /*
58344 ** Compare the values contained by the two memory cells, returning
58345 ** negative, zero or positive if pMem1 is less than, equal to, or greater
58346 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
58347 ** and reals) sorted numerically, followed by text ordered by the collating
58348 ** sequence pColl and finally blob's ordered by memcmp().
58349 **
58350 ** Two NULL values are considered equal by this function.
58351 */
58352 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
58353   int rc;
58354   int f1, f2;
58355   int combined_flags;
58356 
58357   f1 = pMem1->flags;
58358   f2 = pMem2->flags;
58359   combined_flags = f1|f2;
58360   assert( (combined_flags & MEM_RowSet)==0 );
58361 
58362   /* If one value is NULL, it is less than the other. If both values
58363   ** are NULL, return 0.
58364   */
58365   if( combined_flags&MEM_Null ){
58366     return (f2&MEM_Null) - (f1&MEM_Null);
58367   }
58368 
58369   /* If one value is a number and the other is not, the number is less.
58370   ** If both are numbers, compare as reals if one is a real, or as integers
58371   ** if both values are integers.
58372   */
58373   if( combined_flags&(MEM_Int|MEM_Real) ){
58374     if( !(f1&(MEM_Int|MEM_Real)) ){
58375       return 1;
58376     }
58377     if( !(f2&(MEM_Int|MEM_Real)) ){
58378       return -1;
58379     }
58380     if( (f1 & f2 & MEM_Int)==0 ){
58381       double r1, r2;
58382       if( (f1&MEM_Real)==0 ){
58383         r1 = (double)pMem1->u.i;
58384       }else{
58385         r1 = pMem1->r;
58386       }
58387       if( (f2&MEM_Real)==0 ){
58388         r2 = (double)pMem2->u.i;
58389       }else{
58390         r2 = pMem2->r;
58391       }
58392       if( r1<r2 ) return -1;
58393       if( r1>r2 ) return 1;
58394       return 0;
58395     }else{
58396       assert( f1&MEM_Int );
58397       assert( f2&MEM_Int );
58398       if( pMem1->u.i < pMem2->u.i ) return -1;
58399       if( pMem1->u.i > pMem2->u.i ) return 1;
58400       return 0;
58401     }
58402   }
58403 
58404   /* If one value is a string and the other is a blob, the string is less.
58405   ** If both are strings, compare using the collating functions.
58406   */
58407   if( combined_flags&MEM_Str ){
58408     if( (f1 & MEM_Str)==0 ){
58409       return 1;
58410     }
58411     if( (f2 & MEM_Str)==0 ){
58412       return -1;
58413     }
58414 
58415     assert( pMem1->enc==pMem2->enc );
58416     assert( pMem1->enc==SQLITE_UTF8 ||
58417             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
58418 
58419     /* The collation sequence must be defined at this point, even if
58420     ** the user deletes the collation sequence after the vdbe program is
58421     ** compiled (this was not always the case).
58422     */
58423     assert( !pColl || pColl->xCmp );
58424 
58425     if( pColl ){
58426       if( pMem1->enc==pColl->enc ){
58427         /* The strings are already in the correct encoding.  Call the
58428         ** comparison function directly */
58429         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
58430       }else{
58431         const void *v1, *v2;
58432         int n1, n2;
58433         Mem c1;
58434         Mem c2;
58435         memset(&c1, 0, sizeof(c1));
58436         memset(&c2, 0, sizeof(c2));
58437         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
58438         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
58439         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
58440         n1 = v1==0 ? 0 : c1.n;
58441         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
58442         n2 = v2==0 ? 0 : c2.n;
58443         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
58444         sqlite3VdbeMemRelease(&c1);
58445         sqlite3VdbeMemRelease(&c2);
58446         return rc;
58447       }
58448     }
58449     /* If a NULL pointer was passed as the collate function, fall through
58450     ** to the blob case and use memcmp().  */
58451   }
58452 
58453   /* Both values must be blobs.  Compare using memcmp().  */
58454   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
58455   if( rc==0 ){
58456     rc = pMem1->n - pMem2->n;
58457   }
58458   return rc;
58459 }
58460 
58461 /*
58462 ** Move data out of a btree key or data field and into a Mem structure.
58463 ** The data or key is taken from the entry that pCur is currently pointing
58464 ** to.  offset and amt determine what portion of the data or key to retrieve.
58465 ** key is true to get the key or false to get data.  The result is written
58466 ** into the pMem element.
58467 **
58468 ** The pMem structure is assumed to be uninitialized.  Any prior content
58469 ** is overwritten without being freed.
58470 **
58471 ** If this routine fails for any reason (malloc returns NULL or unable
58472 ** to read from the disk) then the pMem is left in an inconsistent state.
58473 */
58474 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
58475   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
58476   int offset,       /* Offset from the start of data to return bytes from. */
58477   int amt,          /* Number of bytes to return. */
58478   int key,          /* If true, retrieve from the btree key, not data. */
58479   Mem *pMem         /* OUT: Return data in this Mem structure. */
58480 ){
58481   char *zData;        /* Data from the btree layer */
58482   int available = 0;  /* Number of bytes available on the local btree page */
58483   int rc = SQLITE_OK; /* Return code */
58484 
58485   assert( sqlite3BtreeCursorIsValid(pCur) );
58486 
58487   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
58488   ** that both the BtShared and database handle mutexes are held. */
58489   assert( (pMem->flags & MEM_RowSet)==0 );
58490   if( key ){
58491     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
58492   }else{
58493     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
58494   }
58495   assert( zData!=0 );
58496 
58497   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
58498     sqlite3VdbeMemRelease(pMem);
58499     pMem->z = &zData[offset];
58500     pMem->flags = MEM_Blob|MEM_Ephem;
58501   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
58502     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
58503     pMem->enc = 0;
58504     pMem->type = SQLITE_BLOB;
58505     if( key ){
58506       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
58507     }else{
58508       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
58509     }
58510     pMem->z[amt] = 0;
58511     pMem->z[amt+1] = 0;
58512     if( rc!=SQLITE_OK ){
58513       sqlite3VdbeMemRelease(pMem);
58514     }
58515   }
58516   pMem->n = amt;
58517 
58518   return rc;
58519 }
58520 
58521 /* This function is only available internally, it is not part of the
58522 ** external API. It works in a similar way to sqlite3_value_text(),
58523 ** except the data returned is in the encoding specified by the second
58524 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
58525 ** SQLITE_UTF8.
58526 **
58527 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
58528 ** If that is the case, then the result must be aligned on an even byte
58529 ** boundary.
58530 */
58531 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
58532   if( !pVal ) return 0;
58533 
58534   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
58535   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
58536   assert( (pVal->flags & MEM_RowSet)==0 );
58537 
58538   if( pVal->flags&MEM_Null ){
58539     return 0;
58540   }
58541   assert( (MEM_Blob>>3) == MEM_Str );
58542   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
58543   ExpandBlob(pVal);
58544   if( pVal->flags&MEM_Str ){
58545     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
58546     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
58547       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
58548       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
58549         return 0;
58550       }
58551     }
58552     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
58553   }else{
58554     assert( (pVal->flags&MEM_Blob)==0 );
58555     sqlite3VdbeMemStringify(pVal, enc);
58556     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
58557   }
58558   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
58559               || pVal->db->mallocFailed );
58560   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
58561     return pVal->z;
58562   }else{
58563     return 0;
58564   }
58565 }
58566 
58567 /*
58568 ** Create a new sqlite3_value object.
58569 */
58570 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
58571   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
58572   if( p ){
58573     p->flags = MEM_Null;
58574     p->type = SQLITE_NULL;
58575     p->db = db;
58576   }
58577   return p;
58578 }
58579 
58580 /*
58581 ** Create a new sqlite3_value object, containing the value of pExpr.
58582 **
58583 ** This only works for very simple expressions that consist of one constant
58584 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
58585 ** be converted directly into a value, then the value is allocated and
58586 ** a pointer written to *ppVal. The caller is responsible for deallocating
58587 ** the value by passing it to sqlite3ValueFree() later on. If the expression
58588 ** cannot be converted to a value, then *ppVal is set to NULL.
58589 */
58590 SQLITE_PRIVATE int sqlite3ValueFromExpr(
58591   sqlite3 *db,              /* The database connection */
58592   Expr *pExpr,              /* The expression to evaluate */
58593   u8 enc,                   /* Encoding to use */
58594   u8 affinity,              /* Affinity to use */
58595   sqlite3_value **ppVal     /* Write the new value here */
58596 ){
58597   int op;
58598   char *zVal = 0;
58599   sqlite3_value *pVal = 0;
58600   int negInt = 1;
58601   const char *zNeg = "";
58602 
58603   if( !pExpr ){
58604     *ppVal = 0;
58605     return SQLITE_OK;
58606   }
58607   op = pExpr->op;
58608 
58609   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
58610   ** The ifdef here is to enable us to achieve 100% branch test coverage even
58611   ** when SQLITE_ENABLE_STAT3 is omitted.
58612   */
58613 #ifdef SQLITE_ENABLE_STAT3
58614   if( op==TK_REGISTER ) op = pExpr->op2;
58615 #else
58616   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
58617 #endif
58618 
58619   /* Handle negative integers in a single step.  This is needed in the
58620   ** case when the value is -9223372036854775808.
58621   */
58622   if( op==TK_UMINUS
58623    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
58624     pExpr = pExpr->pLeft;
58625     op = pExpr->op;
58626     negInt = -1;
58627     zNeg = "-";
58628   }
58629 
58630   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
58631     pVal = sqlite3ValueNew(db);
58632     if( pVal==0 ) goto no_mem;
58633     if( ExprHasProperty(pExpr, EP_IntValue) ){
58634       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
58635     }else{
58636       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
58637       if( zVal==0 ) goto no_mem;
58638       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
58639       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
58640     }
58641     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
58642       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
58643     }else{
58644       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
58645     }
58646     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
58647     if( enc!=SQLITE_UTF8 ){
58648       sqlite3VdbeChangeEncoding(pVal, enc);
58649     }
58650   }else if( op==TK_UMINUS ) {
58651     /* This branch happens for multiple negative signs.  Ex: -(-5) */
58652     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
58653       sqlite3VdbeMemNumerify(pVal);
58654       if( pVal->u.i==SMALLEST_INT64 ){
58655         pVal->flags &= MEM_Int;
58656         pVal->flags |= MEM_Real;
58657         pVal->r = (double)LARGEST_INT64;
58658       }else{
58659         pVal->u.i = -pVal->u.i;
58660       }
58661       pVal->r = -pVal->r;
58662       sqlite3ValueApplyAffinity(pVal, affinity, enc);
58663     }
58664   }else if( op==TK_NULL ){
58665     pVal = sqlite3ValueNew(db);
58666     if( pVal==0 ) goto no_mem;
58667   }
58668 #ifndef SQLITE_OMIT_BLOB_LITERAL
58669   else if( op==TK_BLOB ){
58670     int nVal;
58671     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
58672     assert( pExpr->u.zToken[1]=='\'' );
58673     pVal = sqlite3ValueNew(db);
58674     if( !pVal ) goto no_mem;
58675     zVal = &pExpr->u.zToken[2];
58676     nVal = sqlite3Strlen30(zVal)-1;
58677     assert( zVal[nVal]=='\'' );
58678     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
58679                          0, SQLITE_DYNAMIC);
58680   }
58681 #endif
58682 
58683   if( pVal ){
58684     sqlite3VdbeMemStoreType(pVal);
58685   }
58686   *ppVal = pVal;
58687   return SQLITE_OK;
58688 
58689 no_mem:
58690   db->mallocFailed = 1;
58691   sqlite3DbFree(db, zVal);
58692   sqlite3ValueFree(pVal);
58693   *ppVal = 0;
58694   return SQLITE_NOMEM;
58695 }
58696 
58697 /*
58698 ** Change the string value of an sqlite3_value object
58699 */
58700 SQLITE_PRIVATE void sqlite3ValueSetStr(
58701   sqlite3_value *v,     /* Value to be set */
58702   int n,                /* Length of string z */
58703   const void *z,        /* Text of the new string */
58704   u8 enc,               /* Encoding to use */
58705   void (*xDel)(void*)   /* Destructor for the string */
58706 ){
58707   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
58708 }
58709 
58710 /*
58711 ** Free an sqlite3_value object
58712 */
58713 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
58714   if( !v ) return;
58715   sqlite3VdbeMemRelease((Mem *)v);
58716   sqlite3DbFree(((Mem*)v)->db, v);
58717 }
58718 
58719 /*
58720 ** Return the number of bytes in the sqlite3_value object assuming
58721 ** that it uses the encoding "enc"
58722 */
58723 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
58724   Mem *p = (Mem*)pVal;
58725   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
58726     if( p->flags & MEM_Zero ){
58727       return p->n + p->u.nZero;
58728     }else{
58729       return p->n;
58730     }
58731   }
58732   return 0;
58733 }
58734 
58735 /************** End of vdbemem.c *********************************************/
58736 /************** Begin file vdbeaux.c *****************************************/
58737 /*
58738 ** 2003 September 6
58739 **
58740 ** The author disclaims copyright to this source code.  In place of
58741 ** a legal notice, here is a blessing:
58742 **
58743 **    May you do good and not evil.
58744 **    May you find forgiveness for yourself and forgive others.
58745 **    May you share freely, never taking more than you give.
58746 **
58747 *************************************************************************
58748 ** This file contains code used for creating, destroying, and populating
58749 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
58750 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
58751 ** But that file was getting too big so this subroutines were split out.
58752 */
58753 
58754 /*
58755 ** Create a new virtual database engine.
58756 */
58757 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
58758   Vdbe *p;
58759   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
58760   if( p==0 ) return 0;
58761   p->db = db;
58762   if( db->pVdbe ){
58763     db->pVdbe->pPrev = p;
58764   }
58765   p->pNext = db->pVdbe;
58766   p->pPrev = 0;
58767   db->pVdbe = p;
58768   p->magic = VDBE_MAGIC_INIT;
58769   return p;
58770 }
58771 
58772 /*
58773 ** Remember the SQL string for a prepared statement.
58774 */
58775 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
58776   assert( isPrepareV2==1 || isPrepareV2==0 );
58777   if( p==0 ) return;
58778 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
58779   if( !isPrepareV2 ) return;
58780 #endif
58781   assert( p->zSql==0 );
58782   p->zSql = sqlite3DbStrNDup(p->db, z, n);
58783   p->isPrepareV2 = (u8)isPrepareV2;
58784 }
58785 
58786 /*
58787 ** Return the SQL associated with a prepared statement
58788 */
58789 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
58790   Vdbe *p = (Vdbe *)pStmt;
58791   return (p && p->isPrepareV2) ? p->zSql : 0;
58792 }
58793 
58794 /*
58795 ** Swap all content between two VDBE structures.
58796 */
58797 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
58798   Vdbe tmp, *pTmp;
58799   char *zTmp;
58800   tmp = *pA;
58801   *pA = *pB;
58802   *pB = tmp;
58803   pTmp = pA->pNext;
58804   pA->pNext = pB->pNext;
58805   pB->pNext = pTmp;
58806   pTmp = pA->pPrev;
58807   pA->pPrev = pB->pPrev;
58808   pB->pPrev = pTmp;
58809   zTmp = pA->zSql;
58810   pA->zSql = pB->zSql;
58811   pB->zSql = zTmp;
58812   pB->isPrepareV2 = pA->isPrepareV2;
58813 }
58814 
58815 #ifdef SQLITE_DEBUG
58816 /*
58817 ** Turn tracing on or off
58818 */
58819 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
58820   p->trace = trace;
58821 }
58822 #endif
58823 
58824 /*
58825 ** Resize the Vdbe.aOp array so that it is at least one op larger than
58826 ** it was.
58827 **
58828 ** If an out-of-memory error occurs while resizing the array, return
58829 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
58830 ** unchanged (this is so that any opcodes already allocated can be
58831 ** correctly deallocated along with the rest of the Vdbe).
58832 */
58833 static int growOpArray(Vdbe *p){
58834   VdbeOp *pNew;
58835   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
58836   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
58837   if( pNew ){
58838     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
58839     p->aOp = pNew;
58840   }
58841   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
58842 }
58843 
58844 /*
58845 ** Add a new instruction to the list of instructions current in the
58846 ** VDBE.  Return the address of the new instruction.
58847 **
58848 ** Parameters:
58849 **
58850 **    p               Pointer to the VDBE
58851 **
58852 **    op              The opcode for this instruction
58853 **
58854 **    p1, p2, p3      Operands
58855 **
58856 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
58857 ** the sqlite3VdbeChangeP4() function to change the value of the P4
58858 ** operand.
58859 */
58860 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
58861   int i;
58862   VdbeOp *pOp;
58863 
58864   i = p->nOp;
58865   assert( p->magic==VDBE_MAGIC_INIT );
58866   assert( op>0 && op<0xff );
58867   if( p->nOpAlloc<=i ){
58868     if( growOpArray(p) ){
58869       return 1;
58870     }
58871   }
58872   p->nOp++;
58873   pOp = &p->aOp[i];
58874   pOp->opcode = (u8)op;
58875   pOp->p5 = 0;
58876   pOp->p1 = p1;
58877   pOp->p2 = p2;
58878   pOp->p3 = p3;
58879   pOp->p4.p = 0;
58880   pOp->p4type = P4_NOTUSED;
58881 #ifdef SQLITE_DEBUG
58882   pOp->zComment = 0;
58883   if( p->db->flags & SQLITE_VdbeAddopTrace ){
58884     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
58885   }
58886 #endif
58887 #ifdef VDBE_PROFILE
58888   pOp->cycles = 0;
58889   pOp->cnt = 0;
58890 #endif
58891   return i;
58892 }
58893 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
58894   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
58895 }
58896 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
58897   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
58898 }
58899 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
58900   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
58901 }
58902 
58903 
58904 /*
58905 ** Add an opcode that includes the p4 value as a pointer.
58906 */
58907 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
58908   Vdbe *p,            /* Add the opcode to this VM */
58909   int op,             /* The new opcode */
58910   int p1,             /* The P1 operand */
58911   int p2,             /* The P2 operand */
58912   int p3,             /* The P3 operand */
58913   const char *zP4,    /* The P4 operand */
58914   int p4type          /* P4 operand type */
58915 ){
58916   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58917   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
58918   return addr;
58919 }
58920 
58921 /*
58922 ** Add an OP_ParseSchema opcode.  This routine is broken out from
58923 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
58924 ** as having been used.
58925 **
58926 ** The zWhere string must have been obtained from sqlite3_malloc().
58927 ** This routine will take ownership of the allocated memory.
58928 */
58929 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
58930   int j;
58931   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
58932   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
58933   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
58934 }
58935 
58936 /*
58937 ** Add an opcode that includes the p4 value as an integer.
58938 */
58939 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
58940   Vdbe *p,            /* Add the opcode to this VM */
58941   int op,             /* The new opcode */
58942   int p1,             /* The P1 operand */
58943   int p2,             /* The P2 operand */
58944   int p3,             /* The P3 operand */
58945   int p4              /* The P4 operand as an integer */
58946 ){
58947   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58948   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
58949   return addr;
58950 }
58951 
58952 /*
58953 ** Create a new symbolic label for an instruction that has yet to be
58954 ** coded.  The symbolic label is really just a negative number.  The
58955 ** label can be used as the P2 value of an operation.  Later, when
58956 ** the label is resolved to a specific address, the VDBE will scan
58957 ** through its operation list and change all values of P2 which match
58958 ** the label into the resolved address.
58959 **
58960 ** The VDBE knows that a P2 value is a label because labels are
58961 ** always negative and P2 values are suppose to be non-negative.
58962 ** Hence, a negative P2 value is a label that has yet to be resolved.
58963 **
58964 ** Zero is returned if a malloc() fails.
58965 */
58966 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
58967   int i = p->nLabel++;
58968   assert( p->magic==VDBE_MAGIC_INIT );
58969   if( (i & (i-1))==0 ){
58970     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
58971                                        (i*2+1)*sizeof(p->aLabel[0]));
58972   }
58973   if( p->aLabel ){
58974     p->aLabel[i] = -1;
58975   }
58976   return -1-i;
58977 }
58978 
58979 /*
58980 ** Resolve label "x" to be the address of the next instruction to
58981 ** be inserted.  The parameter "x" must have been obtained from
58982 ** a prior call to sqlite3VdbeMakeLabel().
58983 */
58984 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
58985   int j = -1-x;
58986   assert( p->magic==VDBE_MAGIC_INIT );
58987   assert( j>=0 && j<p->nLabel );
58988   if( p->aLabel ){
58989     p->aLabel[j] = p->nOp;
58990   }
58991 }
58992 
58993 /*
58994 ** Mark the VDBE as one that can only be run one time.
58995 */
58996 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
58997   p->runOnlyOnce = 1;
58998 }
58999 
59000 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
59001 
59002 /*
59003 ** The following type and function are used to iterate through all opcodes
59004 ** in a Vdbe main program and each of the sub-programs (triggers) it may
59005 ** invoke directly or indirectly. It should be used as follows:
59006 **
59007 **   Op *pOp;
59008 **   VdbeOpIter sIter;
59009 **
59010 **   memset(&sIter, 0, sizeof(sIter));
59011 **   sIter.v = v;                            // v is of type Vdbe*
59012 **   while( (pOp = opIterNext(&sIter)) ){
59013 **     // Do something with pOp
59014 **   }
59015 **   sqlite3DbFree(v->db, sIter.apSub);
59016 **
59017 */
59018 typedef struct VdbeOpIter VdbeOpIter;
59019 struct VdbeOpIter {
59020   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
59021   SubProgram **apSub;        /* Array of subprograms */
59022   int nSub;                  /* Number of entries in apSub */
59023   int iAddr;                 /* Address of next instruction to return */
59024   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
59025 };
59026 static Op *opIterNext(VdbeOpIter *p){
59027   Vdbe *v = p->v;
59028   Op *pRet = 0;
59029   Op *aOp;
59030   int nOp;
59031 
59032   if( p->iSub<=p->nSub ){
59033 
59034     if( p->iSub==0 ){
59035       aOp = v->aOp;
59036       nOp = v->nOp;
59037     }else{
59038       aOp = p->apSub[p->iSub-1]->aOp;
59039       nOp = p->apSub[p->iSub-1]->nOp;
59040     }
59041     assert( p->iAddr<nOp );
59042 
59043     pRet = &aOp[p->iAddr];
59044     p->iAddr++;
59045     if( p->iAddr==nOp ){
59046       p->iSub++;
59047       p->iAddr = 0;
59048     }
59049 
59050     if( pRet->p4type==P4_SUBPROGRAM ){
59051       int nByte = (p->nSub+1)*sizeof(SubProgram*);
59052       int j;
59053       for(j=0; j<p->nSub; j++){
59054         if( p->apSub[j]==pRet->p4.pProgram ) break;
59055       }
59056       if( j==p->nSub ){
59057         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
59058         if( !p->apSub ){
59059           pRet = 0;
59060         }else{
59061           p->apSub[p->nSub++] = pRet->p4.pProgram;
59062         }
59063       }
59064     }
59065   }
59066 
59067   return pRet;
59068 }
59069 
59070 /*
59071 ** Check if the program stored in the VM associated with pParse may
59072 ** throw an ABORT exception (causing the statement, but not entire transaction
59073 ** to be rolled back). This condition is true if the main program or any
59074 ** sub-programs contains any of the following:
59075 **
59076 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59077 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59078 **   *  OP_Destroy
59079 **   *  OP_VUpdate
59080 **   *  OP_VRename
59081 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
59082 **
59083 ** Then check that the value of Parse.mayAbort is true if an
59084 ** ABORT may be thrown, or false otherwise. Return true if it does
59085 ** match, or false otherwise. This function is intended to be used as
59086 ** part of an assert statement in the compiler. Similar to:
59087 **
59088 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
59089 */
59090 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
59091   int hasAbort = 0;
59092   Op *pOp;
59093   VdbeOpIter sIter;
59094   memset(&sIter, 0, sizeof(sIter));
59095   sIter.v = v;
59096 
59097   while( (pOp = opIterNext(&sIter))!=0 ){
59098     int opcode = pOp->opcode;
59099     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
59100 #ifndef SQLITE_OMIT_FOREIGN_KEY
59101      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
59102 #endif
59103      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
59104       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
59105     ){
59106       hasAbort = 1;
59107       break;
59108     }
59109   }
59110   sqlite3DbFree(v->db, sIter.apSub);
59111 
59112   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
59113   ** If malloc failed, then the while() loop above may not have iterated
59114   ** through all opcodes and hasAbort may be set incorrectly. Return
59115   ** true for this case to prevent the assert() in the callers frame
59116   ** from failing.  */
59117   return ( v->db->mallocFailed || hasAbort==mayAbort );
59118 }
59119 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
59120 
59121 /*
59122 ** Loop through the program looking for P2 values that are negative
59123 ** on jump instructions.  Each such value is a label.  Resolve the
59124 ** label by setting the P2 value to its correct non-zero value.
59125 **
59126 ** This routine is called once after all opcodes have been inserted.
59127 **
59128 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
59129 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
59130 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
59131 **
59132 ** The Op.opflags field is set on all opcodes.
59133 */
59134 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
59135   int i;
59136   int nMaxArgs = *pMaxFuncArgs;
59137   Op *pOp;
59138   int *aLabel = p->aLabel;
59139   p->readOnly = 1;
59140   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
59141     u8 opcode = pOp->opcode;
59142 
59143     pOp->opflags = sqlite3OpcodeProperty[opcode];
59144     if( opcode==OP_Function || opcode==OP_AggStep ){
59145       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
59146     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
59147       p->readOnly = 0;
59148 #ifndef SQLITE_OMIT_VIRTUALTABLE
59149     }else if( opcode==OP_VUpdate ){
59150       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
59151     }else if( opcode==OP_VFilter ){
59152       int n;
59153       assert( p->nOp - i >= 3 );
59154       assert( pOp[-1].opcode==OP_Integer );
59155       n = pOp[-1].p1;
59156       if( n>nMaxArgs ) nMaxArgs = n;
59157 #endif
59158     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
59159       pOp->p4.xAdvance = sqlite3BtreeNext;
59160       pOp->p4type = P4_ADVANCE;
59161     }else if( opcode==OP_Prev ){
59162       pOp->p4.xAdvance = sqlite3BtreePrevious;
59163       pOp->p4type = P4_ADVANCE;
59164     }
59165 
59166     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
59167       assert( -1-pOp->p2<p->nLabel );
59168       pOp->p2 = aLabel[-1-pOp->p2];
59169     }
59170   }
59171   sqlite3DbFree(p->db, p->aLabel);
59172   p->aLabel = 0;
59173 
59174   *pMaxFuncArgs = nMaxArgs;
59175 }
59176 
59177 /*
59178 ** Return the address of the next instruction to be inserted.
59179 */
59180 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
59181   assert( p->magic==VDBE_MAGIC_INIT );
59182   return p->nOp;
59183 }
59184 
59185 /*
59186 ** This function returns a pointer to the array of opcodes associated with
59187 ** the Vdbe passed as the first argument. It is the callers responsibility
59188 ** to arrange for the returned array to be eventually freed using the
59189 ** vdbeFreeOpArray() function.
59190 **
59191 ** Before returning, *pnOp is set to the number of entries in the returned
59192 ** array. Also, *pnMaxArg is set to the larger of its current value and
59193 ** the number of entries in the Vdbe.apArg[] array required to execute the
59194 ** returned program.
59195 */
59196 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
59197   VdbeOp *aOp = p->aOp;
59198   assert( aOp && !p->db->mallocFailed );
59199 
59200   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
59201   assert( p->btreeMask==0 );
59202 
59203   resolveP2Values(p, pnMaxArg);
59204   *pnOp = p->nOp;
59205   p->aOp = 0;
59206   return aOp;
59207 }
59208 
59209 /*
59210 ** Add a whole list of operations to the operation stack.  Return the
59211 ** address of the first operation added.
59212 */
59213 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
59214   int addr;
59215   assert( p->magic==VDBE_MAGIC_INIT );
59216   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
59217     return 0;
59218   }
59219   addr = p->nOp;
59220   if( ALWAYS(nOp>0) ){
59221     int i;
59222     VdbeOpList const *pIn = aOp;
59223     for(i=0; i<nOp; i++, pIn++){
59224       int p2 = pIn->p2;
59225       VdbeOp *pOut = &p->aOp[i+addr];
59226       pOut->opcode = pIn->opcode;
59227       pOut->p1 = pIn->p1;
59228       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
59229         pOut->p2 = addr + ADDR(p2);
59230       }else{
59231         pOut->p2 = p2;
59232       }
59233       pOut->p3 = pIn->p3;
59234       pOut->p4type = P4_NOTUSED;
59235       pOut->p4.p = 0;
59236       pOut->p5 = 0;
59237 #ifdef SQLITE_DEBUG
59238       pOut->zComment = 0;
59239       if( p->db->flags & SQLITE_VdbeAddopTrace ){
59240         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
59241       }
59242 #endif
59243     }
59244     p->nOp += nOp;
59245   }
59246   return addr;
59247 }
59248 
59249 /*
59250 ** Change the value of the P1 operand for a specific instruction.
59251 ** This routine is useful when a large program is loaded from a
59252 ** static array using sqlite3VdbeAddOpList but we want to make a
59253 ** few minor changes to the program.
59254 */
59255 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
59256   assert( p!=0 );
59257   if( ((u32)p->nOp)>addr ){
59258     p->aOp[addr].p1 = val;
59259   }
59260 }
59261 
59262 /*
59263 ** Change the value of the P2 operand for a specific instruction.
59264 ** This routine is useful for setting a jump destination.
59265 */
59266 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
59267   assert( p!=0 );
59268   if( ((u32)p->nOp)>addr ){
59269     p->aOp[addr].p2 = val;
59270   }
59271 }
59272 
59273 /*
59274 ** Change the value of the P3 operand for a specific instruction.
59275 */
59276 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
59277   assert( p!=0 );
59278   if( ((u32)p->nOp)>addr ){
59279     p->aOp[addr].p3 = val;
59280   }
59281 }
59282 
59283 /*
59284 ** Change the value of the P5 operand for the most recently
59285 ** added operation.
59286 */
59287 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
59288   assert( p!=0 );
59289   if( p->aOp ){
59290     assert( p->nOp>0 );
59291     p->aOp[p->nOp-1].p5 = val;
59292   }
59293 }
59294 
59295 /*
59296 ** Change the P2 operand of instruction addr so that it points to
59297 ** the address of the next instruction to be coded.
59298 */
59299 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
59300   assert( addr>=0 || p->db->mallocFailed );
59301   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
59302 }
59303 
59304 
59305 /*
59306 ** If the input FuncDef structure is ephemeral, then free it.  If
59307 ** the FuncDef is not ephermal, then do nothing.
59308 */
59309 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
59310   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
59311     sqlite3DbFree(db, pDef);
59312   }
59313 }
59314 
59315 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
59316 
59317 /*
59318 ** Delete a P4 value if necessary.
59319 */
59320 static void freeP4(sqlite3 *db, int p4type, void *p4){
59321   if( p4 ){
59322     assert( db );
59323     switch( p4type ){
59324       case P4_REAL:
59325       case P4_INT64:
59326       case P4_DYNAMIC:
59327       case P4_KEYINFO:
59328       case P4_INTARRAY:
59329       case P4_KEYINFO_HANDOFF: {
59330         sqlite3DbFree(db, p4);
59331         break;
59332       }
59333       case P4_MPRINTF: {
59334         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
59335         break;
59336       }
59337       case P4_VDBEFUNC: {
59338         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
59339         freeEphemeralFunction(db, pVdbeFunc->pFunc);
59340         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
59341         sqlite3DbFree(db, pVdbeFunc);
59342         break;
59343       }
59344       case P4_FUNCDEF: {
59345         freeEphemeralFunction(db, (FuncDef*)p4);
59346         break;
59347       }
59348       case P4_MEM: {
59349         if( db->pnBytesFreed==0 ){
59350           sqlite3ValueFree((sqlite3_value*)p4);
59351         }else{
59352           Mem *p = (Mem*)p4;
59353           sqlite3DbFree(db, p->zMalloc);
59354           sqlite3DbFree(db, p);
59355         }
59356         break;
59357       }
59358       case P4_VTAB : {
59359         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
59360         break;
59361       }
59362     }
59363   }
59364 }
59365 
59366 /*
59367 ** Free the space allocated for aOp and any p4 values allocated for the
59368 ** opcodes contained within. If aOp is not NULL it is assumed to contain
59369 ** nOp entries.
59370 */
59371 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
59372   if( aOp ){
59373     Op *pOp;
59374     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
59375       freeP4(db, pOp->p4type, pOp->p4.p);
59376 #ifdef SQLITE_DEBUG
59377       sqlite3DbFree(db, pOp->zComment);
59378 #endif
59379     }
59380   }
59381   sqlite3DbFree(db, aOp);
59382 }
59383 
59384 /*
59385 ** Link the SubProgram object passed as the second argument into the linked
59386 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
59387 ** objects when the VM is no longer required.
59388 */
59389 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
59390   p->pNext = pVdbe->pProgram;
59391   pVdbe->pProgram = p;
59392 }
59393 
59394 /*
59395 ** Change the opcode at addr into OP_Noop
59396 */
59397 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
59398   if( p->aOp ){
59399     VdbeOp *pOp = &p->aOp[addr];
59400     sqlite3 *db = p->db;
59401     freeP4(db, pOp->p4type, pOp->p4.p);
59402     memset(pOp, 0, sizeof(pOp[0]));
59403     pOp->opcode = OP_Noop;
59404   }
59405 }
59406 
59407 /*
59408 ** Change the value of the P4 operand for a specific instruction.
59409 ** This routine is useful when a large program is loaded from a
59410 ** static array using sqlite3VdbeAddOpList but we want to make a
59411 ** few minor changes to the program.
59412 **
59413 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
59414 ** the string is made into memory obtained from sqlite3_malloc().
59415 ** A value of n==0 means copy bytes of zP4 up to and including the
59416 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
59417 **
59418 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
59419 ** A copy is made of the KeyInfo structure into memory obtained from
59420 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
59421 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
59422 ** stored in memory that the caller has obtained from sqlite3_malloc. The
59423 ** caller should not free the allocation, it will be freed when the Vdbe is
59424 ** finalized.
59425 **
59426 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
59427 ** to a string or structure that is guaranteed to exist for the lifetime of
59428 ** the Vdbe. In these cases we can just copy the pointer.
59429 **
59430 ** If addr<0 then change P4 on the most recently inserted instruction.
59431 */
59432 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
59433   Op *pOp;
59434   sqlite3 *db;
59435   assert( p!=0 );
59436   db = p->db;
59437   assert( p->magic==VDBE_MAGIC_INIT );
59438   if( p->aOp==0 || db->mallocFailed ){
59439     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
59440       freeP4(db, n, (void*)*(char**)&zP4);
59441     }
59442     return;
59443   }
59444   assert( p->nOp>0 );
59445   assert( addr<p->nOp );
59446   if( addr<0 ){
59447     addr = p->nOp - 1;
59448   }
59449   pOp = &p->aOp[addr];
59450   assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
59451   freeP4(db, pOp->p4type, pOp->p4.p);
59452   pOp->p4.p = 0;
59453   if( n==P4_INT32 ){
59454     /* Note: this cast is safe, because the origin data point was an int
59455     ** that was cast to a (const char *). */
59456     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
59457     pOp->p4type = P4_INT32;
59458   }else if( zP4==0 ){
59459     pOp->p4.p = 0;
59460     pOp->p4type = P4_NOTUSED;
59461   }else if( n==P4_KEYINFO ){
59462     KeyInfo *pKeyInfo;
59463     int nField, nByte;
59464 
59465     nField = ((KeyInfo*)zP4)->nField;
59466     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
59467     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
59468     pOp->p4.pKeyInfo = pKeyInfo;
59469     if( pKeyInfo ){
59470       u8 *aSortOrder;
59471       memcpy((char*)pKeyInfo, zP4, nByte - nField);
59472       aSortOrder = pKeyInfo->aSortOrder;
59473       assert( aSortOrder!=0 );
59474       pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
59475       memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
59476       pOp->p4type = P4_KEYINFO;
59477     }else{
59478       p->db->mallocFailed = 1;
59479       pOp->p4type = P4_NOTUSED;
59480     }
59481   }else if( n==P4_KEYINFO_HANDOFF ){
59482     pOp->p4.p = (void*)zP4;
59483     pOp->p4type = P4_KEYINFO;
59484   }else if( n==P4_VTAB ){
59485     pOp->p4.p = (void*)zP4;
59486     pOp->p4type = P4_VTAB;
59487     sqlite3VtabLock((VTable *)zP4);
59488     assert( ((VTable *)zP4)->db==p->db );
59489   }else if( n<0 ){
59490     pOp->p4.p = (void*)zP4;
59491     pOp->p4type = (signed char)n;
59492   }else{
59493     if( n==0 ) n = sqlite3Strlen30(zP4);
59494     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
59495     pOp->p4type = P4_DYNAMIC;
59496   }
59497 }
59498 
59499 #ifndef NDEBUG
59500 /*
59501 ** Change the comment on the most recently coded instruction.  Or
59502 ** insert a No-op and add the comment to that new instruction.  This
59503 ** makes the code easier to read during debugging.  None of this happens
59504 ** in a production build.
59505 */
59506 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
59507   assert( p->nOp>0 || p->aOp==0 );
59508   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
59509   if( p->nOp ){
59510     assert( p->aOp );
59511     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
59512     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
59513   }
59514 }
59515 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
59516   va_list ap;
59517   if( p ){
59518     va_start(ap, zFormat);
59519     vdbeVComment(p, zFormat, ap);
59520     va_end(ap);
59521   }
59522 }
59523 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
59524   va_list ap;
59525   if( p ){
59526     sqlite3VdbeAddOp0(p, OP_Noop);
59527     va_start(ap, zFormat);
59528     vdbeVComment(p, zFormat, ap);
59529     va_end(ap);
59530   }
59531 }
59532 #endif  /* NDEBUG */
59533 
59534 /*
59535 ** Return the opcode for a given address.  If the address is -1, then
59536 ** return the most recently inserted opcode.
59537 **
59538 ** If a memory allocation error has occurred prior to the calling of this
59539 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
59540 ** is readable but not writable, though it is cast to a writable value.
59541 ** The return of a dummy opcode allows the call to continue functioning
59542 ** after a OOM fault without having to check to see if the return from
59543 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
59544 ** dummy will never be written to.  This is verified by code inspection and
59545 ** by running with Valgrind.
59546 **
59547 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
59548 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
59549 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
59550 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
59551 ** having to double-check to make sure that the result is non-negative. But
59552 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
59553 ** check the value of p->nOp-1 before continuing.
59554 */
59555 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
59556   /* C89 specifies that the constant "dummy" will be initialized to all
59557   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
59558   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
59559   assert( p->magic==VDBE_MAGIC_INIT );
59560   if( addr<0 ){
59561 #ifdef SQLITE_OMIT_TRACE
59562     if( p->nOp==0 ) return (VdbeOp*)&dummy;
59563 #endif
59564     addr = p->nOp - 1;
59565   }
59566   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
59567   if( p->db->mallocFailed ){
59568     return (VdbeOp*)&dummy;
59569   }else{
59570     return &p->aOp[addr];
59571   }
59572 }
59573 
59574 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
59575      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59576 /*
59577 ** Compute a string that describes the P4 parameter for an opcode.
59578 ** Use zTemp for any required temporary buffer space.
59579 */
59580 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
59581   char *zP4 = zTemp;
59582   assert( nTemp>=20 );
59583   switch( pOp->p4type ){
59584     case P4_KEYINFO_STATIC:
59585     case P4_KEYINFO: {
59586       int i, j;
59587       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
59588       assert( pKeyInfo->aSortOrder!=0 );
59589       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
59590       i = sqlite3Strlen30(zTemp);
59591       for(j=0; j<pKeyInfo->nField; j++){
59592         CollSeq *pColl = pKeyInfo->aColl[j];
59593         const char *zColl = pColl ? pColl->zName : "nil";
59594         int n = sqlite3Strlen30(zColl);
59595         if( i+n>nTemp-6 ){
59596           memcpy(&zTemp[i],",...",4);
59597           break;
59598         }
59599         zTemp[i++] = ',';
59600         if( pKeyInfo->aSortOrder[j] ){
59601           zTemp[i++] = '-';
59602         }
59603         memcpy(&zTemp[i], zColl, n+1);
59604         i += n;
59605       }
59606       zTemp[i++] = ')';
59607       zTemp[i] = 0;
59608       assert( i<nTemp );
59609       break;
59610     }
59611     case P4_COLLSEQ: {
59612       CollSeq *pColl = pOp->p4.pColl;
59613       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
59614       break;
59615     }
59616     case P4_FUNCDEF: {
59617       FuncDef *pDef = pOp->p4.pFunc;
59618       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
59619       break;
59620     }
59621     case P4_INT64: {
59622       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
59623       break;
59624     }
59625     case P4_INT32: {
59626       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
59627       break;
59628     }
59629     case P4_REAL: {
59630       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
59631       break;
59632     }
59633     case P4_MEM: {
59634       Mem *pMem = pOp->p4.pMem;
59635       if( pMem->flags & MEM_Str ){
59636         zP4 = pMem->z;
59637       }else if( pMem->flags & MEM_Int ){
59638         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
59639       }else if( pMem->flags & MEM_Real ){
59640         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
59641       }else if( pMem->flags & MEM_Null ){
59642         sqlite3_snprintf(nTemp, zTemp, "NULL");
59643       }else{
59644         assert( pMem->flags & MEM_Blob );
59645         zP4 = "(blob)";
59646       }
59647       break;
59648     }
59649 #ifndef SQLITE_OMIT_VIRTUALTABLE
59650     case P4_VTAB: {
59651       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
59652       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
59653       break;
59654     }
59655 #endif
59656     case P4_INTARRAY: {
59657       sqlite3_snprintf(nTemp, zTemp, "intarray");
59658       break;
59659     }
59660     case P4_SUBPROGRAM: {
59661       sqlite3_snprintf(nTemp, zTemp, "program");
59662       break;
59663     }
59664     case P4_ADVANCE: {
59665       zTemp[0] = 0;
59666       break;
59667     }
59668     default: {
59669       zP4 = pOp->p4.z;
59670       if( zP4==0 ){
59671         zP4 = zTemp;
59672         zTemp[0] = 0;
59673       }
59674     }
59675   }
59676   assert( zP4!=0 );
59677   return zP4;
59678 }
59679 #endif
59680 
59681 /*
59682 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
59683 **
59684 ** The prepared statements need to know in advance the complete set of
59685 ** attached databases that will be use.  A mask of these databases
59686 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
59687 ** p->btreeMask of databases that will require a lock.
59688 */
59689 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
59690   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
59691   assert( i<(int)sizeof(p->btreeMask)*8 );
59692   p->btreeMask |= ((yDbMask)1)<<i;
59693   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
59694     p->lockMask |= ((yDbMask)1)<<i;
59695   }
59696 }
59697 
59698 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59699 /*
59700 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
59701 ** this routine obtains the mutex associated with each BtShared structure
59702 ** that may be accessed by the VM passed as an argument. In doing so it also
59703 ** sets the BtShared.db member of each of the BtShared structures, ensuring
59704 ** that the correct busy-handler callback is invoked if required.
59705 **
59706 ** If SQLite is not threadsafe but does support shared-cache mode, then
59707 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
59708 ** of all of BtShared structures accessible via the database handle
59709 ** associated with the VM.
59710 **
59711 ** If SQLite is not threadsafe and does not support shared-cache mode, this
59712 ** function is a no-op.
59713 **
59714 ** The p->btreeMask field is a bitmask of all btrees that the prepared
59715 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
59716 ** corresponding to btrees that use shared cache.  Then the runtime of
59717 ** this routine is N*N.  But as N is rarely more than 1, this should not
59718 ** be a problem.
59719 */
59720 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
59721   int i;
59722   yDbMask mask;
59723   sqlite3 *db;
59724   Db *aDb;
59725   int nDb;
59726   if( p->lockMask==0 ) return;  /* The common case */
59727   db = p->db;
59728   aDb = db->aDb;
59729   nDb = db->nDb;
59730   for(i=0, mask=1; i<nDb; i++, mask += mask){
59731     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59732       sqlite3BtreeEnter(aDb[i].pBt);
59733     }
59734   }
59735 }
59736 #endif
59737 
59738 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59739 /*
59740 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
59741 */
59742 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
59743   int i;
59744   yDbMask mask;
59745   sqlite3 *db;
59746   Db *aDb;
59747   int nDb;
59748   if( p->lockMask==0 ) return;  /* The common case */
59749   db = p->db;
59750   aDb = db->aDb;
59751   nDb = db->nDb;
59752   for(i=0, mask=1; i<nDb; i++, mask += mask){
59753     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59754       sqlite3BtreeLeave(aDb[i].pBt);
59755     }
59756   }
59757 }
59758 #endif
59759 
59760 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59761 /*
59762 ** Print a single opcode.  This routine is used for debugging only.
59763 */
59764 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
59765   char *zP4;
59766   char zPtr[50];
59767   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
59768   if( pOut==0 ) pOut = stdout;
59769   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
59770   fprintf(pOut, zFormat1, pc,
59771       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
59772 #ifdef SQLITE_DEBUG
59773       pOp->zComment ? pOp->zComment : ""
59774 #else
59775       ""
59776 #endif
59777   );
59778   fflush(pOut);
59779 }
59780 #endif
59781 
59782 /*
59783 ** Release an array of N Mem elements
59784 */
59785 static void releaseMemArray(Mem *p, int N){
59786   if( p && N ){
59787     Mem *pEnd;
59788     sqlite3 *db = p->db;
59789     u8 malloc_failed = db->mallocFailed;
59790     if( db->pnBytesFreed ){
59791       for(pEnd=&p[N]; p<pEnd; p++){
59792         sqlite3DbFree(db, p->zMalloc);
59793       }
59794       return;
59795     }
59796     for(pEnd=&p[N]; p<pEnd; p++){
59797       assert( (&p[1])==pEnd || p[0].db==p[1].db );
59798 
59799       /* This block is really an inlined version of sqlite3VdbeMemRelease()
59800       ** that takes advantage of the fact that the memory cell value is
59801       ** being set to NULL after releasing any dynamic resources.
59802       **
59803       ** The justification for duplicating code is that according to
59804       ** callgrind, this causes a certain test case to hit the CPU 4.7
59805       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
59806       ** sqlite3MemRelease() were called from here. With -O2, this jumps
59807       ** to 6.6 percent. The test case is inserting 1000 rows into a table
59808       ** with no indexes using a single prepared INSERT statement, bind()
59809       ** and reset(). Inserts are grouped into a transaction.
59810       */
59811       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
59812         sqlite3VdbeMemRelease(p);
59813       }else if( p->zMalloc ){
59814         sqlite3DbFree(db, p->zMalloc);
59815         p->zMalloc = 0;
59816       }
59817 
59818       p->flags = MEM_Invalid;
59819     }
59820     db->mallocFailed = malloc_failed;
59821   }
59822 }
59823 
59824 /*
59825 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
59826 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
59827 */
59828 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
59829   int i;
59830   Mem *aMem = VdbeFrameMem(p);
59831   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
59832   for(i=0; i<p->nChildCsr; i++){
59833     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
59834   }
59835   releaseMemArray(aMem, p->nChildMem);
59836   sqlite3DbFree(p->v->db, p);
59837 }
59838 
59839 #ifndef SQLITE_OMIT_EXPLAIN
59840 /*
59841 ** Give a listing of the program in the virtual machine.
59842 **
59843 ** The interface is the same as sqlite3VdbeExec().  But instead of
59844 ** running the code, it invokes the callback once for each instruction.
59845 ** This feature is used to implement "EXPLAIN".
59846 **
59847 ** When p->explain==1, each instruction is listed.  When
59848 ** p->explain==2, only OP_Explain instructions are listed and these
59849 ** are shown in a different format.  p->explain==2 is used to implement
59850 ** EXPLAIN QUERY PLAN.
59851 **
59852 ** When p->explain==1, first the main program is listed, then each of
59853 ** the trigger subprograms are listed one by one.
59854 */
59855 SQLITE_PRIVATE int sqlite3VdbeList(
59856   Vdbe *p                   /* The VDBE */
59857 ){
59858   int nRow;                            /* Stop when row count reaches this */
59859   int nSub = 0;                        /* Number of sub-vdbes seen so far */
59860   SubProgram **apSub = 0;              /* Array of sub-vdbes */
59861   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
59862   sqlite3 *db = p->db;                 /* The database connection */
59863   int i;                               /* Loop counter */
59864   int rc = SQLITE_OK;                  /* Return code */
59865   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
59866 
59867   assert( p->explain );
59868   assert( p->magic==VDBE_MAGIC_RUN );
59869   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
59870 
59871   /* Even though this opcode does not use dynamic strings for
59872   ** the result, result columns may become dynamic if the user calls
59873   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
59874   */
59875   releaseMemArray(pMem, 8);
59876   p->pResultSet = 0;
59877 
59878   if( p->rc==SQLITE_NOMEM ){
59879     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59880     ** sqlite3_column_text16() failed.  */
59881     db->mallocFailed = 1;
59882     return SQLITE_ERROR;
59883   }
59884 
59885   /* When the number of output rows reaches nRow, that means the
59886   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
59887   ** nRow is the sum of the number of rows in the main program, plus
59888   ** the sum of the number of rows in all trigger subprograms encountered
59889   ** so far.  The nRow value will increase as new trigger subprograms are
59890   ** encountered, but p->pc will eventually catch up to nRow.
59891   */
59892   nRow = p->nOp;
59893   if( p->explain==1 ){
59894     /* The first 8 memory cells are used for the result set.  So we will
59895     ** commandeer the 9th cell to use as storage for an array of pointers
59896     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
59897     ** cells.  */
59898     assert( p->nMem>9 );
59899     pSub = &p->aMem[9];
59900     if( pSub->flags&MEM_Blob ){
59901       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
59902       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
59903       nSub = pSub->n/sizeof(Vdbe*);
59904       apSub = (SubProgram **)pSub->z;
59905     }
59906     for(i=0; i<nSub; i++){
59907       nRow += apSub[i]->nOp;
59908     }
59909   }
59910 
59911   do{
59912     i = p->pc++;
59913   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
59914   if( i>=nRow ){
59915     p->rc = SQLITE_OK;
59916     rc = SQLITE_DONE;
59917   }else if( db->u1.isInterrupted ){
59918     p->rc = SQLITE_INTERRUPT;
59919     rc = SQLITE_ERROR;
59920     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
59921   }else{
59922     char *z;
59923     Op *pOp;
59924     if( i<p->nOp ){
59925       /* The output line number is small enough that we are still in the
59926       ** main program. */
59927       pOp = &p->aOp[i];
59928     }else{
59929       /* We are currently listing subprograms.  Figure out which one and
59930       ** pick up the appropriate opcode. */
59931       int j;
59932       i -= p->nOp;
59933       for(j=0; i>=apSub[j]->nOp; j++){
59934         i -= apSub[j]->nOp;
59935       }
59936       pOp = &apSub[j]->aOp[i];
59937     }
59938     if( p->explain==1 ){
59939       pMem->flags = MEM_Int;
59940       pMem->type = SQLITE_INTEGER;
59941       pMem->u.i = i;                                /* Program counter */
59942       pMem++;
59943 
59944       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
59945       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
59946       assert( pMem->z!=0 );
59947       pMem->n = sqlite3Strlen30(pMem->z);
59948       pMem->type = SQLITE_TEXT;
59949       pMem->enc = SQLITE_UTF8;
59950       pMem++;
59951 
59952       /* When an OP_Program opcode is encounter (the only opcode that has
59953       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
59954       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
59955       ** has not already been seen.
59956       */
59957       if( pOp->p4type==P4_SUBPROGRAM ){
59958         int nByte = (nSub+1)*sizeof(SubProgram*);
59959         int j;
59960         for(j=0; j<nSub; j++){
59961           if( apSub[j]==pOp->p4.pProgram ) break;
59962         }
59963         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
59964           apSub = (SubProgram **)pSub->z;
59965           apSub[nSub++] = pOp->p4.pProgram;
59966           pSub->flags |= MEM_Blob;
59967           pSub->n = nSub*sizeof(SubProgram*);
59968         }
59969       }
59970     }
59971 
59972     pMem->flags = MEM_Int;
59973     pMem->u.i = pOp->p1;                          /* P1 */
59974     pMem->type = SQLITE_INTEGER;
59975     pMem++;
59976 
59977     pMem->flags = MEM_Int;
59978     pMem->u.i = pOp->p2;                          /* P2 */
59979     pMem->type = SQLITE_INTEGER;
59980     pMem++;
59981 
59982     pMem->flags = MEM_Int;
59983     pMem->u.i = pOp->p3;                          /* P3 */
59984     pMem->type = SQLITE_INTEGER;
59985     pMem++;
59986 
59987     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
59988       assert( p->db->mallocFailed );
59989       return SQLITE_ERROR;
59990     }
59991     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59992     z = displayP4(pOp, pMem->z, 32);
59993     if( z!=pMem->z ){
59994       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
59995     }else{
59996       assert( pMem->z!=0 );
59997       pMem->n = sqlite3Strlen30(pMem->z);
59998       pMem->enc = SQLITE_UTF8;
59999     }
60000     pMem->type = SQLITE_TEXT;
60001     pMem++;
60002 
60003     if( p->explain==1 ){
60004       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
60005         assert( p->db->mallocFailed );
60006         return SQLITE_ERROR;
60007       }
60008       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60009       pMem->n = 2;
60010       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
60011       pMem->type = SQLITE_TEXT;
60012       pMem->enc = SQLITE_UTF8;
60013       pMem++;
60014 
60015 #ifdef SQLITE_DEBUG
60016       if( pOp->zComment ){
60017         pMem->flags = MEM_Str|MEM_Term;
60018         pMem->z = pOp->zComment;
60019         pMem->n = sqlite3Strlen30(pMem->z);
60020         pMem->enc = SQLITE_UTF8;
60021         pMem->type = SQLITE_TEXT;
60022       }else
60023 #endif
60024       {
60025         pMem->flags = MEM_Null;                       /* Comment */
60026         pMem->type = SQLITE_NULL;
60027       }
60028     }
60029 
60030     p->nResColumn = 8 - 4*(p->explain-1);
60031     p->pResultSet = &p->aMem[1];
60032     p->rc = SQLITE_OK;
60033     rc = SQLITE_ROW;
60034   }
60035   return rc;
60036 }
60037 #endif /* SQLITE_OMIT_EXPLAIN */
60038 
60039 #ifdef SQLITE_DEBUG
60040 /*
60041 ** Print the SQL that was used to generate a VDBE program.
60042 */
60043 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
60044   int nOp = p->nOp;
60045   VdbeOp *pOp;
60046   if( nOp<1 ) return;
60047   pOp = &p->aOp[0];
60048   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60049     const char *z = pOp->p4.z;
60050     while( sqlite3Isspace(*z) ) z++;
60051     printf("SQL: [%s]\n", z);
60052   }
60053 }
60054 #endif
60055 
60056 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
60057 /*
60058 ** Print an IOTRACE message showing SQL content.
60059 */
60060 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
60061   int nOp = p->nOp;
60062   VdbeOp *pOp;
60063   if( sqlite3IoTrace==0 ) return;
60064   if( nOp<1 ) return;
60065   pOp = &p->aOp[0];
60066   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60067     int i, j;
60068     char z[1000];
60069     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
60070     for(i=0; sqlite3Isspace(z[i]); i++){}
60071     for(j=0; z[i]; i++){
60072       if( sqlite3Isspace(z[i]) ){
60073         if( z[i-1]!=' ' ){
60074           z[j++] = ' ';
60075         }
60076       }else{
60077         z[j++] = z[i];
60078       }
60079     }
60080     z[j] = 0;
60081     sqlite3IoTrace("SQL %s\n", z);
60082   }
60083 }
60084 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
60085 
60086 /*
60087 ** Allocate space from a fixed size buffer and return a pointer to
60088 ** that space.  If insufficient space is available, return NULL.
60089 **
60090 ** The pBuf parameter is the initial value of a pointer which will
60091 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
60092 ** NULL, it means that memory space has already been allocated and that
60093 ** this routine should not allocate any new memory.  When pBuf is not
60094 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
60095 ** is NULL.
60096 **
60097 ** nByte is the number of bytes of space needed.
60098 **
60099 ** *ppFrom points to available space and pEnd points to the end of the
60100 ** available space.  When space is allocated, *ppFrom is advanced past
60101 ** the end of the allocated space.
60102 **
60103 ** *pnByte is a counter of the number of bytes of space that have failed
60104 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
60105 ** request, then increment *pnByte by the amount of the request.
60106 */
60107 static void *allocSpace(
60108   void *pBuf,          /* Where return pointer will be stored */
60109   int nByte,           /* Number of bytes to allocate */
60110   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
60111   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
60112   int *pnByte          /* If allocation cannot be made, increment *pnByte */
60113 ){
60114   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
60115   if( pBuf ) return pBuf;
60116   nByte = ROUND8(nByte);
60117   if( &(*ppFrom)[nByte] <= pEnd ){
60118     pBuf = (void*)*ppFrom;
60119     *ppFrom += nByte;
60120   }else{
60121     *pnByte += nByte;
60122   }
60123   return pBuf;
60124 }
60125 
60126 /*
60127 ** Rewind the VDBE back to the beginning in preparation for
60128 ** running it.
60129 */
60130 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
60131 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
60132   int i;
60133 #endif
60134   assert( p!=0 );
60135   assert( p->magic==VDBE_MAGIC_INIT );
60136 
60137   /* There should be at least one opcode.
60138   */
60139   assert( p->nOp>0 );
60140 
60141   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
60142   p->magic = VDBE_MAGIC_RUN;
60143 
60144 #ifdef SQLITE_DEBUG
60145   for(i=1; i<p->nMem; i++){
60146     assert( p->aMem[i].db==p->db );
60147   }
60148 #endif
60149   p->pc = -1;
60150   p->rc = SQLITE_OK;
60151   p->errorAction = OE_Abort;
60152   p->magic = VDBE_MAGIC_RUN;
60153   p->nChange = 0;
60154   p->cacheCtr = 1;
60155   p->minWriteFileFormat = 255;
60156   p->iStatement = 0;
60157   p->nFkConstraint = 0;
60158 #ifdef VDBE_PROFILE
60159   for(i=0; i<p->nOp; i++){
60160     p->aOp[i].cnt = 0;
60161     p->aOp[i].cycles = 0;
60162   }
60163 #endif
60164 }
60165 
60166 /*
60167 ** Prepare a virtual machine for execution for the first time after
60168 ** creating the virtual machine.  This involves things such
60169 ** as allocating stack space and initializing the program counter.
60170 ** After the VDBE has be prepped, it can be executed by one or more
60171 ** calls to sqlite3VdbeExec().
60172 **
60173 ** This function may be called exact once on a each virtual machine.
60174 ** After this routine is called the VM has been "packaged" and is ready
60175 ** to run.  After this routine is called, futher calls to
60176 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
60177 ** the Vdbe from the Parse object that helped generate it so that the
60178 ** the Vdbe becomes an independent entity and the Parse object can be
60179 ** destroyed.
60180 **
60181 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
60182 ** to its initial state after it has been run.
60183 */
60184 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
60185   Vdbe *p,                       /* The VDBE */
60186   Parse *pParse                  /* Parsing context */
60187 ){
60188   sqlite3 *db;                   /* The database connection */
60189   int nVar;                      /* Number of parameters */
60190   int nMem;                      /* Number of VM memory registers */
60191   int nCursor;                   /* Number of cursors required */
60192   int nArg;                      /* Number of arguments in subprograms */
60193   int nOnce;                     /* Number of OP_Once instructions */
60194   int n;                         /* Loop counter */
60195   u8 *zCsr;                      /* Memory available for allocation */
60196   u8 *zEnd;                      /* First byte past allocated memory */
60197   int nByte;                     /* How much extra memory is needed */
60198 
60199   assert( p!=0 );
60200   assert( p->nOp>0 );
60201   assert( pParse!=0 );
60202   assert( p->magic==VDBE_MAGIC_INIT );
60203   db = p->db;
60204   assert( db->mallocFailed==0 );
60205   nVar = pParse->nVar;
60206   nMem = pParse->nMem;
60207   nCursor = pParse->nTab;
60208   nArg = pParse->nMaxArg;
60209   nOnce = pParse->nOnce;
60210   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
60211 
60212   /* For each cursor required, also allocate a memory cell. Memory
60213   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
60214   ** the vdbe program. Instead they are used to allocate space for
60215   ** VdbeCursor/BtCursor structures. The blob of memory associated with
60216   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
60217   ** stores the blob of memory associated with cursor 1, etc.
60218   **
60219   ** See also: allocateCursor().
60220   */
60221   nMem += nCursor;
60222 
60223   /* Allocate space for memory registers, SQL variables, VDBE cursors and
60224   ** an array to marshal SQL function arguments in.
60225   */
60226   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
60227   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
60228 
60229   resolveP2Values(p, &nArg);
60230   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
60231   if( pParse->explain && nMem<10 ){
60232     nMem = 10;
60233   }
60234   memset(zCsr, 0, zEnd-zCsr);
60235   zCsr += (zCsr - (u8*)0)&7;
60236   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
60237   p->expired = 0;
60238 
60239   /* Memory for registers, parameters, cursor, etc, is allocated in two
60240   ** passes.  On the first pass, we try to reuse unused space at the
60241   ** end of the opcode array.  If we are unable to satisfy all memory
60242   ** requirements by reusing the opcode array tail, then the second
60243   ** pass will fill in the rest using a fresh allocation.
60244   **
60245   ** This two-pass approach that reuses as much memory as possible from
60246   ** the leftover space at the end of the opcode array can significantly
60247   ** reduce the amount of memory held by a prepared statement.
60248   */
60249   do {
60250     nByte = 0;
60251     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
60252     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
60253     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
60254     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
60255     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
60256                           &zCsr, zEnd, &nByte);
60257     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
60258     if( nByte ){
60259       p->pFree = sqlite3DbMallocZero(db, nByte);
60260     }
60261     zCsr = p->pFree;
60262     zEnd = &zCsr[nByte];
60263   }while( nByte && !db->mallocFailed );
60264 
60265   p->nCursor = nCursor;
60266   p->nOnceFlag = nOnce;
60267   if( p->aVar ){
60268     p->nVar = (ynVar)nVar;
60269     for(n=0; n<nVar; n++){
60270       p->aVar[n].flags = MEM_Null;
60271       p->aVar[n].db = db;
60272     }
60273   }
60274   if( p->azVar ){
60275     p->nzVar = pParse->nzVar;
60276     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
60277     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
60278   }
60279   if( p->aMem ){
60280     p->aMem--;                      /* aMem[] goes from 1..nMem */
60281     p->nMem = nMem;                 /*       not from 0..nMem-1 */
60282     for(n=1; n<=nMem; n++){
60283       p->aMem[n].flags = MEM_Invalid;
60284       p->aMem[n].db = db;
60285     }
60286   }
60287   p->explain = pParse->explain;
60288   sqlite3VdbeRewind(p);
60289 }
60290 
60291 /*
60292 ** Close a VDBE cursor and release all the resources that cursor
60293 ** happens to hold.
60294 */
60295 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
60296   if( pCx==0 ){
60297     return;
60298   }
60299   sqlite3VdbeSorterClose(p->db, pCx);
60300   if( pCx->pBt ){
60301     sqlite3BtreeClose(pCx->pBt);
60302     /* The pCx->pCursor will be close automatically, if it exists, by
60303     ** the call above. */
60304   }else if( pCx->pCursor ){
60305     sqlite3BtreeCloseCursor(pCx->pCursor);
60306   }
60307 #ifndef SQLITE_OMIT_VIRTUALTABLE
60308   if( pCx->pVtabCursor ){
60309     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
60310     const sqlite3_module *pModule = pCx->pModule;
60311     p->inVtabMethod = 1;
60312     pModule->xClose(pVtabCursor);
60313     p->inVtabMethod = 0;
60314   }
60315 #endif
60316 }
60317 
60318 /*
60319 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
60320 ** is used, for example, when a trigger sub-program is halted to restore
60321 ** control to the main program.
60322 */
60323 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
60324   Vdbe *v = pFrame->v;
60325   v->aOnceFlag = pFrame->aOnceFlag;
60326   v->nOnceFlag = pFrame->nOnceFlag;
60327   v->aOp = pFrame->aOp;
60328   v->nOp = pFrame->nOp;
60329   v->aMem = pFrame->aMem;
60330   v->nMem = pFrame->nMem;
60331   v->apCsr = pFrame->apCsr;
60332   v->nCursor = pFrame->nCursor;
60333   v->db->lastRowid = pFrame->lastRowid;
60334   v->nChange = pFrame->nChange;
60335   return pFrame->pc;
60336 }
60337 
60338 /*
60339 ** Close all cursors.
60340 **
60341 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
60342 ** cell array. This is necessary as the memory cell array may contain
60343 ** pointers to VdbeFrame objects, which may in turn contain pointers to
60344 ** open cursors.
60345 */
60346 static void closeAllCursors(Vdbe *p){
60347   if( p->pFrame ){
60348     VdbeFrame *pFrame;
60349     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
60350     sqlite3VdbeFrameRestore(pFrame);
60351   }
60352   p->pFrame = 0;
60353   p->nFrame = 0;
60354 
60355   if( p->apCsr ){
60356     int i;
60357     for(i=0; i<p->nCursor; i++){
60358       VdbeCursor *pC = p->apCsr[i];
60359       if( pC ){
60360         sqlite3VdbeFreeCursor(p, pC);
60361         p->apCsr[i] = 0;
60362       }
60363     }
60364   }
60365   if( p->aMem ){
60366     releaseMemArray(&p->aMem[1], p->nMem);
60367   }
60368   while( p->pDelFrame ){
60369     VdbeFrame *pDel = p->pDelFrame;
60370     p->pDelFrame = pDel->pParent;
60371     sqlite3VdbeFrameDelete(pDel);
60372   }
60373 }
60374 
60375 /*
60376 ** Clean up the VM after execution.
60377 **
60378 ** This routine will automatically close any cursors, lists, and/or
60379 ** sorters that were left open.  It also deletes the values of
60380 ** variables in the aVar[] array.
60381 */
60382 static void Cleanup(Vdbe *p){
60383   sqlite3 *db = p->db;
60384 
60385 #ifdef SQLITE_DEBUG
60386   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
60387   ** Vdbe.aMem[] arrays have already been cleaned up.  */
60388   int i;
60389   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
60390   if( p->aMem ){
60391     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
60392   }
60393 #endif
60394 
60395   sqlite3DbFree(db, p->zErrMsg);
60396   p->zErrMsg = 0;
60397   p->pResultSet = 0;
60398 }
60399 
60400 /*
60401 ** Set the number of result columns that will be returned by this SQL
60402 ** statement. This is now set at compile time, rather than during
60403 ** execution of the vdbe program so that sqlite3_column_count() can
60404 ** be called on an SQL statement before sqlite3_step().
60405 */
60406 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
60407   Mem *pColName;
60408   int n;
60409   sqlite3 *db = p->db;
60410 
60411   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
60412   sqlite3DbFree(db, p->aColName);
60413   n = nResColumn*COLNAME_N;
60414   p->nResColumn = (u16)nResColumn;
60415   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
60416   if( p->aColName==0 ) return;
60417   while( n-- > 0 ){
60418     pColName->flags = MEM_Null;
60419     pColName->db = p->db;
60420     pColName++;
60421   }
60422 }
60423 
60424 /*
60425 ** Set the name of the idx'th column to be returned by the SQL statement.
60426 ** zName must be a pointer to a nul terminated string.
60427 **
60428 ** This call must be made after a call to sqlite3VdbeSetNumCols().
60429 **
60430 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
60431 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
60432 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
60433 */
60434 SQLITE_PRIVATE int sqlite3VdbeSetColName(
60435   Vdbe *p,                         /* Vdbe being configured */
60436   int idx,                         /* Index of column zName applies to */
60437   int var,                         /* One of the COLNAME_* constants */
60438   const char *zName,               /* Pointer to buffer containing name */
60439   void (*xDel)(void*)              /* Memory management strategy for zName */
60440 ){
60441   int rc;
60442   Mem *pColName;
60443   assert( idx<p->nResColumn );
60444   assert( var<COLNAME_N );
60445   if( p->db->mallocFailed ){
60446     assert( !zName || xDel!=SQLITE_DYNAMIC );
60447     return SQLITE_NOMEM;
60448   }
60449   assert( p->aColName!=0 );
60450   pColName = &(p->aColName[idx+var*p->nResColumn]);
60451   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
60452   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
60453   return rc;
60454 }
60455 
60456 /*
60457 ** A read or write transaction may or may not be active on database handle
60458 ** db. If a transaction is active, commit it. If there is a
60459 ** write-transaction spanning more than one database file, this routine
60460 ** takes care of the master journal trickery.
60461 */
60462 static int vdbeCommit(sqlite3 *db, Vdbe *p){
60463   int i;
60464   int nTrans = 0;  /* Number of databases with an active write-transaction */
60465   int rc = SQLITE_OK;
60466   int needXcommit = 0;
60467 
60468 #ifdef SQLITE_OMIT_VIRTUALTABLE
60469   /* With this option, sqlite3VtabSync() is defined to be simply
60470   ** SQLITE_OK so p is not used.
60471   */
60472   UNUSED_PARAMETER(p);
60473 #endif
60474 
60475   /* Before doing anything else, call the xSync() callback for any
60476   ** virtual module tables written in this transaction. This has to
60477   ** be done before determining whether a master journal file is
60478   ** required, as an xSync() callback may add an attached database
60479   ** to the transaction.
60480   */
60481   rc = sqlite3VtabSync(db, &p->zErrMsg);
60482 
60483   /* This loop determines (a) if the commit hook should be invoked and
60484   ** (b) how many database files have open write transactions, not
60485   ** including the temp database. (b) is important because if more than
60486   ** one database file has an open write transaction, a master journal
60487   ** file is required for an atomic commit.
60488   */
60489   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60490     Btree *pBt = db->aDb[i].pBt;
60491     if( sqlite3BtreeIsInTrans(pBt) ){
60492       needXcommit = 1;
60493       if( i!=1 ) nTrans++;
60494       sqlite3BtreeEnter(pBt);
60495       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
60496       sqlite3BtreeLeave(pBt);
60497     }
60498   }
60499   if( rc!=SQLITE_OK ){
60500     return rc;
60501   }
60502 
60503   /* If there are any write-transactions at all, invoke the commit hook */
60504   if( needXcommit && db->xCommitCallback ){
60505     rc = db->xCommitCallback(db->pCommitArg);
60506     if( rc ){
60507       return SQLITE_CONSTRAINT_COMMITHOOK;
60508     }
60509   }
60510 
60511   /* The simple case - no more than one database file (not counting the
60512   ** TEMP database) has a transaction active.   There is no need for the
60513   ** master-journal.
60514   **
60515   ** If the return value of sqlite3BtreeGetFilename() is a zero length
60516   ** string, it means the main database is :memory: or a temp file.  In
60517   ** that case we do not support atomic multi-file commits, so use the
60518   ** simple case then too.
60519   */
60520   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
60521    || nTrans<=1
60522   ){
60523     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60524       Btree *pBt = db->aDb[i].pBt;
60525       if( pBt ){
60526         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
60527       }
60528     }
60529 
60530     /* Do the commit only if all databases successfully complete phase 1.
60531     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
60532     ** IO error while deleting or truncating a journal file. It is unlikely,
60533     ** but could happen. In this case abandon processing and return the error.
60534     */
60535     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60536       Btree *pBt = db->aDb[i].pBt;
60537       if( pBt ){
60538         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
60539       }
60540     }
60541     if( rc==SQLITE_OK ){
60542       sqlite3VtabCommit(db);
60543     }
60544   }
60545 
60546   /* The complex case - There is a multi-file write-transaction active.
60547   ** This requires a master journal file to ensure the transaction is
60548   ** committed atomicly.
60549   */
60550 #ifndef SQLITE_OMIT_DISKIO
60551   else{
60552     sqlite3_vfs *pVfs = db->pVfs;
60553     int needSync = 0;
60554     char *zMaster = 0;   /* File-name for the master journal */
60555     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
60556     sqlite3_file *pMaster = 0;
60557     i64 offset = 0;
60558     int res;
60559     int retryCount = 0;
60560     int nMainFile;
60561 
60562     /* Select a master journal file name */
60563     nMainFile = sqlite3Strlen30(zMainFile);
60564     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
60565     if( zMaster==0 ) return SQLITE_NOMEM;
60566     do {
60567       u32 iRandom;
60568       if( retryCount ){
60569         if( retryCount>100 ){
60570           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
60571           sqlite3OsDelete(pVfs, zMaster, 0);
60572           break;
60573         }else if( retryCount==1 ){
60574           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
60575         }
60576       }
60577       retryCount++;
60578       sqlite3_randomness(sizeof(iRandom), &iRandom);
60579       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
60580                                (iRandom>>8)&0xffffff, iRandom&0xff);
60581       /* The antipenultimate character of the master journal name must
60582       ** be "9" to avoid name collisions when using 8+3 filenames. */
60583       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
60584       sqlite3FileSuffix3(zMainFile, zMaster);
60585       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
60586     }while( rc==SQLITE_OK && res );
60587     if( rc==SQLITE_OK ){
60588       /* Open the master journal. */
60589       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
60590           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
60591           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
60592       );
60593     }
60594     if( rc!=SQLITE_OK ){
60595       sqlite3DbFree(db, zMaster);
60596       return rc;
60597     }
60598 
60599     /* Write the name of each database file in the transaction into the new
60600     ** master journal file. If an error occurs at this point close
60601     ** and delete the master journal file. All the individual journal files
60602     ** still have 'null' as the master journal pointer, so they will roll
60603     ** back independently if a failure occurs.
60604     */
60605     for(i=0; i<db->nDb; i++){
60606       Btree *pBt = db->aDb[i].pBt;
60607       if( sqlite3BtreeIsInTrans(pBt) ){
60608         char const *zFile = sqlite3BtreeGetJournalname(pBt);
60609         if( zFile==0 ){
60610           continue;  /* Ignore TEMP and :memory: databases */
60611         }
60612         assert( zFile[0]!=0 );
60613         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
60614           needSync = 1;
60615         }
60616         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
60617         offset += sqlite3Strlen30(zFile)+1;
60618         if( rc!=SQLITE_OK ){
60619           sqlite3OsCloseFree(pMaster);
60620           sqlite3OsDelete(pVfs, zMaster, 0);
60621           sqlite3DbFree(db, zMaster);
60622           return rc;
60623         }
60624       }
60625     }
60626 
60627     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
60628     ** flag is set this is not required.
60629     */
60630     if( needSync
60631      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
60632      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
60633     ){
60634       sqlite3OsCloseFree(pMaster);
60635       sqlite3OsDelete(pVfs, zMaster, 0);
60636       sqlite3DbFree(db, zMaster);
60637       return rc;
60638     }
60639 
60640     /* Sync all the db files involved in the transaction. The same call
60641     ** sets the master journal pointer in each individual journal. If
60642     ** an error occurs here, do not delete the master journal file.
60643     **
60644     ** If the error occurs during the first call to
60645     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
60646     ** master journal file will be orphaned. But we cannot delete it,
60647     ** in case the master journal file name was written into the journal
60648     ** file before the failure occurred.
60649     */
60650     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60651       Btree *pBt = db->aDb[i].pBt;
60652       if( pBt ){
60653         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
60654       }
60655     }
60656     sqlite3OsCloseFree(pMaster);
60657     assert( rc!=SQLITE_BUSY );
60658     if( rc!=SQLITE_OK ){
60659       sqlite3DbFree(db, zMaster);
60660       return rc;
60661     }
60662 
60663     /* Delete the master journal file. This commits the transaction. After
60664     ** doing this the directory is synced again before any individual
60665     ** transaction files are deleted.
60666     */
60667     rc = sqlite3OsDelete(pVfs, zMaster, 1);
60668     sqlite3DbFree(db, zMaster);
60669     zMaster = 0;
60670     if( rc ){
60671       return rc;
60672     }
60673 
60674     /* All files and directories have already been synced, so the following
60675     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
60676     ** deleting or truncating journals. If something goes wrong while
60677     ** this is happening we don't really care. The integrity of the
60678     ** transaction is already guaranteed, but some stray 'cold' journals
60679     ** may be lying around. Returning an error code won't help matters.
60680     */
60681     disable_simulated_io_errors();
60682     sqlite3BeginBenignMalloc();
60683     for(i=0; i<db->nDb; i++){
60684       Btree *pBt = db->aDb[i].pBt;
60685       if( pBt ){
60686         sqlite3BtreeCommitPhaseTwo(pBt, 1);
60687       }
60688     }
60689     sqlite3EndBenignMalloc();
60690     enable_simulated_io_errors();
60691 
60692     sqlite3VtabCommit(db);
60693   }
60694 #endif
60695 
60696   return rc;
60697 }
60698 
60699 /*
60700 ** This routine checks that the sqlite3.activeVdbeCnt count variable
60701 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
60702 ** currently active. An assertion fails if the two counts do not match.
60703 ** This is an internal self-check only - it is not an essential processing
60704 ** step.
60705 **
60706 ** This is a no-op if NDEBUG is defined.
60707 */
60708 #ifndef NDEBUG
60709 static void checkActiveVdbeCnt(sqlite3 *db){
60710   Vdbe *p;
60711   int cnt = 0;
60712   int nWrite = 0;
60713   p = db->pVdbe;
60714   while( p ){
60715     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
60716       cnt++;
60717       if( p->readOnly==0 ) nWrite++;
60718     }
60719     p = p->pNext;
60720   }
60721   assert( cnt==db->activeVdbeCnt );
60722   assert( nWrite==db->writeVdbeCnt );
60723 }
60724 #else
60725 #define checkActiveVdbeCnt(x)
60726 #endif
60727 
60728 /*
60729 ** If the Vdbe passed as the first argument opened a statement-transaction,
60730 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
60731 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
60732 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
60733 ** statement transaction is commtted.
60734 **
60735 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
60736 ** Otherwise SQLITE_OK.
60737 */
60738 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
60739   sqlite3 *const db = p->db;
60740   int rc = SQLITE_OK;
60741 
60742   /* If p->iStatement is greater than zero, then this Vdbe opened a
60743   ** statement transaction that should be closed here. The only exception
60744   ** is that an IO error may have occurred, causing an emergency rollback.
60745   ** In this case (db->nStatement==0), and there is nothing to do.
60746   */
60747   if( db->nStatement && p->iStatement ){
60748     int i;
60749     const int iSavepoint = p->iStatement-1;
60750 
60751     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
60752     assert( db->nStatement>0 );
60753     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
60754 
60755     for(i=0; i<db->nDb; i++){
60756       int rc2 = SQLITE_OK;
60757       Btree *pBt = db->aDb[i].pBt;
60758       if( pBt ){
60759         if( eOp==SAVEPOINT_ROLLBACK ){
60760           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
60761         }
60762         if( rc2==SQLITE_OK ){
60763           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
60764         }
60765         if( rc==SQLITE_OK ){
60766           rc = rc2;
60767         }
60768       }
60769     }
60770     db->nStatement--;
60771     p->iStatement = 0;
60772 
60773     if( rc==SQLITE_OK ){
60774       if( eOp==SAVEPOINT_ROLLBACK ){
60775         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
60776       }
60777       if( rc==SQLITE_OK ){
60778         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
60779       }
60780     }
60781 
60782     /* If the statement transaction is being rolled back, also restore the
60783     ** database handles deferred constraint counter to the value it had when
60784     ** the statement transaction was opened.  */
60785     if( eOp==SAVEPOINT_ROLLBACK ){
60786       db->nDeferredCons = p->nStmtDefCons;
60787     }
60788   }
60789   return rc;
60790 }
60791 
60792 /*
60793 ** This function is called when a transaction opened by the database
60794 ** handle associated with the VM passed as an argument is about to be
60795 ** committed. If there are outstanding deferred foreign key constraint
60796 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
60797 **
60798 ** If there are outstanding FK violations and this function returns
60799 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
60800 ** and write an error message to it. Then return SQLITE_ERROR.
60801 */
60802 #ifndef SQLITE_OMIT_FOREIGN_KEY
60803 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
60804   sqlite3 *db = p->db;
60805   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
60806     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
60807     p->errorAction = OE_Abort;
60808     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
60809     return SQLITE_ERROR;
60810   }
60811   return SQLITE_OK;
60812 }
60813 #endif
60814 
60815 /*
60816 ** This routine is called the when a VDBE tries to halt.  If the VDBE
60817 ** has made changes and is in autocommit mode, then commit those
60818 ** changes.  If a rollback is needed, then do the rollback.
60819 **
60820 ** This routine is the only way to move the state of a VM from
60821 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
60822 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
60823 **
60824 ** Return an error code.  If the commit could not complete because of
60825 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
60826 ** means the close did not happen and needs to be repeated.
60827 */
60828 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
60829   int rc;                         /* Used to store transient return codes */
60830   sqlite3 *db = p->db;
60831 
60832   /* This function contains the logic that determines if a statement or
60833   ** transaction will be committed or rolled back as a result of the
60834   ** execution of this virtual machine.
60835   **
60836   ** If any of the following errors occur:
60837   **
60838   **     SQLITE_NOMEM
60839   **     SQLITE_IOERR
60840   **     SQLITE_FULL
60841   **     SQLITE_INTERRUPT
60842   **
60843   ** Then the internal cache might have been left in an inconsistent
60844   ** state.  We need to rollback the statement transaction, if there is
60845   ** one, or the complete transaction if there is no statement transaction.
60846   */
60847 
60848   if( p->db->mallocFailed ){
60849     p->rc = SQLITE_NOMEM;
60850   }
60851   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
60852   closeAllCursors(p);
60853   if( p->magic!=VDBE_MAGIC_RUN ){
60854     return SQLITE_OK;
60855   }
60856   checkActiveVdbeCnt(db);
60857 
60858   /* No commit or rollback needed if the program never started */
60859   if( p->pc>=0 ){
60860     int mrc;   /* Primary error code from p->rc */
60861     int eStatementOp = 0;
60862     int isSpecialError;            /* Set to true if a 'special' error */
60863 
60864     /* Lock all btrees used by the statement */
60865     sqlite3VdbeEnter(p);
60866 
60867     /* Check for one of the special errors */
60868     mrc = p->rc & 0xff;
60869     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
60870     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
60871                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
60872     if( isSpecialError ){
60873       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
60874       ** no rollback is necessary. Otherwise, at least a savepoint
60875       ** transaction must be rolled back to restore the database to a
60876       ** consistent state.
60877       **
60878       ** Even if the statement is read-only, it is important to perform
60879       ** a statement or transaction rollback operation. If the error
60880       ** occurred while writing to the journal, sub-journal or database
60881       ** file as part of an effort to free up cache space (see function
60882       ** pagerStress() in pager.c), the rollback is required to restore
60883       ** the pager to a consistent state.
60884       */
60885       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
60886         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
60887           eStatementOp = SAVEPOINT_ROLLBACK;
60888         }else{
60889           /* We are forced to roll back the active transaction. Before doing
60890           ** so, abort any other statements this handle currently has active.
60891           */
60892           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60893           sqlite3CloseSavepoints(db);
60894           db->autoCommit = 1;
60895         }
60896       }
60897     }
60898 
60899     /* Check for immediate foreign key violations. */
60900     if( p->rc==SQLITE_OK ){
60901       sqlite3VdbeCheckFk(p, 0);
60902     }
60903 
60904     /* If the auto-commit flag is set and this is the only active writer
60905     ** VM, then we do either a commit or rollback of the current transaction.
60906     **
60907     ** Note: This block also runs if one of the special errors handled
60908     ** above has occurred.
60909     */
60910     if( !sqlite3VtabInSync(db)
60911      && db->autoCommit
60912      && db->writeVdbeCnt==(p->readOnly==0)
60913     ){
60914       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
60915         rc = sqlite3VdbeCheckFk(p, 1);
60916         if( rc!=SQLITE_OK ){
60917           if( NEVER(p->readOnly) ){
60918             sqlite3VdbeLeave(p);
60919             return SQLITE_ERROR;
60920           }
60921           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
60922         }else{
60923           /* The auto-commit flag is true, the vdbe program was successful
60924           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
60925           ** key constraints to hold up the transaction. This means a commit
60926           ** is required. */
60927           rc = vdbeCommit(db, p);
60928         }
60929         if( rc==SQLITE_BUSY && p->readOnly ){
60930           sqlite3VdbeLeave(p);
60931           return SQLITE_BUSY;
60932         }else if( rc!=SQLITE_OK ){
60933           p->rc = rc;
60934           sqlite3RollbackAll(db, SQLITE_OK);
60935         }else{
60936           db->nDeferredCons = 0;
60937           sqlite3CommitInternalChanges(db);
60938         }
60939       }else{
60940         sqlite3RollbackAll(db, SQLITE_OK);
60941       }
60942       db->nStatement = 0;
60943     }else if( eStatementOp==0 ){
60944       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
60945         eStatementOp = SAVEPOINT_RELEASE;
60946       }else if( p->errorAction==OE_Abort ){
60947         eStatementOp = SAVEPOINT_ROLLBACK;
60948       }else{
60949         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60950         sqlite3CloseSavepoints(db);
60951         db->autoCommit = 1;
60952       }
60953     }
60954 
60955     /* If eStatementOp is non-zero, then a statement transaction needs to
60956     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
60957     ** do so. If this operation returns an error, and the current statement
60958     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
60959     ** current statement error code.
60960     */
60961     if( eStatementOp ){
60962       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
60963       if( rc ){
60964         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
60965           p->rc = rc;
60966           sqlite3DbFree(db, p->zErrMsg);
60967           p->zErrMsg = 0;
60968         }
60969         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
60970         sqlite3CloseSavepoints(db);
60971         db->autoCommit = 1;
60972       }
60973     }
60974 
60975     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
60976     ** has been rolled back, update the database connection change-counter.
60977     */
60978     if( p->changeCntOn ){
60979       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
60980         sqlite3VdbeSetChanges(db, p->nChange);
60981       }else{
60982         sqlite3VdbeSetChanges(db, 0);
60983       }
60984       p->nChange = 0;
60985     }
60986 
60987     /* Release the locks */
60988     sqlite3VdbeLeave(p);
60989   }
60990 
60991   /* We have successfully halted and closed the VM.  Record this fact. */
60992   if( p->pc>=0 ){
60993     db->activeVdbeCnt--;
60994     if( !p->readOnly ){
60995       db->writeVdbeCnt--;
60996     }
60997     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
60998   }
60999   p->magic = VDBE_MAGIC_HALT;
61000   checkActiveVdbeCnt(db);
61001   if( p->db->mallocFailed ){
61002     p->rc = SQLITE_NOMEM;
61003   }
61004 
61005   /* If the auto-commit flag is set to true, then any locks that were held
61006   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
61007   ** to invoke any required unlock-notify callbacks.
61008   */
61009   if( db->autoCommit ){
61010     sqlite3ConnectionUnlocked(db);
61011   }
61012 
61013   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
61014   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
61015 }
61016 
61017 
61018 /*
61019 ** Each VDBE holds the result of the most recent sqlite3_step() call
61020 ** in p->rc.  This routine sets that result back to SQLITE_OK.
61021 */
61022 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
61023   p->rc = SQLITE_OK;
61024 }
61025 
61026 /*
61027 ** Copy the error code and error message belonging to the VDBE passed
61028 ** as the first argument to its database handle (so that they will be
61029 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
61030 **
61031 ** This function does not clear the VDBE error code or message, just
61032 ** copies them to the database handle.
61033 */
61034 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
61035   sqlite3 *db = p->db;
61036   int rc = p->rc;
61037   if( p->zErrMsg ){
61038     u8 mallocFailed = db->mallocFailed;
61039     sqlite3BeginBenignMalloc();
61040     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61041     sqlite3EndBenignMalloc();
61042     db->mallocFailed = mallocFailed;
61043     db->errCode = rc;
61044   }else{
61045     sqlite3Error(db, rc, 0);
61046   }
61047   return rc;
61048 }
61049 
61050 #ifdef SQLITE_ENABLE_SQLLOG
61051 /*
61052 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
61053 ** invoke it.
61054 */
61055 static void vdbeInvokeSqllog(Vdbe *v){
61056   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
61057     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
61058     assert( v->db->init.busy==0 );
61059     if( zExpanded ){
61060       sqlite3GlobalConfig.xSqllog(
61061           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
61062       );
61063       sqlite3DbFree(v->db, zExpanded);
61064     }
61065   }
61066 }
61067 #else
61068 # define vdbeInvokeSqllog(x)
61069 #endif
61070 
61071 /*
61072 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
61073 ** Write any error messages into *pzErrMsg.  Return the result code.
61074 **
61075 ** After this routine is run, the VDBE should be ready to be executed
61076 ** again.
61077 **
61078 ** To look at it another way, this routine resets the state of the
61079 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
61080 ** VDBE_MAGIC_INIT.
61081 */
61082 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
61083   sqlite3 *db;
61084   db = p->db;
61085 
61086   /* If the VM did not run to completion or if it encountered an
61087   ** error, then it might not have been halted properly.  So halt
61088   ** it now.
61089   */
61090   sqlite3VdbeHalt(p);
61091 
61092   /* If the VDBE has be run even partially, then transfer the error code
61093   ** and error message from the VDBE into the main database structure.  But
61094   ** if the VDBE has just been set to run but has not actually executed any
61095   ** instructions yet, leave the main database error information unchanged.
61096   */
61097   if( p->pc>=0 ){
61098     vdbeInvokeSqllog(p);
61099     sqlite3VdbeTransferError(p);
61100     sqlite3DbFree(db, p->zErrMsg);
61101     p->zErrMsg = 0;
61102     if( p->runOnlyOnce ) p->expired = 1;
61103   }else if( p->rc && p->expired ){
61104     /* The expired flag was set on the VDBE before the first call
61105     ** to sqlite3_step(). For consistency (since sqlite3_step() was
61106     ** called), set the database error in this case as well.
61107     */
61108     sqlite3Error(db, p->rc, 0);
61109     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61110     sqlite3DbFree(db, p->zErrMsg);
61111     p->zErrMsg = 0;
61112   }
61113 
61114   /* Reclaim all memory used by the VDBE
61115   */
61116   Cleanup(p);
61117 
61118   /* Save profiling information from this VDBE run.
61119   */
61120 #ifdef VDBE_PROFILE
61121   {
61122     FILE *out = fopen("vdbe_profile.out", "a");
61123     if( out ){
61124       int i;
61125       fprintf(out, "---- ");
61126       for(i=0; i<p->nOp; i++){
61127         fprintf(out, "%02x", p->aOp[i].opcode);
61128       }
61129       fprintf(out, "\n");
61130       for(i=0; i<p->nOp; i++){
61131         fprintf(out, "%6d %10lld %8lld ",
61132            p->aOp[i].cnt,
61133            p->aOp[i].cycles,
61134            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
61135         );
61136         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
61137       }
61138       fclose(out);
61139     }
61140   }
61141 #endif
61142   p->magic = VDBE_MAGIC_INIT;
61143   return p->rc & db->errMask;
61144 }
61145 
61146 /*
61147 ** Clean up and delete a VDBE after execution.  Return an integer which is
61148 ** the result code.  Write any error message text into *pzErrMsg.
61149 */
61150 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
61151   int rc = SQLITE_OK;
61152   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
61153     rc = sqlite3VdbeReset(p);
61154     assert( (rc & p->db->errMask)==rc );
61155   }
61156   sqlite3VdbeDelete(p);
61157   return rc;
61158 }
61159 
61160 /*
61161 ** Call the destructor for each auxdata entry in pVdbeFunc for which
61162 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
61163 ** are always destroyed.  To destroy all auxdata entries, call this
61164 ** routine with mask==0.
61165 */
61166 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
61167   int i;
61168   for(i=0; i<pVdbeFunc->nAux; i++){
61169     struct AuxData *pAux = &pVdbeFunc->apAux[i];
61170     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
61171       if( pAux->xDelete ){
61172         pAux->xDelete(pAux->pAux);
61173       }
61174       pAux->pAux = 0;
61175     }
61176   }
61177 }
61178 
61179 /*
61180 ** Free all memory associated with the Vdbe passed as the second argument,
61181 ** except for object itself, which is preserved.
61182 **
61183 ** The difference between this function and sqlite3VdbeDelete() is that
61184 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
61185 ** the database connection and frees the object itself.
61186 */
61187 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
61188   SubProgram *pSub, *pNext;
61189   int i;
61190   assert( p->db==0 || p->db==db );
61191   releaseMemArray(p->aVar, p->nVar);
61192   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61193   for(pSub=p->pProgram; pSub; pSub=pNext){
61194     pNext = pSub->pNext;
61195     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
61196     sqlite3DbFree(db, pSub);
61197   }
61198   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
61199   vdbeFreeOpArray(db, p->aOp, p->nOp);
61200   sqlite3DbFree(db, p->aLabel);
61201   sqlite3DbFree(db, p->aColName);
61202   sqlite3DbFree(db, p->zSql);
61203   sqlite3DbFree(db, p->pFree);
61204 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
61205   sqlite3DbFree(db, p->zExplain);
61206   sqlite3DbFree(db, p->pExplain);
61207 #endif
61208 }
61209 
61210 /*
61211 ** Delete an entire VDBE.
61212 */
61213 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
61214   sqlite3 *db;
61215 
61216   if( NEVER(p==0) ) return;
61217   db = p->db;
61218   assert( sqlite3_mutex_held(db->mutex) );
61219   sqlite3VdbeClearObject(db, p);
61220   if( p->pPrev ){
61221     p->pPrev->pNext = p->pNext;
61222   }else{
61223     assert( db->pVdbe==p );
61224     db->pVdbe = p->pNext;
61225   }
61226   if( p->pNext ){
61227     p->pNext->pPrev = p->pPrev;
61228   }
61229   p->magic = VDBE_MAGIC_DEAD;
61230   p->db = 0;
61231   sqlite3DbFree(db, p);
61232 }
61233 
61234 /*
61235 ** Make sure the cursor p is ready to read or write the row to which it
61236 ** was last positioned.  Return an error code if an OOM fault or I/O error
61237 ** prevents us from positioning the cursor to its correct position.
61238 **
61239 ** If a MoveTo operation is pending on the given cursor, then do that
61240 ** MoveTo now.  If no move is pending, check to see if the row has been
61241 ** deleted out from under the cursor and if it has, mark the row as
61242 ** a NULL row.
61243 **
61244 ** If the cursor is already pointing to the correct row and that row has
61245 ** not been deleted out from under the cursor, then this routine is a no-op.
61246 */
61247 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
61248   if( p->deferredMoveto ){
61249     int res, rc;
61250 #ifdef SQLITE_TEST
61251     extern int sqlite3_search_count;
61252 #endif
61253     assert( p->isTable );
61254     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
61255     if( rc ) return rc;
61256     p->lastRowid = p->movetoTarget;
61257     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
61258     p->rowidIsValid = 1;
61259 #ifdef SQLITE_TEST
61260     sqlite3_search_count++;
61261 #endif
61262     p->deferredMoveto = 0;
61263     p->cacheStatus = CACHE_STALE;
61264   }else if( ALWAYS(p->pCursor) ){
61265     int hasMoved;
61266     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
61267     if( rc ) return rc;
61268     if( hasMoved ){
61269       p->cacheStatus = CACHE_STALE;
61270       p->nullRow = 1;
61271     }
61272   }
61273   return SQLITE_OK;
61274 }
61275 
61276 /*
61277 ** The following functions:
61278 **
61279 ** sqlite3VdbeSerialType()
61280 ** sqlite3VdbeSerialTypeLen()
61281 ** sqlite3VdbeSerialLen()
61282 ** sqlite3VdbeSerialPut()
61283 ** sqlite3VdbeSerialGet()
61284 **
61285 ** encapsulate the code that serializes values for storage in SQLite
61286 ** data and index records. Each serialized value consists of a
61287 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
61288 ** integer, stored as a varint.
61289 **
61290 ** In an SQLite index record, the serial type is stored directly before
61291 ** the blob of data that it corresponds to. In a table record, all serial
61292 ** types are stored at the start of the record, and the blobs of data at
61293 ** the end. Hence these functions allow the caller to handle the
61294 ** serial-type and data blob separately.
61295 **
61296 ** The following table describes the various storage classes for data:
61297 **
61298 **   serial type        bytes of data      type
61299 **   --------------     ---------------    ---------------
61300 **      0                     0            NULL
61301 **      1                     1            signed integer
61302 **      2                     2            signed integer
61303 **      3                     3            signed integer
61304 **      4                     4            signed integer
61305 **      5                     6            signed integer
61306 **      6                     8            signed integer
61307 **      7                     8            IEEE float
61308 **      8                     0            Integer constant 0
61309 **      9                     0            Integer constant 1
61310 **     10,11                               reserved for expansion
61311 **    N>=12 and even       (N-12)/2        BLOB
61312 **    N>=13 and odd        (N-13)/2        text
61313 **
61314 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
61315 ** of SQLite will not understand those serial types.
61316 */
61317 
61318 /*
61319 ** Return the serial-type for the value stored in pMem.
61320 */
61321 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
61322   int flags = pMem->flags;
61323   int n;
61324 
61325   if( flags&MEM_Null ){
61326     return 0;
61327   }
61328   if( flags&MEM_Int ){
61329     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
61330 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
61331     i64 i = pMem->u.i;
61332     u64 u;
61333     if( i<0 ){
61334       if( i<(-MAX_6BYTE) ) return 6;
61335       /* Previous test prevents:  u = -(-9223372036854775808) */
61336       u = -i;
61337     }else{
61338       u = i;
61339     }
61340     if( u<=127 ){
61341       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
61342     }
61343     if( u<=32767 ) return 2;
61344     if( u<=8388607 ) return 3;
61345     if( u<=2147483647 ) return 4;
61346     if( u<=MAX_6BYTE ) return 5;
61347     return 6;
61348   }
61349   if( flags&MEM_Real ){
61350     return 7;
61351   }
61352   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
61353   n = pMem->n;
61354   if( flags & MEM_Zero ){
61355     n += pMem->u.nZero;
61356   }
61357   assert( n>=0 );
61358   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
61359 }
61360 
61361 /*
61362 ** Return the length of the data corresponding to the supplied serial-type.
61363 */
61364 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
61365   if( serial_type>=12 ){
61366     return (serial_type-12)/2;
61367   }else{
61368     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
61369     return aSize[serial_type];
61370   }
61371 }
61372 
61373 /*
61374 ** If we are on an architecture with mixed-endian floating
61375 ** points (ex: ARM7) then swap the lower 4 bytes with the
61376 ** upper 4 bytes.  Return the result.
61377 **
61378 ** For most architectures, this is a no-op.
61379 **
61380 ** (later):  It is reported to me that the mixed-endian problem
61381 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
61382 ** that early versions of GCC stored the two words of a 64-bit
61383 ** float in the wrong order.  And that error has been propagated
61384 ** ever since.  The blame is not necessarily with GCC, though.
61385 ** GCC might have just copying the problem from a prior compiler.
61386 ** I am also told that newer versions of GCC that follow a different
61387 ** ABI get the byte order right.
61388 **
61389 ** Developers using SQLite on an ARM7 should compile and run their
61390 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
61391 ** enabled, some asserts below will ensure that the byte order of
61392 ** floating point values is correct.
61393 **
61394 ** (2007-08-30)  Frank van Vugt has studied this problem closely
61395 ** and has send his findings to the SQLite developers.  Frank
61396 ** writes that some Linux kernels offer floating point hardware
61397 ** emulation that uses only 32-bit mantissas instead of a full
61398 ** 48-bits as required by the IEEE standard.  (This is the
61399 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
61400 ** byte swapping becomes very complicated.  To avoid problems,
61401 ** the necessary byte swapping is carried out using a 64-bit integer
61402 ** rather than a 64-bit float.  Frank assures us that the code here
61403 ** works for him.  We, the developers, have no way to independently
61404 ** verify this, but Frank seems to know what he is talking about
61405 ** so we trust him.
61406 */
61407 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
61408 static u64 floatSwap(u64 in){
61409   union {
61410     u64 r;
61411     u32 i[2];
61412   } u;
61413   u32 t;
61414 
61415   u.r = in;
61416   t = u.i[0];
61417   u.i[0] = u.i[1];
61418   u.i[1] = t;
61419   return u.r;
61420 }
61421 # define swapMixedEndianFloat(X)  X = floatSwap(X)
61422 #else
61423 # define swapMixedEndianFloat(X)
61424 #endif
61425 
61426 /*
61427 ** Write the serialized data blob for the value stored in pMem into
61428 ** buf. It is assumed that the caller has allocated sufficient space.
61429 ** Return the number of bytes written.
61430 **
61431 ** nBuf is the amount of space left in buf[].  nBuf must always be
61432 ** large enough to hold the entire field.  Except, if the field is
61433 ** a blob with a zero-filled tail, then buf[] might be just the right
61434 ** size to hold everything except for the zero-filled tail.  If buf[]
61435 ** is only big enough to hold the non-zero prefix, then only write that
61436 ** prefix into buf[].  But if buf[] is large enough to hold both the
61437 ** prefix and the tail then write the prefix and set the tail to all
61438 ** zeros.
61439 **
61440 ** Return the number of bytes actually written into buf[].  The number
61441 ** of bytes in the zero-filled tail is included in the return value only
61442 ** if those bytes were zeroed in buf[].
61443 */
61444 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
61445   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
61446   u32 len;
61447 
61448   /* Integer and Real */
61449   if( serial_type<=7 && serial_type>0 ){
61450     u64 v;
61451     u32 i;
61452     if( serial_type==7 ){
61453       assert( sizeof(v)==sizeof(pMem->r) );
61454       memcpy(&v, &pMem->r, sizeof(v));
61455       swapMixedEndianFloat(v);
61456     }else{
61457       v = pMem->u.i;
61458     }
61459     len = i = sqlite3VdbeSerialTypeLen(serial_type);
61460     assert( len<=(u32)nBuf );
61461     while( i-- ){
61462       buf[i] = (u8)(v&0xFF);
61463       v >>= 8;
61464     }
61465     return len;
61466   }
61467 
61468   /* String or blob */
61469   if( serial_type>=12 ){
61470     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
61471              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
61472     assert( pMem->n<=nBuf );
61473     len = pMem->n;
61474     memcpy(buf, pMem->z, len);
61475     if( pMem->flags & MEM_Zero ){
61476       len += pMem->u.nZero;
61477       assert( nBuf>=0 );
61478       if( len > (u32)nBuf ){
61479         len = (u32)nBuf;
61480       }
61481       memset(&buf[pMem->n], 0, len-pMem->n);
61482     }
61483     return len;
61484   }
61485 
61486   /* NULL or constants 0 or 1 */
61487   return 0;
61488 }
61489 
61490 /*
61491 ** Deserialize the data blob pointed to by buf as serial type serial_type
61492 ** and store the result in pMem.  Return the number of bytes read.
61493 */
61494 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
61495   const unsigned char *buf,     /* Buffer to deserialize from */
61496   u32 serial_type,              /* Serial type to deserialize */
61497   Mem *pMem                     /* Memory cell to write value into */
61498 ){
61499   switch( serial_type ){
61500     case 10:   /* Reserved for future use */
61501     case 11:   /* Reserved for future use */
61502     case 0: {  /* NULL */
61503       pMem->flags = MEM_Null;
61504       break;
61505     }
61506     case 1: { /* 1-byte signed integer */
61507       pMem->u.i = (signed char)buf[0];
61508       pMem->flags = MEM_Int;
61509       return 1;
61510     }
61511     case 2: { /* 2-byte signed integer */
61512       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
61513       pMem->flags = MEM_Int;
61514       return 2;
61515     }
61516     case 3: { /* 3-byte signed integer */
61517       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
61518       pMem->flags = MEM_Int;
61519       return 3;
61520     }
61521     case 4: { /* 4-byte signed integer */
61522       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61523       pMem->flags = MEM_Int;
61524       return 4;
61525     }
61526     case 5: { /* 6-byte signed integer */
61527       u64 x = (((signed char)buf[0])<<8) | buf[1];
61528       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
61529       x = (x<<32) | y;
61530       pMem->u.i = *(i64*)&x;
61531       pMem->flags = MEM_Int;
61532       return 6;
61533     }
61534     case 6:   /* 8-byte signed integer */
61535     case 7: { /* IEEE floating point */
61536       u64 x;
61537       u32 y;
61538 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
61539       /* Verify that integers and floating point values use the same
61540       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
61541       ** defined that 64-bit floating point values really are mixed
61542       ** endian.
61543       */
61544       static const u64 t1 = ((u64)0x3ff00000)<<32;
61545       static const double r1 = 1.0;
61546       u64 t2 = t1;
61547       swapMixedEndianFloat(t2);
61548       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
61549 #endif
61550 
61551       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61552       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
61553       x = (x<<32) | y;
61554       if( serial_type==6 ){
61555         pMem->u.i = *(i64*)&x;
61556         pMem->flags = MEM_Int;
61557       }else{
61558         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
61559         swapMixedEndianFloat(x);
61560         memcpy(&pMem->r, &x, sizeof(x));
61561         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
61562       }
61563       return 8;
61564     }
61565     case 8:    /* Integer 0 */
61566     case 9: {  /* Integer 1 */
61567       pMem->u.i = serial_type-8;
61568       pMem->flags = MEM_Int;
61569       return 0;
61570     }
61571     default: {
61572       u32 len = (serial_type-12)/2;
61573       pMem->z = (char *)buf;
61574       pMem->n = len;
61575       pMem->xDel = 0;
61576       if( serial_type&0x01 ){
61577         pMem->flags = MEM_Str | MEM_Ephem;
61578       }else{
61579         pMem->flags = MEM_Blob | MEM_Ephem;
61580       }
61581       return len;
61582     }
61583   }
61584   return 0;
61585 }
61586 
61587 /*
61588 ** This routine is used to allocate sufficient space for an UnpackedRecord
61589 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
61590 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
61591 **
61592 ** The space is either allocated using sqlite3DbMallocRaw() or from within
61593 ** the unaligned buffer passed via the second and third arguments (presumably
61594 ** stack space). If the former, then *ppFree is set to a pointer that should
61595 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
61596 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
61597 ** before returning.
61598 **
61599 ** If an OOM error occurs, NULL is returned.
61600 */
61601 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
61602   KeyInfo *pKeyInfo,              /* Description of the record */
61603   char *pSpace,                   /* Unaligned space available */
61604   int szSpace,                    /* Size of pSpace[] in bytes */
61605   char **ppFree                   /* OUT: Caller should free this pointer */
61606 ){
61607   UnpackedRecord *p;              /* Unpacked record to return */
61608   int nOff;                       /* Increment pSpace by nOff to align it */
61609   int nByte;                      /* Number of bytes required for *p */
61610 
61611   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
61612   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
61613   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
61614   */
61615   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
61616   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
61617   if( nByte>szSpace+nOff ){
61618     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
61619     *ppFree = (char *)p;
61620     if( !p ) return 0;
61621   }else{
61622     p = (UnpackedRecord*)&pSpace[nOff];
61623     *ppFree = 0;
61624   }
61625 
61626   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
61627   assert( pKeyInfo->aSortOrder!=0 );
61628   p->pKeyInfo = pKeyInfo;
61629   p->nField = pKeyInfo->nField + 1;
61630   return p;
61631 }
61632 
61633 /*
61634 ** Given the nKey-byte encoding of a record in pKey[], populate the
61635 ** UnpackedRecord structure indicated by the fourth argument with the
61636 ** contents of the decoded record.
61637 */
61638 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
61639   KeyInfo *pKeyInfo,     /* Information about the record format */
61640   int nKey,              /* Size of the binary record */
61641   const void *pKey,      /* The binary record */
61642   UnpackedRecord *p      /* Populate this structure before returning. */
61643 ){
61644   const unsigned char *aKey = (const unsigned char *)pKey;
61645   int d;
61646   u32 idx;                        /* Offset in aKey[] to read from */
61647   u16 u;                          /* Unsigned loop counter */
61648   u32 szHdr;
61649   Mem *pMem = p->aMem;
61650 
61651   p->flags = 0;
61652   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61653   idx = getVarint32(aKey, szHdr);
61654   d = szHdr;
61655   u = 0;
61656   while( idx<szHdr && u<p->nField && d<=nKey ){
61657     u32 serial_type;
61658 
61659     idx += getVarint32(&aKey[idx], serial_type);
61660     pMem->enc = pKeyInfo->enc;
61661     pMem->db = pKeyInfo->db;
61662     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
61663     pMem->zMalloc = 0;
61664     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
61665     pMem++;
61666     u++;
61667   }
61668   assert( u<=pKeyInfo->nField + 1 );
61669   p->nField = u;
61670 }
61671 
61672 /*
61673 ** This function compares the two table rows or index records
61674 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
61675 ** or positive integer if key1 is less than, equal to or
61676 ** greater than key2.  The {nKey1, pKey1} key must be a blob
61677 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
61678 ** key must be a parsed key such as obtained from
61679 ** sqlite3VdbeParseRecord.
61680 **
61681 ** Key1 and Key2 do not have to contain the same number of fields.
61682 ** The key with fewer fields is usually compares less than the
61683 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
61684 ** and the common prefixes are equal, then key1 is less than key2.
61685 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
61686 ** equal, then the keys are considered to be equal and
61687 ** the parts beyond the common prefix are ignored.
61688 */
61689 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
61690   int nKey1, const void *pKey1, /* Left key */
61691   UnpackedRecord *pPKey2        /* Right key */
61692 ){
61693   int d1;            /* Offset into aKey[] of next data element */
61694   u32 idx1;          /* Offset into aKey[] of next header element */
61695   u32 szHdr1;        /* Number of bytes in header */
61696   int i = 0;
61697   int nField;
61698   int rc = 0;
61699   const unsigned char *aKey1 = (const unsigned char *)pKey1;
61700   KeyInfo *pKeyInfo;
61701   Mem mem1;
61702 
61703   pKeyInfo = pPKey2->pKeyInfo;
61704   mem1.enc = pKeyInfo->enc;
61705   mem1.db = pKeyInfo->db;
61706   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
61707   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
61708 
61709   /* Compilers may complain that mem1.u.i is potentially uninitialized.
61710   ** We could initialize it, as shown here, to silence those complaints.
61711   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
61712   ** the unnecessary initialization has a measurable negative performance
61713   ** impact, since this routine is a very high runner.  And so, we choose
61714   ** to ignore the compiler warnings and leave this variable uninitialized.
61715   */
61716   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
61717 
61718   idx1 = getVarint32(aKey1, szHdr1);
61719   d1 = szHdr1;
61720   nField = pKeyInfo->nField;
61721   assert( pKeyInfo->aSortOrder!=0 );
61722   while( idx1<szHdr1 && i<pPKey2->nField ){
61723     u32 serial_type1;
61724 
61725     /* Read the serial types for the next element in each key. */
61726     idx1 += getVarint32( aKey1+idx1, serial_type1 );
61727     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
61728 
61729     /* Extract the values to be compared.
61730     */
61731     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
61732 
61733     /* Do the comparison
61734     */
61735     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
61736                            i<nField ? pKeyInfo->aColl[i] : 0);
61737     if( rc!=0 ){
61738       assert( mem1.zMalloc==0 );  /* See comment below */
61739 
61740       /* Invert the result if we are using DESC sort order. */
61741       if( i<nField && pKeyInfo->aSortOrder[i] ){
61742         rc = -rc;
61743       }
61744 
61745       /* If the PREFIX_SEARCH flag is set and all fields except the final
61746       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
61747       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
61748       ** This is used by the OP_IsUnique opcode.
61749       */
61750       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
61751         assert( idx1==szHdr1 && rc );
61752         assert( mem1.flags & MEM_Int );
61753         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
61754         pPKey2->rowid = mem1.u.i;
61755       }
61756 
61757       return rc;
61758     }
61759     i++;
61760   }
61761 
61762   /* No memory allocation is ever used on mem1.  Prove this using
61763   ** the following assert().  If the assert() fails, it indicates a
61764   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
61765   */
61766   assert( mem1.zMalloc==0 );
61767 
61768   /* rc==0 here means that one of the keys ran out of fields and
61769   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
61770   ** flag is set, then break the tie by treating key2 as larger.
61771   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
61772   ** are considered to be equal.  Otherwise, the longer key is the
61773   ** larger.  As it happens, the pPKey2 will always be the longer
61774   ** if there is a difference.
61775   */
61776   assert( rc==0 );
61777   if( pPKey2->flags & UNPACKED_INCRKEY ){
61778     rc = -1;
61779   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
61780     /* Leave rc==0 */
61781   }else if( idx1<szHdr1 ){
61782     rc = 1;
61783   }
61784   return rc;
61785 }
61786 
61787 
61788 /*
61789 ** pCur points at an index entry created using the OP_MakeRecord opcode.
61790 ** Read the rowid (the last field in the record) and store it in *rowid.
61791 ** Return SQLITE_OK if everything works, or an error code otherwise.
61792 **
61793 ** pCur might be pointing to text obtained from a corrupt database file.
61794 ** So the content cannot be trusted.  Do appropriate checks on the content.
61795 */
61796 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
61797   i64 nCellKey = 0;
61798   int rc;
61799   u32 szHdr;        /* Size of the header */
61800   u32 typeRowid;    /* Serial type of the rowid */
61801   u32 lenRowid;     /* Size of the rowid */
61802   Mem m, v;
61803 
61804   UNUSED_PARAMETER(db);
61805 
61806   /* Get the size of the index entry.  Only indices entries of less
61807   ** than 2GiB are support - anything large must be database corruption.
61808   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
61809   ** this code can safely assume that nCellKey is 32-bits
61810   */
61811   assert( sqlite3BtreeCursorIsValid(pCur) );
61812   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61813   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
61814   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
61815 
61816   /* Read in the complete content of the index entry */
61817   memset(&m, 0, sizeof(m));
61818   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
61819   if( rc ){
61820     return rc;
61821   }
61822 
61823   /* The index entry must begin with a header size */
61824   (void)getVarint32((u8*)m.z, szHdr);
61825   testcase( szHdr==3 );
61826   testcase( szHdr==m.n );
61827   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
61828     goto idx_rowid_corruption;
61829   }
61830 
61831   /* The last field of the index should be an integer - the ROWID.
61832   ** Verify that the last entry really is an integer. */
61833   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
61834   testcase( typeRowid==1 );
61835   testcase( typeRowid==2 );
61836   testcase( typeRowid==3 );
61837   testcase( typeRowid==4 );
61838   testcase( typeRowid==5 );
61839   testcase( typeRowid==6 );
61840   testcase( typeRowid==8 );
61841   testcase( typeRowid==9 );
61842   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
61843     goto idx_rowid_corruption;
61844   }
61845   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
61846   testcase( (u32)m.n==szHdr+lenRowid );
61847   if( unlikely((u32)m.n<szHdr+lenRowid) ){
61848     goto idx_rowid_corruption;
61849   }
61850 
61851   /* Fetch the integer off the end of the index record */
61852   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
61853   *rowid = v.u.i;
61854   sqlite3VdbeMemRelease(&m);
61855   return SQLITE_OK;
61856 
61857   /* Jump here if database corruption is detected after m has been
61858   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
61859 idx_rowid_corruption:
61860   testcase( m.zMalloc!=0 );
61861   sqlite3VdbeMemRelease(&m);
61862   return SQLITE_CORRUPT_BKPT;
61863 }
61864 
61865 /*
61866 ** Compare the key of the index entry that cursor pC is pointing to against
61867 ** the key string in pUnpacked.  Write into *pRes a number
61868 ** that is negative, zero, or positive if pC is less than, equal to,
61869 ** or greater than pUnpacked.  Return SQLITE_OK on success.
61870 **
61871 ** pUnpacked is either created without a rowid or is truncated so that it
61872 ** omits the rowid at the end.  The rowid at the end of the index entry
61873 ** is ignored as well.  Hence, this routine only compares the prefixes
61874 ** of the keys prior to the final rowid, not the entire key.
61875 */
61876 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
61877   VdbeCursor *pC,             /* The cursor to compare against */
61878   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
61879   int *res                    /* Write the comparison result here */
61880 ){
61881   i64 nCellKey = 0;
61882   int rc;
61883   BtCursor *pCur = pC->pCursor;
61884   Mem m;
61885 
61886   assert( sqlite3BtreeCursorIsValid(pCur) );
61887   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61888   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
61889   /* nCellKey will always be between 0 and 0xffffffff because of the say
61890   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
61891   if( nCellKey<=0 || nCellKey>0x7fffffff ){
61892     *res = 0;
61893     return SQLITE_CORRUPT_BKPT;
61894   }
61895   memset(&m, 0, sizeof(m));
61896   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
61897   if( rc ){
61898     return rc;
61899   }
61900   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
61901   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
61902   sqlite3VdbeMemRelease(&m);
61903   return SQLITE_OK;
61904 }
61905 
61906 /*
61907 ** This routine sets the value to be returned by subsequent calls to
61908 ** sqlite3_changes() on the database handle 'db'.
61909 */
61910 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
61911   assert( sqlite3_mutex_held(db->mutex) );
61912   db->nChange = nChange;
61913   db->nTotalChange += nChange;
61914 }
61915 
61916 /*
61917 ** Set a flag in the vdbe to update the change counter when it is finalised
61918 ** or reset.
61919 */
61920 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
61921   v->changeCntOn = 1;
61922 }
61923 
61924 /*
61925 ** Mark every prepared statement associated with a database connection
61926 ** as expired.
61927 **
61928 ** An expired statement means that recompilation of the statement is
61929 ** recommend.  Statements expire when things happen that make their
61930 ** programs obsolete.  Removing user-defined functions or collating
61931 ** sequences, or changing an authorization function are the types of
61932 ** things that make prepared statements obsolete.
61933 */
61934 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
61935   Vdbe *p;
61936   for(p = db->pVdbe; p; p=p->pNext){
61937     p->expired = 1;
61938   }
61939 }
61940 
61941 /*
61942 ** Return the database associated with the Vdbe.
61943 */
61944 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
61945   return v->db;
61946 }
61947 
61948 /*
61949 ** Return a pointer to an sqlite3_value structure containing the value bound
61950 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
61951 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
61952 ** constants) to the value before returning it.
61953 **
61954 ** The returned value must be freed by the caller using sqlite3ValueFree().
61955 */
61956 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
61957   assert( iVar>0 );
61958   if( v ){
61959     Mem *pMem = &v->aVar[iVar-1];
61960     if( 0==(pMem->flags & MEM_Null) ){
61961       sqlite3_value *pRet = sqlite3ValueNew(v->db);
61962       if( pRet ){
61963         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
61964         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
61965         sqlite3VdbeMemStoreType((Mem *)pRet);
61966       }
61967       return pRet;
61968     }
61969   }
61970   return 0;
61971 }
61972 
61973 /*
61974 ** Configure SQL variable iVar so that binding a new value to it signals
61975 ** to sqlite3_reoptimize() that re-preparing the statement may result
61976 ** in a better query plan.
61977 */
61978 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
61979   assert( iVar>0 );
61980   if( iVar>32 ){
61981     v->expmask = 0xffffffff;
61982   }else{
61983     v->expmask |= ((u32)1 << (iVar-1));
61984   }
61985 }
61986 
61987 /************** End of vdbeaux.c *********************************************/
61988 /************** Begin file vdbeapi.c *****************************************/
61989 /*
61990 ** 2004 May 26
61991 **
61992 ** The author disclaims copyright to this source code.  In place of
61993 ** a legal notice, here is a blessing:
61994 **
61995 **    May you do good and not evil.
61996 **    May you find forgiveness for yourself and forgive others.
61997 **    May you share freely, never taking more than you give.
61998 **
61999 *************************************************************************
62000 **
62001 ** This file contains code use to implement APIs that are part of the
62002 ** VDBE.
62003 */
62004 
62005 #ifndef SQLITE_OMIT_DEPRECATED
62006 /*
62007 ** Return TRUE (non-zero) of the statement supplied as an argument needs
62008 ** to be recompiled.  A statement needs to be recompiled whenever the
62009 ** execution environment changes in a way that would alter the program
62010 ** that sqlite3_prepare() generates.  For example, if new functions or
62011 ** collating sequences are registered or if an authorizer function is
62012 ** added or changed.
62013 */
62014 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
62015   Vdbe *p = (Vdbe*)pStmt;
62016   return p==0 || p->expired;
62017 }
62018 #endif
62019 
62020 /*
62021 ** Check on a Vdbe to make sure it has not been finalized.  Log
62022 ** an error and return true if it has been finalized (or is otherwise
62023 ** invalid).  Return false if it is ok.
62024 */
62025 static int vdbeSafety(Vdbe *p){
62026   if( p->db==0 ){
62027     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
62028     return 1;
62029   }else{
62030     return 0;
62031   }
62032 }
62033 static int vdbeSafetyNotNull(Vdbe *p){
62034   if( p==0 ){
62035     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
62036     return 1;
62037   }else{
62038     return vdbeSafety(p);
62039   }
62040 }
62041 
62042 /*
62043 ** The following routine destroys a virtual machine that is created by
62044 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
62045 ** success/failure code that describes the result of executing the virtual
62046 ** machine.
62047 **
62048 ** This routine sets the error code and string returned by
62049 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62050 */
62051 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
62052   int rc;
62053   if( pStmt==0 ){
62054     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
62055     ** pointer is a harmless no-op. */
62056     rc = SQLITE_OK;
62057   }else{
62058     Vdbe *v = (Vdbe*)pStmt;
62059     sqlite3 *db = v->db;
62060     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
62061     sqlite3_mutex_enter(db->mutex);
62062     rc = sqlite3VdbeFinalize(v);
62063     rc = sqlite3ApiExit(db, rc);
62064     sqlite3LeaveMutexAndCloseZombie(db);
62065   }
62066   return rc;
62067 }
62068 
62069 /*
62070 ** Terminate the current execution of an SQL statement and reset it
62071 ** back to its starting state so that it can be reused. A success code from
62072 ** the prior execution is returned.
62073 **
62074 ** This routine sets the error code and string returned by
62075 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62076 */
62077 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
62078   int rc;
62079   if( pStmt==0 ){
62080     rc = SQLITE_OK;
62081   }else{
62082     Vdbe *v = (Vdbe*)pStmt;
62083     sqlite3_mutex_enter(v->db->mutex);
62084     rc = sqlite3VdbeReset(v);
62085     sqlite3VdbeRewind(v);
62086     assert( (rc & (v->db->errMask))==rc );
62087     rc = sqlite3ApiExit(v->db, rc);
62088     sqlite3_mutex_leave(v->db->mutex);
62089   }
62090   return rc;
62091 }
62092 
62093 /*
62094 ** Set all the parameters in the compiled SQL statement to NULL.
62095 */
62096 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
62097   int i;
62098   int rc = SQLITE_OK;
62099   Vdbe *p = (Vdbe*)pStmt;
62100 #if SQLITE_THREADSAFE
62101   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
62102 #endif
62103   sqlite3_mutex_enter(mutex);
62104   for(i=0; i<p->nVar; i++){
62105     sqlite3VdbeMemRelease(&p->aVar[i]);
62106     p->aVar[i].flags = MEM_Null;
62107   }
62108   if( p->isPrepareV2 && p->expmask ){
62109     p->expired = 1;
62110   }
62111   sqlite3_mutex_leave(mutex);
62112   return rc;
62113 }
62114 
62115 
62116 /**************************** sqlite3_value_  *******************************
62117 ** The following routines extract information from a Mem or sqlite3_value
62118 ** structure.
62119 */
62120 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
62121   Mem *p = (Mem*)pVal;
62122   if( p->flags & (MEM_Blob|MEM_Str) ){
62123     sqlite3VdbeMemExpandBlob(p);
62124     p->flags &= ~MEM_Str;
62125     p->flags |= MEM_Blob;
62126     return p->n ? p->z : 0;
62127   }else{
62128     return sqlite3_value_text(pVal);
62129   }
62130 }
62131 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
62132   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
62133 }
62134 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
62135   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
62136 }
62137 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
62138   return sqlite3VdbeRealValue((Mem*)pVal);
62139 }
62140 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
62141   return (int)sqlite3VdbeIntValue((Mem*)pVal);
62142 }
62143 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
62144   return sqlite3VdbeIntValue((Mem*)pVal);
62145 }
62146 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
62147   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
62148 }
62149 #ifndef SQLITE_OMIT_UTF16
62150 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
62151   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
62152 }
62153 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
62154   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
62155 }
62156 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
62157   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
62158 }
62159 #endif /* SQLITE_OMIT_UTF16 */
62160 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
62161   return pVal->type;
62162 }
62163 
62164 /**************************** sqlite3_result_  *******************************
62165 ** The following routines are used by user-defined functions to specify
62166 ** the function result.
62167 **
62168 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
62169 ** result as a string or blob but if the string or blob is too large, it
62170 ** then sets the error code to SQLITE_TOOBIG
62171 */
62172 static void setResultStrOrError(
62173   sqlite3_context *pCtx,  /* Function context */
62174   const char *z,          /* String pointer */
62175   int n,                  /* Bytes in string, or negative */
62176   u8 enc,                 /* Encoding of z.  0 for BLOBs */
62177   void (*xDel)(void*)     /* Destructor function */
62178 ){
62179   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
62180     sqlite3_result_error_toobig(pCtx);
62181   }
62182 }
62183 SQLITE_API void sqlite3_result_blob(
62184   sqlite3_context *pCtx,
62185   const void *z,
62186   int n,
62187   void (*xDel)(void *)
62188 ){
62189   assert( n>=0 );
62190   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62191   setResultStrOrError(pCtx, z, n, 0, xDel);
62192 }
62193 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
62194   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62195   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
62196 }
62197 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
62198   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62199   pCtx->isError = SQLITE_ERROR;
62200   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
62201 }
62202 #ifndef SQLITE_OMIT_UTF16
62203 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
62204   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62205   pCtx->isError = SQLITE_ERROR;
62206   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
62207 }
62208 #endif
62209 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
62210   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62211   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
62212 }
62213 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
62214   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62215   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
62216 }
62217 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
62218   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62219   sqlite3VdbeMemSetNull(&pCtx->s);
62220 }
62221 SQLITE_API void sqlite3_result_text(
62222   sqlite3_context *pCtx,
62223   const char *z,
62224   int n,
62225   void (*xDel)(void *)
62226 ){
62227   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62228   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
62229 }
62230 #ifndef SQLITE_OMIT_UTF16
62231 SQLITE_API void sqlite3_result_text16(
62232   sqlite3_context *pCtx,
62233   const void *z,
62234   int n,
62235   void (*xDel)(void *)
62236 ){
62237   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62238   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
62239 }
62240 SQLITE_API void sqlite3_result_text16be(
62241   sqlite3_context *pCtx,
62242   const void *z,
62243   int n,
62244   void (*xDel)(void *)
62245 ){
62246   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62247   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
62248 }
62249 SQLITE_API void sqlite3_result_text16le(
62250   sqlite3_context *pCtx,
62251   const void *z,
62252   int n,
62253   void (*xDel)(void *)
62254 ){
62255   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62256   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
62257 }
62258 #endif /* SQLITE_OMIT_UTF16 */
62259 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
62260   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62261   sqlite3VdbeMemCopy(&pCtx->s, pValue);
62262 }
62263 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
62264   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62265   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
62266 }
62267 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
62268   pCtx->isError = errCode;
62269   if( pCtx->s.flags & MEM_Null ){
62270     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
62271                          SQLITE_UTF8, SQLITE_STATIC);
62272   }
62273 }
62274 
62275 /* Force an SQLITE_TOOBIG error. */
62276 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
62277   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62278   pCtx->isError = SQLITE_TOOBIG;
62279   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
62280                        SQLITE_UTF8, SQLITE_STATIC);
62281 }
62282 
62283 /* An SQLITE_NOMEM error. */
62284 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
62285   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62286   sqlite3VdbeMemSetNull(&pCtx->s);
62287   pCtx->isError = SQLITE_NOMEM;
62288   pCtx->s.db->mallocFailed = 1;
62289 }
62290 
62291 /*
62292 ** This function is called after a transaction has been committed. It
62293 ** invokes callbacks registered with sqlite3_wal_hook() as required.
62294 */
62295 static int doWalCallbacks(sqlite3 *db){
62296   int rc = SQLITE_OK;
62297 #ifndef SQLITE_OMIT_WAL
62298   int i;
62299   for(i=0; i<db->nDb; i++){
62300     Btree *pBt = db->aDb[i].pBt;
62301     if( pBt ){
62302       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
62303       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
62304         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
62305       }
62306     }
62307   }
62308 #endif
62309   return rc;
62310 }
62311 
62312 /*
62313 ** Execute the statement pStmt, either until a row of data is ready, the
62314 ** statement is completely executed or an error occurs.
62315 **
62316 ** This routine implements the bulk of the logic behind the sqlite_step()
62317 ** API.  The only thing omitted is the automatic recompile if a
62318 ** schema change has occurred.  That detail is handled by the
62319 ** outer sqlite3_step() wrapper procedure.
62320 */
62321 static int sqlite3Step(Vdbe *p){
62322   sqlite3 *db;
62323   int rc;
62324 
62325   assert(p);
62326   if( p->magic!=VDBE_MAGIC_RUN ){
62327     /* We used to require that sqlite3_reset() be called before retrying
62328     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
62329     ** with version 3.7.0, we changed this so that sqlite3_reset() would
62330     ** be called automatically instead of throwing the SQLITE_MISUSE error.
62331     ** This "automatic-reset" change is not technically an incompatibility,
62332     ** since any application that receives an SQLITE_MISUSE is broken by
62333     ** definition.
62334     **
62335     ** Nevertheless, some published applications that were originally written
62336     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
62337     ** returns, and those were broken by the automatic-reset change.  As a
62338     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
62339     ** legacy behavior of returning SQLITE_MISUSE for cases where the
62340     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
62341     ** or SQLITE_BUSY error.
62342     */
62343 #ifdef SQLITE_OMIT_AUTORESET
62344     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
62345       sqlite3_reset((sqlite3_stmt*)p);
62346     }else{
62347       return SQLITE_MISUSE_BKPT;
62348     }
62349 #else
62350     sqlite3_reset((sqlite3_stmt*)p);
62351 #endif
62352   }
62353 
62354   /* Check that malloc() has not failed. If it has, return early. */
62355   db = p->db;
62356   if( db->mallocFailed ){
62357     p->rc = SQLITE_NOMEM;
62358     return SQLITE_NOMEM;
62359   }
62360 
62361   if( p->pc<=0 && p->expired ){
62362     p->rc = SQLITE_SCHEMA;
62363     rc = SQLITE_ERROR;
62364     goto end_of_step;
62365   }
62366   if( p->pc<0 ){
62367     /* If there are no other statements currently running, then
62368     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
62369     ** from interrupting a statement that has not yet started.
62370     */
62371     if( db->activeVdbeCnt==0 ){
62372       db->u1.isInterrupted = 0;
62373     }
62374 
62375     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
62376 
62377 #ifndef SQLITE_OMIT_TRACE
62378     if( db->xProfile && !db->init.busy ){
62379       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
62380     }
62381 #endif
62382 
62383     db->activeVdbeCnt++;
62384     if( p->readOnly==0 ) db->writeVdbeCnt++;
62385     p->pc = 0;
62386   }
62387 #ifndef SQLITE_OMIT_EXPLAIN
62388   if( p->explain ){
62389     rc = sqlite3VdbeList(p);
62390   }else
62391 #endif /* SQLITE_OMIT_EXPLAIN */
62392   {
62393     db->vdbeExecCnt++;
62394     rc = sqlite3VdbeExec(p);
62395     db->vdbeExecCnt--;
62396   }
62397 
62398 #ifndef SQLITE_OMIT_TRACE
62399   /* Invoke the profile callback if there is one
62400   */
62401   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
62402     sqlite3_int64 iNow;
62403     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
62404     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
62405   }
62406 #endif
62407 
62408   if( rc==SQLITE_DONE ){
62409     assert( p->rc==SQLITE_OK );
62410     p->rc = doWalCallbacks(db);
62411     if( p->rc!=SQLITE_OK ){
62412       rc = SQLITE_ERROR;
62413     }
62414   }
62415 
62416   db->errCode = rc;
62417   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
62418     p->rc = SQLITE_NOMEM;
62419   }
62420 end_of_step:
62421   /* At this point local variable rc holds the value that should be
62422   ** returned if this statement was compiled using the legacy
62423   ** sqlite3_prepare() interface. According to the docs, this can only
62424   ** be one of the values in the first assert() below. Variable p->rc
62425   ** contains the value that would be returned if sqlite3_finalize()
62426   ** were called on statement p.
62427   */
62428   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
62429        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
62430   );
62431   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
62432   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
62433     /* If this statement was prepared using sqlite3_prepare_v2(), and an
62434     ** error has occurred, then return the error code in p->rc to the
62435     ** caller. Set the error code in the database handle to the same value.
62436     */
62437     rc = sqlite3VdbeTransferError(p);
62438   }
62439   return (rc&db->errMask);
62440 }
62441 
62442 /*
62443 ** The maximum number of times that a statement will try to reparse
62444 ** itself before giving up and returning SQLITE_SCHEMA.
62445 */
62446 #ifndef SQLITE_MAX_SCHEMA_RETRY
62447 # define SQLITE_MAX_SCHEMA_RETRY 5
62448 #endif
62449 
62450 /*
62451 ** This is the top-level implementation of sqlite3_step().  Call
62452 ** sqlite3Step() to do most of the work.  If a schema error occurs,
62453 ** call sqlite3Reprepare() and try again.
62454 */
62455 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
62456   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
62457   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
62458   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
62459   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
62460   sqlite3 *db;             /* The database connection */
62461 
62462   if( vdbeSafetyNotNull(v) ){
62463     return SQLITE_MISUSE_BKPT;
62464   }
62465   db = v->db;
62466   sqlite3_mutex_enter(db->mutex);
62467   v->doingRerun = 0;
62468   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
62469          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
62470          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
62471     sqlite3_reset(pStmt);
62472     v->doingRerun = 1;
62473     assert( v->expired==0 );
62474   }
62475   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
62476     /* This case occurs after failing to recompile an sql statement.
62477     ** The error message from the SQL compiler has already been loaded
62478     ** into the database handle. This block copies the error message
62479     ** from the database handle into the statement and sets the statement
62480     ** program counter to 0 to ensure that when the statement is
62481     ** finalized or reset the parser error message is available via
62482     ** sqlite3_errmsg() and sqlite3_errcode().
62483     */
62484     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
62485     sqlite3DbFree(db, v->zErrMsg);
62486     if( !db->mallocFailed ){
62487       v->zErrMsg = sqlite3DbStrDup(db, zErr);
62488       v->rc = rc2;
62489     } else {
62490       v->zErrMsg = 0;
62491       v->rc = rc = SQLITE_NOMEM;
62492     }
62493   }
62494   rc = sqlite3ApiExit(db, rc);
62495   sqlite3_mutex_leave(db->mutex);
62496   return rc;
62497 }
62498 
62499 /*
62500 ** Extract the user data from a sqlite3_context structure and return a
62501 ** pointer to it.
62502 */
62503 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
62504   assert( p && p->pFunc );
62505   return p->pFunc->pUserData;
62506 }
62507 
62508 /*
62509 ** Extract the user data from a sqlite3_context structure and return a
62510 ** pointer to it.
62511 **
62512 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
62513 ** returns a copy of the pointer to the database connection (the 1st
62514 ** parameter) of the sqlite3_create_function() and
62515 ** sqlite3_create_function16() routines that originally registered the
62516 ** application defined function.
62517 */
62518 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
62519   assert( p && p->pFunc );
62520   return p->s.db;
62521 }
62522 
62523 /*
62524 ** The following is the implementation of an SQL function that always
62525 ** fails with an error message stating that the function is used in the
62526 ** wrong context.  The sqlite3_overload_function() API might construct
62527 ** SQL function that use this routine so that the functions will exist
62528 ** for name resolution but are actually overloaded by the xFindFunction
62529 ** method of virtual tables.
62530 */
62531 SQLITE_PRIVATE void sqlite3InvalidFunction(
62532   sqlite3_context *context,  /* The function calling context */
62533   int NotUsed,               /* Number of arguments to the function */
62534   sqlite3_value **NotUsed2   /* Value of each argument */
62535 ){
62536   const char *zName = context->pFunc->zName;
62537   char *zErr;
62538   UNUSED_PARAMETER2(NotUsed, NotUsed2);
62539   zErr = sqlite3_mprintf(
62540       "unable to use function %s in the requested context", zName);
62541   sqlite3_result_error(context, zErr, -1);
62542   sqlite3_free(zErr);
62543 }
62544 
62545 /*
62546 ** Allocate or return the aggregate context for a user function.  A new
62547 ** context is allocated on the first call.  Subsequent calls return the
62548 ** same context that was returned on prior calls.
62549 */
62550 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
62551   Mem *pMem;
62552   assert( p && p->pFunc && p->pFunc->xStep );
62553   assert( sqlite3_mutex_held(p->s.db->mutex) );
62554   pMem = p->pMem;
62555   testcase( nByte<0 );
62556   if( (pMem->flags & MEM_Agg)==0 ){
62557     if( nByte<=0 ){
62558       sqlite3VdbeMemReleaseExternal(pMem);
62559       pMem->flags = MEM_Null;
62560       pMem->z = 0;
62561     }else{
62562       sqlite3VdbeMemGrow(pMem, nByte, 0);
62563       pMem->flags = MEM_Agg;
62564       pMem->u.pDef = p->pFunc;
62565       if( pMem->z ){
62566         memset(pMem->z, 0, nByte);
62567       }
62568     }
62569   }
62570   return (void*)pMem->z;
62571 }
62572 
62573 /*
62574 ** Return the auxilary data pointer, if any, for the iArg'th argument to
62575 ** the user-function defined by pCtx.
62576 */
62577 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
62578   VdbeFunc *pVdbeFunc;
62579 
62580   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62581   pVdbeFunc = pCtx->pVdbeFunc;
62582   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
62583     return 0;
62584   }
62585   return pVdbeFunc->apAux[iArg].pAux;
62586 }
62587 
62588 /*
62589 ** Set the auxilary data pointer and delete function, for the iArg'th
62590 ** argument to the user-function defined by pCtx. Any previous value is
62591 ** deleted by calling the delete function specified when it was set.
62592 */
62593 SQLITE_API void sqlite3_set_auxdata(
62594   sqlite3_context *pCtx,
62595   int iArg,
62596   void *pAux,
62597   void (*xDelete)(void*)
62598 ){
62599   struct AuxData *pAuxData;
62600   VdbeFunc *pVdbeFunc;
62601   if( iArg<0 ) goto failed;
62602 
62603   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62604   pVdbeFunc = pCtx->pVdbeFunc;
62605   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
62606     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
62607     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
62608     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
62609     if( !pVdbeFunc ){
62610       goto failed;
62611     }
62612     pCtx->pVdbeFunc = pVdbeFunc;
62613     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
62614     pVdbeFunc->nAux = iArg+1;
62615     pVdbeFunc->pFunc = pCtx->pFunc;
62616   }
62617 
62618   pAuxData = &pVdbeFunc->apAux[iArg];
62619   if( pAuxData->pAux && pAuxData->xDelete ){
62620     pAuxData->xDelete(pAuxData->pAux);
62621   }
62622   pAuxData->pAux = pAux;
62623   pAuxData->xDelete = xDelete;
62624   return;
62625 
62626 failed:
62627   if( xDelete ){
62628     xDelete(pAux);
62629   }
62630 }
62631 
62632 #ifndef SQLITE_OMIT_DEPRECATED
62633 /*
62634 ** Return the number of times the Step function of a aggregate has been
62635 ** called.
62636 **
62637 ** This function is deprecated.  Do not use it for new code.  It is
62638 ** provide only to avoid breaking legacy code.  New aggregate function
62639 ** implementations should keep their own counts within their aggregate
62640 ** context.
62641 */
62642 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
62643   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
62644   return p->pMem->n;
62645 }
62646 #endif
62647 
62648 /*
62649 ** Return the number of columns in the result set for the statement pStmt.
62650 */
62651 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
62652   Vdbe *pVm = (Vdbe *)pStmt;
62653   return pVm ? pVm->nResColumn : 0;
62654 }
62655 
62656 /*
62657 ** Return the number of values available from the current row of the
62658 ** currently executing statement pStmt.
62659 */
62660 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
62661   Vdbe *pVm = (Vdbe *)pStmt;
62662   if( pVm==0 || pVm->pResultSet==0 ) return 0;
62663   return pVm->nResColumn;
62664 }
62665 
62666 
62667 /*
62668 ** Check to see if column iCol of the given statement is valid.  If
62669 ** it is, return a pointer to the Mem for the value of that column.
62670 ** If iCol is not valid, return a pointer to a Mem which has a value
62671 ** of NULL.
62672 */
62673 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
62674   Vdbe *pVm;
62675   Mem *pOut;
62676 
62677   pVm = (Vdbe *)pStmt;
62678   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
62679     sqlite3_mutex_enter(pVm->db->mutex);
62680     pOut = &pVm->pResultSet[i];
62681   }else{
62682     /* If the value passed as the second argument is out of range, return
62683     ** a pointer to the following static Mem object which contains the
62684     ** value SQL NULL. Even though the Mem structure contains an element
62685     ** of type i64, on certain architectures (x86) with certain compiler
62686     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
62687     ** instead of an 8-byte one. This all works fine, except that when
62688     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
62689     ** that a Mem structure is located on an 8-byte boundary. To prevent
62690     ** these assert()s from failing, when building with SQLITE_DEBUG defined
62691     ** using gcc, we force nullMem to be 8-byte aligned using the magical
62692     ** __attribute__((aligned(8))) macro.  */
62693     static const Mem nullMem
62694 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
62695       __attribute__((aligned(8)))
62696 #endif
62697       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
62698 #ifdef SQLITE_DEBUG
62699          0, 0,  /* pScopyFrom, pFiller */
62700 #endif
62701          0, 0 };
62702 
62703     if( pVm && ALWAYS(pVm->db) ){
62704       sqlite3_mutex_enter(pVm->db->mutex);
62705       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
62706     }
62707     pOut = (Mem*)&nullMem;
62708   }
62709   return pOut;
62710 }
62711 
62712 /*
62713 ** This function is called after invoking an sqlite3_value_XXX function on a
62714 ** column value (i.e. a value returned by evaluating an SQL expression in the
62715 ** select list of a SELECT statement) that may cause a malloc() failure. If
62716 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
62717 ** code of statement pStmt set to SQLITE_NOMEM.
62718 **
62719 ** Specifically, this is called from within:
62720 **
62721 **     sqlite3_column_int()
62722 **     sqlite3_column_int64()
62723 **     sqlite3_column_text()
62724 **     sqlite3_column_text16()
62725 **     sqlite3_column_real()
62726 **     sqlite3_column_bytes()
62727 **     sqlite3_column_bytes16()
62728 **     sqiite3_column_blob()
62729 */
62730 static void columnMallocFailure(sqlite3_stmt *pStmt)
62731 {
62732   /* If malloc() failed during an encoding conversion within an
62733   ** sqlite3_column_XXX API, then set the return code of the statement to
62734   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
62735   ** and _finalize() will return NOMEM.
62736   */
62737   Vdbe *p = (Vdbe *)pStmt;
62738   if( p ){
62739     p->rc = sqlite3ApiExit(p->db, p->rc);
62740     sqlite3_mutex_leave(p->db->mutex);
62741   }
62742 }
62743 
62744 /**************************** sqlite3_column_  *******************************
62745 ** The following routines are used to access elements of the current row
62746 ** in the result set.
62747 */
62748 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
62749   const void *val;
62750   val = sqlite3_value_blob( columnMem(pStmt,i) );
62751   /* Even though there is no encoding conversion, value_blob() might
62752   ** need to call malloc() to expand the result of a zeroblob()
62753   ** expression.
62754   */
62755   columnMallocFailure(pStmt);
62756   return val;
62757 }
62758 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
62759   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
62760   columnMallocFailure(pStmt);
62761   return val;
62762 }
62763 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
62764   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
62765   columnMallocFailure(pStmt);
62766   return val;
62767 }
62768 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
62769   double val = sqlite3_value_double( columnMem(pStmt,i) );
62770   columnMallocFailure(pStmt);
62771   return val;
62772 }
62773 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
62774   int val = sqlite3_value_int( columnMem(pStmt,i) );
62775   columnMallocFailure(pStmt);
62776   return val;
62777 }
62778 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
62779   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
62780   columnMallocFailure(pStmt);
62781   return val;
62782 }
62783 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
62784   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
62785   columnMallocFailure(pStmt);
62786   return val;
62787 }
62788 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
62789   Mem *pOut = columnMem(pStmt, i);
62790   if( pOut->flags&MEM_Static ){
62791     pOut->flags &= ~MEM_Static;
62792     pOut->flags |= MEM_Ephem;
62793   }
62794   columnMallocFailure(pStmt);
62795   return (sqlite3_value *)pOut;
62796 }
62797 #ifndef SQLITE_OMIT_UTF16
62798 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
62799   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
62800   columnMallocFailure(pStmt);
62801   return val;
62802 }
62803 #endif /* SQLITE_OMIT_UTF16 */
62804 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
62805   int iType = sqlite3_value_type( columnMem(pStmt,i) );
62806   columnMallocFailure(pStmt);
62807   return iType;
62808 }
62809 
62810 /* The following function is experimental and subject to change or
62811 ** removal */
62812 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
62813 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
62814 **}
62815 */
62816 
62817 /*
62818 ** Convert the N-th element of pStmt->pColName[] into a string using
62819 ** xFunc() then return that string.  If N is out of range, return 0.
62820 **
62821 ** There are up to 5 names for each column.  useType determines which
62822 ** name is returned.  Here are the names:
62823 **
62824 **    0      The column name as it should be displayed for output
62825 **    1      The datatype name for the column
62826 **    2      The name of the database that the column derives from
62827 **    3      The name of the table that the column derives from
62828 **    4      The name of the table column that the result column derives from
62829 **
62830 ** If the result is not a simple column reference (if it is an expression
62831 ** or a constant) then useTypes 2, 3, and 4 return NULL.
62832 */
62833 static const void *columnName(
62834   sqlite3_stmt *pStmt,
62835   int N,
62836   const void *(*xFunc)(Mem*),
62837   int useType
62838 ){
62839   const void *ret = 0;
62840   Vdbe *p = (Vdbe *)pStmt;
62841   int n;
62842   sqlite3 *db = p->db;
62843 
62844   assert( db!=0 );
62845   n = sqlite3_column_count(pStmt);
62846   if( N<n && N>=0 ){
62847     N += useType*n;
62848     sqlite3_mutex_enter(db->mutex);
62849     assert( db->mallocFailed==0 );
62850     ret = xFunc(&p->aColName[N]);
62851      /* A malloc may have failed inside of the xFunc() call. If this
62852     ** is the case, clear the mallocFailed flag and return NULL.
62853     */
62854     if( db->mallocFailed ){
62855       db->mallocFailed = 0;
62856       ret = 0;
62857     }
62858     sqlite3_mutex_leave(db->mutex);
62859   }
62860   return ret;
62861 }
62862 
62863 /*
62864 ** Return the name of the Nth column of the result set returned by SQL
62865 ** statement pStmt.
62866 */
62867 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
62868   return columnName(
62869       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
62870 }
62871 #ifndef SQLITE_OMIT_UTF16
62872 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
62873   return columnName(
62874       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
62875 }
62876 #endif
62877 
62878 /*
62879 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
62880 ** not define OMIT_DECLTYPE.
62881 */
62882 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
62883 # error "Must not define both SQLITE_OMIT_DECLTYPE \
62884          and SQLITE_ENABLE_COLUMN_METADATA"
62885 #endif
62886 
62887 #ifndef SQLITE_OMIT_DECLTYPE
62888 /*
62889 ** Return the column declaration type (if applicable) of the 'i'th column
62890 ** of the result set of SQL statement pStmt.
62891 */
62892 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
62893   return columnName(
62894       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
62895 }
62896 #ifndef SQLITE_OMIT_UTF16
62897 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
62898   return columnName(
62899       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
62900 }
62901 #endif /* SQLITE_OMIT_UTF16 */
62902 #endif /* SQLITE_OMIT_DECLTYPE */
62903 
62904 #ifdef SQLITE_ENABLE_COLUMN_METADATA
62905 /*
62906 ** Return the name of the database from which a result column derives.
62907 ** NULL is returned if the result column is an expression or constant or
62908 ** anything else which is not an unabiguous reference to a database column.
62909 */
62910 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
62911   return columnName(
62912       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
62913 }
62914 #ifndef SQLITE_OMIT_UTF16
62915 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
62916   return columnName(
62917       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
62918 }
62919 #endif /* SQLITE_OMIT_UTF16 */
62920 
62921 /*
62922 ** Return the name of the table from which a result column derives.
62923 ** NULL is returned if the result column is an expression or constant or
62924 ** anything else which is not an unabiguous reference to a database column.
62925 */
62926 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
62927   return columnName(
62928       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
62929 }
62930 #ifndef SQLITE_OMIT_UTF16
62931 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
62932   return columnName(
62933       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
62934 }
62935 #endif /* SQLITE_OMIT_UTF16 */
62936 
62937 /*
62938 ** Return the name of the table column from which a result column derives.
62939 ** NULL is returned if the result column is an expression or constant or
62940 ** anything else which is not an unabiguous reference to a database column.
62941 */
62942 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
62943   return columnName(
62944       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
62945 }
62946 #ifndef SQLITE_OMIT_UTF16
62947 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
62948   return columnName(
62949       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
62950 }
62951 #endif /* SQLITE_OMIT_UTF16 */
62952 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
62953 
62954 
62955 /******************************* sqlite3_bind_  ***************************
62956 **
62957 ** Routines used to attach values to wildcards in a compiled SQL statement.
62958 */
62959 /*
62960 ** Unbind the value bound to variable i in virtual machine p. This is the
62961 ** the same as binding a NULL value to the column. If the "i" parameter is
62962 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
62963 **
62964 ** A successful evaluation of this routine acquires the mutex on p.
62965 ** the mutex is released if any kind of error occurs.
62966 **
62967 ** The error code stored in database p->db is overwritten with the return
62968 ** value in any case.
62969 */
62970 static int vdbeUnbind(Vdbe *p, int i){
62971   Mem *pVar;
62972   if( vdbeSafetyNotNull(p) ){
62973     return SQLITE_MISUSE_BKPT;
62974   }
62975   sqlite3_mutex_enter(p->db->mutex);
62976   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
62977     sqlite3Error(p->db, SQLITE_MISUSE, 0);
62978     sqlite3_mutex_leave(p->db->mutex);
62979     sqlite3_log(SQLITE_MISUSE,
62980         "bind on a busy prepared statement: [%s]", p->zSql);
62981     return SQLITE_MISUSE_BKPT;
62982   }
62983   if( i<1 || i>p->nVar ){
62984     sqlite3Error(p->db, SQLITE_RANGE, 0);
62985     sqlite3_mutex_leave(p->db->mutex);
62986     return SQLITE_RANGE;
62987   }
62988   i--;
62989   pVar = &p->aVar[i];
62990   sqlite3VdbeMemRelease(pVar);
62991   pVar->flags = MEM_Null;
62992   sqlite3Error(p->db, SQLITE_OK, 0);
62993 
62994   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
62995   ** binding a new value to this variable invalidates the current query plan.
62996   **
62997   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
62998   ** parameter in the WHERE clause might influence the choice of query plan
62999   ** for a statement, then the statement will be automatically recompiled,
63000   ** as if there had been a schema change, on the first sqlite3_step() call
63001   ** following any change to the bindings of that parameter.
63002   */
63003   if( p->isPrepareV2 &&
63004      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
63005   ){
63006     p->expired = 1;
63007   }
63008   return SQLITE_OK;
63009 }
63010 
63011 /*
63012 ** Bind a text or BLOB value.
63013 */
63014 static int bindText(
63015   sqlite3_stmt *pStmt,   /* The statement to bind against */
63016   int i,                 /* Index of the parameter to bind */
63017   const void *zData,     /* Pointer to the data to be bound */
63018   int nData,             /* Number of bytes of data to be bound */
63019   void (*xDel)(void*),   /* Destructor for the data */
63020   u8 encoding            /* Encoding for the data */
63021 ){
63022   Vdbe *p = (Vdbe *)pStmt;
63023   Mem *pVar;
63024   int rc;
63025 
63026   rc = vdbeUnbind(p, i);
63027   if( rc==SQLITE_OK ){
63028     if( zData!=0 ){
63029       pVar = &p->aVar[i-1];
63030       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
63031       if( rc==SQLITE_OK && encoding!=0 ){
63032         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
63033       }
63034       sqlite3Error(p->db, rc, 0);
63035       rc = sqlite3ApiExit(p->db, rc);
63036     }
63037     sqlite3_mutex_leave(p->db->mutex);
63038   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
63039     xDel((void*)zData);
63040   }
63041   return rc;
63042 }
63043 
63044 
63045 /*
63046 ** Bind a blob value to an SQL statement variable.
63047 */
63048 SQLITE_API int sqlite3_bind_blob(
63049   sqlite3_stmt *pStmt,
63050   int i,
63051   const void *zData,
63052   int nData,
63053   void (*xDel)(void*)
63054 ){
63055   return bindText(pStmt, i, zData, nData, xDel, 0);
63056 }
63057 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
63058   int rc;
63059   Vdbe *p = (Vdbe *)pStmt;
63060   rc = vdbeUnbind(p, i);
63061   if( rc==SQLITE_OK ){
63062     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
63063     sqlite3_mutex_leave(p->db->mutex);
63064   }
63065   return rc;
63066 }
63067 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
63068   return sqlite3_bind_int64(p, i, (i64)iValue);
63069 }
63070 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
63071   int rc;
63072   Vdbe *p = (Vdbe *)pStmt;
63073   rc = vdbeUnbind(p, i);
63074   if( rc==SQLITE_OK ){
63075     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
63076     sqlite3_mutex_leave(p->db->mutex);
63077   }
63078   return rc;
63079 }
63080 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
63081   int rc;
63082   Vdbe *p = (Vdbe*)pStmt;
63083   rc = vdbeUnbind(p, i);
63084   if( rc==SQLITE_OK ){
63085     sqlite3_mutex_leave(p->db->mutex);
63086   }
63087   return rc;
63088 }
63089 SQLITE_API int sqlite3_bind_text(
63090   sqlite3_stmt *pStmt,
63091   int i,
63092   const char *zData,
63093   int nData,
63094   void (*xDel)(void*)
63095 ){
63096   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
63097 }
63098 #ifndef SQLITE_OMIT_UTF16
63099 SQLITE_API int sqlite3_bind_text16(
63100   sqlite3_stmt *pStmt,
63101   int i,
63102   const void *zData,
63103   int nData,
63104   void (*xDel)(void*)
63105 ){
63106   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
63107 }
63108 #endif /* SQLITE_OMIT_UTF16 */
63109 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
63110   int rc;
63111   switch( pValue->type ){
63112     case SQLITE_INTEGER: {
63113       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
63114       break;
63115     }
63116     case SQLITE_FLOAT: {
63117       rc = sqlite3_bind_double(pStmt, i, pValue->r);
63118       break;
63119     }
63120     case SQLITE_BLOB: {
63121       if( pValue->flags & MEM_Zero ){
63122         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
63123       }else{
63124         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
63125       }
63126       break;
63127     }
63128     case SQLITE_TEXT: {
63129       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
63130                               pValue->enc);
63131       break;
63132     }
63133     default: {
63134       rc = sqlite3_bind_null(pStmt, i);
63135       break;
63136     }
63137   }
63138   return rc;
63139 }
63140 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
63141   int rc;
63142   Vdbe *p = (Vdbe *)pStmt;
63143   rc = vdbeUnbind(p, i);
63144   if( rc==SQLITE_OK ){
63145     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
63146     sqlite3_mutex_leave(p->db->mutex);
63147   }
63148   return rc;
63149 }
63150 
63151 /*
63152 ** Return the number of wildcards that can be potentially bound to.
63153 ** This routine is added to support DBD::SQLite.
63154 */
63155 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
63156   Vdbe *p = (Vdbe*)pStmt;
63157   return p ? p->nVar : 0;
63158 }
63159 
63160 /*
63161 ** Return the name of a wildcard parameter.  Return NULL if the index
63162 ** is out of range or if the wildcard is unnamed.
63163 **
63164 ** The result is always UTF-8.
63165 */
63166 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
63167   Vdbe *p = (Vdbe*)pStmt;
63168   if( p==0 || i<1 || i>p->nzVar ){
63169     return 0;
63170   }
63171   return p->azVar[i-1];
63172 }
63173 
63174 /*
63175 ** Given a wildcard parameter name, return the index of the variable
63176 ** with that name.  If there is no variable with the given name,
63177 ** return 0.
63178 */
63179 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
63180   int i;
63181   if( p==0 ){
63182     return 0;
63183   }
63184   if( zName ){
63185     for(i=0; i<p->nzVar; i++){
63186       const char *z = p->azVar[i];
63187       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
63188         return i+1;
63189       }
63190     }
63191   }
63192   return 0;
63193 }
63194 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
63195   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
63196 }
63197 
63198 /*
63199 ** Transfer all bindings from the first statement over to the second.
63200 */
63201 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63202   Vdbe *pFrom = (Vdbe*)pFromStmt;
63203   Vdbe *pTo = (Vdbe*)pToStmt;
63204   int i;
63205   assert( pTo->db==pFrom->db );
63206   assert( pTo->nVar==pFrom->nVar );
63207   sqlite3_mutex_enter(pTo->db->mutex);
63208   for(i=0; i<pFrom->nVar; i++){
63209     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
63210   }
63211   sqlite3_mutex_leave(pTo->db->mutex);
63212   return SQLITE_OK;
63213 }
63214 
63215 #ifndef SQLITE_OMIT_DEPRECATED
63216 /*
63217 ** Deprecated external interface.  Internal/core SQLite code
63218 ** should call sqlite3TransferBindings.
63219 **
63220 ** Is is misuse to call this routine with statements from different
63221 ** database connections.  But as this is a deprecated interface, we
63222 ** will not bother to check for that condition.
63223 **
63224 ** If the two statements contain a different number of bindings, then
63225 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
63226 ** SQLITE_OK is returned.
63227 */
63228 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63229   Vdbe *pFrom = (Vdbe*)pFromStmt;
63230   Vdbe *pTo = (Vdbe*)pToStmt;
63231   if( pFrom->nVar!=pTo->nVar ){
63232     return SQLITE_ERROR;
63233   }
63234   if( pTo->isPrepareV2 && pTo->expmask ){
63235     pTo->expired = 1;
63236   }
63237   if( pFrom->isPrepareV2 && pFrom->expmask ){
63238     pFrom->expired = 1;
63239   }
63240   return sqlite3TransferBindings(pFromStmt, pToStmt);
63241 }
63242 #endif
63243 
63244 /*
63245 ** Return the sqlite3* database handle to which the prepared statement given
63246 ** in the argument belongs.  This is the same database handle that was
63247 ** the first argument to the sqlite3_prepare() that was used to create
63248 ** the statement in the first place.
63249 */
63250 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
63251   return pStmt ? ((Vdbe*)pStmt)->db : 0;
63252 }
63253 
63254 /*
63255 ** Return true if the prepared statement is guaranteed to not modify the
63256 ** database.
63257 */
63258 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
63259   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
63260 }
63261 
63262 /*
63263 ** Return true if the prepared statement is in need of being reset.
63264 */
63265 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
63266   Vdbe *v = (Vdbe*)pStmt;
63267   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
63268 }
63269 
63270 /*
63271 ** Return a pointer to the next prepared statement after pStmt associated
63272 ** with database connection pDb.  If pStmt is NULL, return the first
63273 ** prepared statement for the database connection.  Return NULL if there
63274 ** are no more.
63275 */
63276 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
63277   sqlite3_stmt *pNext;
63278   sqlite3_mutex_enter(pDb->mutex);
63279   if( pStmt==0 ){
63280     pNext = (sqlite3_stmt*)pDb->pVdbe;
63281   }else{
63282     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
63283   }
63284   sqlite3_mutex_leave(pDb->mutex);
63285   return pNext;
63286 }
63287 
63288 /*
63289 ** Return the value of a status counter for a prepared statement
63290 */
63291 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
63292   Vdbe *pVdbe = (Vdbe*)pStmt;
63293   int v = pVdbe->aCounter[op-1];
63294   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
63295   return v;
63296 }
63297 
63298 /************** End of vdbeapi.c *********************************************/
63299 /************** Begin file vdbetrace.c ***************************************/
63300 /*
63301 ** 2009 November 25
63302 **
63303 ** The author disclaims copyright to this source code.  In place of
63304 ** a legal notice, here is a blessing:
63305 **
63306 **    May you do good and not evil.
63307 **    May you find forgiveness for yourself and forgive others.
63308 **    May you share freely, never taking more than you give.
63309 **
63310 *************************************************************************
63311 **
63312 ** This file contains code used to insert the values of host parameters
63313 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
63314 **
63315 ** The Vdbe parse-tree explainer is also found here.
63316 */
63317 
63318 #ifndef SQLITE_OMIT_TRACE
63319 
63320 /*
63321 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
63322 ** bytes in this text up to but excluding the first character in
63323 ** a host parameter.  If the text contains no host parameters, return
63324 ** the total number of bytes in the text.
63325 */
63326 static int findNextHostParameter(const char *zSql, int *pnToken){
63327   int tokenType;
63328   int nTotal = 0;
63329   int n;
63330 
63331   *pnToken = 0;
63332   while( zSql[0] ){
63333     n = sqlite3GetToken((u8*)zSql, &tokenType);
63334     assert( n>0 && tokenType!=TK_ILLEGAL );
63335     if( tokenType==TK_VARIABLE ){
63336       *pnToken = n;
63337       break;
63338     }
63339     nTotal += n;
63340     zSql += n;
63341   }
63342   return nTotal;
63343 }
63344 
63345 /*
63346 ** This function returns a pointer to a nul-terminated string in memory
63347 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
63348 ** string contains a copy of zRawSql but with host parameters expanded to
63349 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
63350 ** then the returned string holds a copy of zRawSql with "-- " prepended
63351 ** to each line of text.
63352 **
63353 ** The calling function is responsible for making sure the memory returned
63354 ** is eventually freed.
63355 **
63356 ** ALGORITHM:  Scan the input string looking for host parameters in any of
63357 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
63358 ** string literals, quoted identifier names, and comments.  For text forms,
63359 ** the host parameter index is found by scanning the perpared
63360 ** statement for the corresponding OP_Variable opcode.  Once the host
63361 ** parameter index is known, locate the value in p->aVar[].  Then render
63362 ** the value as a literal in place of the host parameter name.
63363 */
63364 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
63365   Vdbe *p,                 /* The prepared statement being evaluated */
63366   const char *zRawSql      /* Raw text of the SQL statement */
63367 ){
63368   sqlite3 *db;             /* The database connection */
63369   int idx = 0;             /* Index of a host parameter */
63370   int nextIndex = 1;       /* Index of next ? host parameter */
63371   int n;                   /* Length of a token prefix */
63372   int nToken;              /* Length of the parameter token */
63373   int i;                   /* Loop counter */
63374   Mem *pVar;               /* Value of a host parameter */
63375   StrAccum out;            /* Accumulate the output here */
63376   char zBase[100];         /* Initial working space */
63377 
63378   db = p->db;
63379   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
63380                       db->aLimit[SQLITE_LIMIT_LENGTH]);
63381   out.db = db;
63382   if( db->vdbeExecCnt>1 ){
63383     while( *zRawSql ){
63384       const char *zStart = zRawSql;
63385       while( *(zRawSql++)!='\n' && *zRawSql );
63386       sqlite3StrAccumAppend(&out, "-- ", 3);
63387       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
63388     }
63389   }else{
63390     while( zRawSql[0] ){
63391       n = findNextHostParameter(zRawSql, &nToken);
63392       assert( n>0 );
63393       sqlite3StrAccumAppend(&out, zRawSql, n);
63394       zRawSql += n;
63395       assert( zRawSql[0] || nToken==0 );
63396       if( nToken==0 ) break;
63397       if( zRawSql[0]=='?' ){
63398         if( nToken>1 ){
63399           assert( sqlite3Isdigit(zRawSql[1]) );
63400           sqlite3GetInt32(&zRawSql[1], &idx);
63401         }else{
63402           idx = nextIndex;
63403         }
63404       }else{
63405         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
63406         testcase( zRawSql[0]==':' );
63407         testcase( zRawSql[0]=='$' );
63408         testcase( zRawSql[0]=='@' );
63409         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
63410         assert( idx>0 );
63411       }
63412       zRawSql += nToken;
63413       nextIndex = idx + 1;
63414       assert( idx>0 && idx<=p->nVar );
63415       pVar = &p->aVar[idx-1];
63416       if( pVar->flags & MEM_Null ){
63417         sqlite3StrAccumAppend(&out, "NULL", 4);
63418       }else if( pVar->flags & MEM_Int ){
63419         sqlite3XPrintf(&out, "%lld", pVar->u.i);
63420       }else if( pVar->flags & MEM_Real ){
63421         sqlite3XPrintf(&out, "%!.15g", pVar->r);
63422       }else if( pVar->flags & MEM_Str ){
63423 #ifndef SQLITE_OMIT_UTF16
63424         u8 enc = ENC(db);
63425         if( enc!=SQLITE_UTF8 ){
63426           Mem utf8;
63427           memset(&utf8, 0, sizeof(utf8));
63428           utf8.db = db;
63429           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
63430           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
63431           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
63432           sqlite3VdbeMemRelease(&utf8);
63433         }else
63434 #endif
63435         {
63436           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
63437         }
63438       }else if( pVar->flags & MEM_Zero ){
63439         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
63440       }else{
63441         assert( pVar->flags & MEM_Blob );
63442         sqlite3StrAccumAppend(&out, "x'", 2);
63443         for(i=0; i<pVar->n; i++){
63444           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
63445         }
63446         sqlite3StrAccumAppend(&out, "'", 1);
63447       }
63448     }
63449   }
63450   return sqlite3StrAccumFinish(&out);
63451 }
63452 
63453 #endif /* #ifndef SQLITE_OMIT_TRACE */
63454 
63455 /*****************************************************************************
63456 ** The following code implements the data-structure explaining logic
63457 ** for the Vdbe.
63458 */
63459 
63460 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
63461 
63462 /*
63463 ** Allocate a new Explain object
63464 */
63465 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
63466   if( pVdbe ){
63467     Explain *p;
63468     sqlite3BeginBenignMalloc();
63469     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
63470     if( p ){
63471       p->pVdbe = pVdbe;
63472       sqlite3_free(pVdbe->pExplain);
63473       pVdbe->pExplain = p;
63474       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
63475                           SQLITE_MAX_LENGTH);
63476       p->str.useMalloc = 2;
63477     }else{
63478       sqlite3EndBenignMalloc();
63479     }
63480   }
63481 }
63482 
63483 /*
63484 ** Return true if the Explain ends with a new-line.
63485 */
63486 static int endsWithNL(Explain *p){
63487   return p && p->str.zText && p->str.nChar
63488            && p->str.zText[p->str.nChar-1]=='\n';
63489 }
63490 
63491 /*
63492 ** Append text to the indentation
63493 */
63494 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
63495   Explain *p;
63496   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
63497     va_list ap;
63498     if( p->nIndent && endsWithNL(p) ){
63499       int n = p->nIndent;
63500       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
63501       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
63502     }
63503     va_start(ap, zFormat);
63504     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
63505     va_end(ap);
63506   }
63507 }
63508 
63509 /*
63510 ** Append a '\n' if there is not already one.
63511 */
63512 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
63513   Explain *p;
63514   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
63515     sqlite3StrAccumAppend(&p->str, "\n", 1);
63516   }
63517 }
63518 
63519 /*
63520 ** Push a new indentation level.  Subsequent lines will be indented
63521 ** so that they begin at the current cursor position.
63522 */
63523 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
63524   Explain *p;
63525   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
63526     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
63527       const char *z = p->str.zText;
63528       int i = p->str.nChar-1;
63529       int x;
63530       while( i>=0 && z[i]!='\n' ){ i--; }
63531       x = (p->str.nChar - 1) - i;
63532       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
63533         x = p->aIndent[p->nIndent-1];
63534       }
63535       p->aIndent[p->nIndent] = x;
63536     }
63537     p->nIndent++;
63538   }
63539 }
63540 
63541 /*
63542 ** Pop the indentation stack by one level.
63543 */
63544 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
63545   if( p && p->pExplain ) p->pExplain->nIndent--;
63546 }
63547 
63548 /*
63549 ** Free the indentation structure
63550 */
63551 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
63552   if( pVdbe && pVdbe->pExplain ){
63553     sqlite3_free(pVdbe->zExplain);
63554     sqlite3ExplainNL(pVdbe);
63555     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
63556     sqlite3_free(pVdbe->pExplain);
63557     pVdbe->pExplain = 0;
63558     sqlite3EndBenignMalloc();
63559   }
63560 }
63561 
63562 /*
63563 ** Return the explanation of a virtual machine.
63564 */
63565 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
63566   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
63567 }
63568 #endif /* defined(SQLITE_DEBUG) */
63569 
63570 /************** End of vdbetrace.c *******************************************/
63571 /************** Begin file vdbe.c ********************************************/
63572 /*
63573 ** 2001 September 15
63574 **
63575 ** The author disclaims copyright to this source code.  In place of
63576 ** a legal notice, here is a blessing:
63577 **
63578 **    May you do good and not evil.
63579 **    May you find forgiveness for yourself and forgive others.
63580 **    May you share freely, never taking more than you give.
63581 **
63582 *************************************************************************
63583 ** The code in this file implements execution method of the
63584 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
63585 ** handles housekeeping details such as creating and deleting
63586 ** VDBE instances.  This file is solely interested in executing
63587 ** the VDBE program.
63588 **
63589 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
63590 ** to a VDBE.
63591 **
63592 ** The SQL parser generates a program which is then executed by
63593 ** the VDBE to do the work of the SQL statement.  VDBE programs are
63594 ** similar in form to assembly language.  The program consists of
63595 ** a linear sequence of operations.  Each operation has an opcode
63596 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
63597 ** is a null-terminated string.  Operand P5 is an unsigned character.
63598 ** Few opcodes use all 5 operands.
63599 **
63600 ** Computation results are stored on a set of registers numbered beginning
63601 ** with 1 and going up to Vdbe.nMem.  Each register can store
63602 ** either an integer, a null-terminated string, a floating point
63603 ** number, or the SQL "NULL" value.  An implicit conversion from one
63604 ** type to the other occurs as necessary.
63605 **
63606 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
63607 ** function which does the work of interpreting a VDBE program.
63608 ** But other routines are also provided to help in building up
63609 ** a program instruction by instruction.
63610 **
63611 ** Various scripts scan this source file in order to generate HTML
63612 ** documentation, headers files, or other derived files.  The formatting
63613 ** of the code in this file is, therefore, important.  See other comments
63614 ** in this file for details.  If in doubt, do not deviate from existing
63615 ** commenting and indentation practices when changing or adding code.
63616 */
63617 
63618 /*
63619 ** Invoke this macro on memory cells just prior to changing the
63620 ** value of the cell.  This macro verifies that shallow copies are
63621 ** not misused.
63622 */
63623 #ifdef SQLITE_DEBUG
63624 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
63625 #else
63626 # define memAboutToChange(P,M)
63627 #endif
63628 
63629 /*
63630 ** The following global variable is incremented every time a cursor
63631 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
63632 ** procedures use this information to make sure that indices are
63633 ** working correctly.  This variable has no function other than to
63634 ** help verify the correct operation of the library.
63635 */
63636 #ifdef SQLITE_TEST
63637 SQLITE_API int sqlite3_search_count = 0;
63638 #endif
63639 
63640 /*
63641 ** When this global variable is positive, it gets decremented once before
63642 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
63643 ** field of the sqlite3 structure is set in order to simulate an interrupt.
63644 **
63645 ** This facility is used for testing purposes only.  It does not function
63646 ** in an ordinary build.
63647 */
63648 #ifdef SQLITE_TEST
63649 SQLITE_API int sqlite3_interrupt_count = 0;
63650 #endif
63651 
63652 /*
63653 ** The next global variable is incremented each type the OP_Sort opcode
63654 ** is executed.  The test procedures use this information to make sure that
63655 ** sorting is occurring or not occurring at appropriate times.   This variable
63656 ** has no function other than to help verify the correct operation of the
63657 ** library.
63658 */
63659 #ifdef SQLITE_TEST
63660 SQLITE_API int sqlite3_sort_count = 0;
63661 #endif
63662 
63663 /*
63664 ** The next global variable records the size of the largest MEM_Blob
63665 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
63666 ** use this information to make sure that the zero-blob functionality
63667 ** is working correctly.   This variable has no function other than to
63668 ** help verify the correct operation of the library.
63669 */
63670 #ifdef SQLITE_TEST
63671 SQLITE_API int sqlite3_max_blobsize = 0;
63672 static void updateMaxBlobsize(Mem *p){
63673   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
63674     sqlite3_max_blobsize = p->n;
63675   }
63676 }
63677 #endif
63678 
63679 /*
63680 ** The next global variable is incremented each type the OP_Found opcode
63681 ** is executed. This is used to test whether or not the foreign key
63682 ** operation implemented using OP_FkIsZero is working. This variable
63683 ** has no function other than to help verify the correct operation of the
63684 ** library.
63685 */
63686 #ifdef SQLITE_TEST
63687 SQLITE_API int sqlite3_found_count = 0;
63688 #endif
63689 
63690 /*
63691 ** Test a register to see if it exceeds the current maximum blob size.
63692 ** If it does, record the new maximum blob size.
63693 */
63694 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
63695 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
63696 #else
63697 # define UPDATE_MAX_BLOBSIZE(P)
63698 #endif
63699 
63700 /*
63701 ** Convert the given register into a string if it isn't one
63702 ** already. Return non-zero if a malloc() fails.
63703 */
63704 #define Stringify(P, enc) \
63705    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
63706      { goto no_mem; }
63707 
63708 /*
63709 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
63710 ** a pointer to a dynamically allocated string where some other entity
63711 ** is responsible for deallocating that string.  Because the register
63712 ** does not control the string, it might be deleted without the register
63713 ** knowing it.
63714 **
63715 ** This routine converts an ephemeral string into a dynamically allocated
63716 ** string that the register itself controls.  In other words, it
63717 ** converts an MEM_Ephem string into an MEM_Dyn string.
63718 */
63719 #define Deephemeralize(P) \
63720    if( ((P)->flags&MEM_Ephem)!=0 \
63721        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
63722 
63723 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
63724 # define isSorter(x) ((x)->pSorter!=0)
63725 
63726 /*
63727 ** Argument pMem points at a register that will be passed to a
63728 ** user-defined function or returned to the user as the result of a query.
63729 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
63730 ** routines.
63731 */
63732 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
63733   int flags = pMem->flags;
63734   if( flags & MEM_Null ){
63735     pMem->type = SQLITE_NULL;
63736   }
63737   else if( flags & MEM_Int ){
63738     pMem->type = SQLITE_INTEGER;
63739   }
63740   else if( flags & MEM_Real ){
63741     pMem->type = SQLITE_FLOAT;
63742   }
63743   else if( flags & MEM_Str ){
63744     pMem->type = SQLITE_TEXT;
63745   }else{
63746     pMem->type = SQLITE_BLOB;
63747   }
63748 }
63749 
63750 /*
63751 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
63752 ** if we run out of memory.
63753 */
63754 static VdbeCursor *allocateCursor(
63755   Vdbe *p,              /* The virtual machine */
63756   int iCur,             /* Index of the new VdbeCursor */
63757   int nField,           /* Number of fields in the table or index */
63758   int iDb,              /* Database the cursor belongs to, or -1 */
63759   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
63760 ){
63761   /* Find the memory cell that will be used to store the blob of memory
63762   ** required for this VdbeCursor structure. It is convenient to use a
63763   ** vdbe memory cell to manage the memory allocation required for a
63764   ** VdbeCursor structure for the following reasons:
63765   **
63766   **   * Sometimes cursor numbers are used for a couple of different
63767   **     purposes in a vdbe program. The different uses might require
63768   **     different sized allocations. Memory cells provide growable
63769   **     allocations.
63770   **
63771   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
63772   **     be freed lazily via the sqlite3_release_memory() API. This
63773   **     minimizes the number of malloc calls made by the system.
63774   **
63775   ** Memory cells for cursors are allocated at the top of the address
63776   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
63777   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
63778   */
63779   Mem *pMem = &p->aMem[p->nMem-iCur];
63780 
63781   int nByte;
63782   VdbeCursor *pCx = 0;
63783   nByte =
63784       ROUND8(sizeof(VdbeCursor)) +
63785       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
63786       2*nField*sizeof(u32);
63787 
63788   assert( iCur<p->nCursor );
63789   if( p->apCsr[iCur] ){
63790     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
63791     p->apCsr[iCur] = 0;
63792   }
63793   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
63794     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
63795     memset(pCx, 0, sizeof(VdbeCursor));
63796     pCx->iDb = iDb;
63797     pCx->nField = nField;
63798     if( nField ){
63799       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
63800     }
63801     if( isBtreeCursor ){
63802       pCx->pCursor = (BtCursor*)
63803           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
63804       sqlite3BtreeCursorZero(pCx->pCursor);
63805     }
63806   }
63807   return pCx;
63808 }
63809 
63810 /*
63811 ** Try to convert a value into a numeric representation if we can
63812 ** do so without loss of information.  In other words, if the string
63813 ** looks like a number, convert it into a number.  If it does not
63814 ** look like a number, leave it alone.
63815 */
63816 static void applyNumericAffinity(Mem *pRec){
63817   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
63818     double rValue;
63819     i64 iValue;
63820     u8 enc = pRec->enc;
63821     if( (pRec->flags&MEM_Str)==0 ) return;
63822     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
63823     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
63824       pRec->u.i = iValue;
63825       pRec->flags |= MEM_Int;
63826     }else{
63827       pRec->r = rValue;
63828       pRec->flags |= MEM_Real;
63829     }
63830   }
63831 }
63832 
63833 /*
63834 ** Processing is determine by the affinity parameter:
63835 **
63836 ** SQLITE_AFF_INTEGER:
63837 ** SQLITE_AFF_REAL:
63838 ** SQLITE_AFF_NUMERIC:
63839 **    Try to convert pRec to an integer representation or a
63840 **    floating-point representation if an integer representation
63841 **    is not possible.  Note that the integer representation is
63842 **    always preferred, even if the affinity is REAL, because
63843 **    an integer representation is more space efficient on disk.
63844 **
63845 ** SQLITE_AFF_TEXT:
63846 **    Convert pRec to a text representation.
63847 **
63848 ** SQLITE_AFF_NONE:
63849 **    No-op.  pRec is unchanged.
63850 */
63851 static void applyAffinity(
63852   Mem *pRec,          /* The value to apply affinity to */
63853   char affinity,      /* The affinity to be applied */
63854   u8 enc              /* Use this text encoding */
63855 ){
63856   if( affinity==SQLITE_AFF_TEXT ){
63857     /* Only attempt the conversion to TEXT if there is an integer or real
63858     ** representation (blob and NULL do not get converted) but no string
63859     ** representation.
63860     */
63861     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
63862       sqlite3VdbeMemStringify(pRec, enc);
63863     }
63864     pRec->flags &= ~(MEM_Real|MEM_Int);
63865   }else if( affinity!=SQLITE_AFF_NONE ){
63866     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
63867              || affinity==SQLITE_AFF_NUMERIC );
63868     applyNumericAffinity(pRec);
63869     if( pRec->flags & MEM_Real ){
63870       sqlite3VdbeIntegerAffinity(pRec);
63871     }
63872   }
63873 }
63874 
63875 /*
63876 ** Try to convert the type of a function argument or a result column
63877 ** into a numeric representation.  Use either INTEGER or REAL whichever
63878 ** is appropriate.  But only do the conversion if it is possible without
63879 ** loss of information and return the revised type of the argument.
63880 */
63881 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
63882   Mem *pMem = (Mem*)pVal;
63883   if( pMem->type==SQLITE_TEXT ){
63884     applyNumericAffinity(pMem);
63885     sqlite3VdbeMemStoreType(pMem);
63886   }
63887   return pMem->type;
63888 }
63889 
63890 /*
63891 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
63892 ** not the internal Mem* type.
63893 */
63894 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
63895   sqlite3_value *pVal,
63896   u8 affinity,
63897   u8 enc
63898 ){
63899   applyAffinity((Mem *)pVal, affinity, enc);
63900 }
63901 
63902 #ifdef SQLITE_DEBUG
63903 /*
63904 ** Write a nice string representation of the contents of cell pMem
63905 ** into buffer zBuf, length nBuf.
63906 */
63907 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
63908   char *zCsr = zBuf;
63909   int f = pMem->flags;
63910 
63911   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
63912 
63913   if( f&MEM_Blob ){
63914     int i;
63915     char c;
63916     if( f & MEM_Dyn ){
63917       c = 'z';
63918       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63919     }else if( f & MEM_Static ){
63920       c = 't';
63921       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63922     }else if( f & MEM_Ephem ){
63923       c = 'e';
63924       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63925     }else{
63926       c = 's';
63927     }
63928 
63929     sqlite3_snprintf(100, zCsr, "%c", c);
63930     zCsr += sqlite3Strlen30(zCsr);
63931     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
63932     zCsr += sqlite3Strlen30(zCsr);
63933     for(i=0; i<16 && i<pMem->n; i++){
63934       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
63935       zCsr += sqlite3Strlen30(zCsr);
63936     }
63937     for(i=0; i<16 && i<pMem->n; i++){
63938       char z = pMem->z[i];
63939       if( z<32 || z>126 ) *zCsr++ = '.';
63940       else *zCsr++ = z;
63941     }
63942 
63943     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
63944     zCsr += sqlite3Strlen30(zCsr);
63945     if( f & MEM_Zero ){
63946       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
63947       zCsr += sqlite3Strlen30(zCsr);
63948     }
63949     *zCsr = '\0';
63950   }else if( f & MEM_Str ){
63951     int j, k;
63952     zBuf[0] = ' ';
63953     if( f & MEM_Dyn ){
63954       zBuf[1] = 'z';
63955       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63956     }else if( f & MEM_Static ){
63957       zBuf[1] = 't';
63958       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63959     }else if( f & MEM_Ephem ){
63960       zBuf[1] = 'e';
63961       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63962     }else{
63963       zBuf[1] = 's';
63964     }
63965     k = 2;
63966     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
63967     k += sqlite3Strlen30(&zBuf[k]);
63968     zBuf[k++] = '[';
63969     for(j=0; j<15 && j<pMem->n; j++){
63970       u8 c = pMem->z[j];
63971       if( c>=0x20 && c<0x7f ){
63972         zBuf[k++] = c;
63973       }else{
63974         zBuf[k++] = '.';
63975       }
63976     }
63977     zBuf[k++] = ']';
63978     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
63979     k += sqlite3Strlen30(&zBuf[k]);
63980     zBuf[k++] = 0;
63981   }
63982 }
63983 #endif
63984 
63985 #ifdef SQLITE_DEBUG
63986 /*
63987 ** Print the value of a register for tracing purposes:
63988 */
63989 static void memTracePrint(FILE *out, Mem *p){
63990   if( p->flags & MEM_Invalid ){
63991     fprintf(out, " undefined");
63992   }else if( p->flags & MEM_Null ){
63993     fprintf(out, " NULL");
63994   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
63995     fprintf(out, " si:%lld", p->u.i);
63996   }else if( p->flags & MEM_Int ){
63997     fprintf(out, " i:%lld", p->u.i);
63998 #ifndef SQLITE_OMIT_FLOATING_POINT
63999   }else if( p->flags & MEM_Real ){
64000     fprintf(out, " r:%g", p->r);
64001 #endif
64002   }else if( p->flags & MEM_RowSet ){
64003     fprintf(out, " (rowset)");
64004   }else{
64005     char zBuf[200];
64006     sqlite3VdbeMemPrettyPrint(p, zBuf);
64007     fprintf(out, " ");
64008     fprintf(out, "%s", zBuf);
64009   }
64010 }
64011 static void registerTrace(FILE *out, int iReg, Mem *p){
64012   fprintf(out, "REG[%d] = ", iReg);
64013   memTracePrint(out, p);
64014   fprintf(out, "\n");
64015 }
64016 #endif
64017 
64018 #ifdef SQLITE_DEBUG
64019 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
64020 #else
64021 #  define REGISTER_TRACE(R,M)
64022 #endif
64023 
64024 
64025 #ifdef VDBE_PROFILE
64026 
64027 /*
64028 ** hwtime.h contains inline assembler code for implementing
64029 ** high-performance timing routines.
64030 */
64031 /************** Include hwtime.h in the middle of vdbe.c *********************/
64032 /************** Begin file hwtime.h ******************************************/
64033 /*
64034 ** 2008 May 27
64035 **
64036 ** The author disclaims copyright to this source code.  In place of
64037 ** a legal notice, here is a blessing:
64038 **
64039 **    May you do good and not evil.
64040 **    May you find forgiveness for yourself and forgive others.
64041 **    May you share freely, never taking more than you give.
64042 **
64043 ******************************************************************************
64044 **
64045 ** This file contains inline asm code for retrieving "high-performance"
64046 ** counters for x86 class CPUs.
64047 */
64048 #ifndef _HWTIME_H_
64049 #define _HWTIME_H_
64050 
64051 /*
64052 ** The following routine only works on pentium-class (or newer) processors.
64053 ** It uses the RDTSC opcode to read the cycle count value out of the
64054 ** processor and returns that value.  This can be used for high-res
64055 ** profiling.
64056 */
64057 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
64058       (defined(i386) || defined(__i386__) || defined(_M_IX86))
64059 
64060   #if defined(__GNUC__)
64061 
64062   __inline__ sqlite_uint64 sqlite3Hwtime(void){
64063      unsigned int lo, hi;
64064      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
64065      return (sqlite_uint64)hi << 32 | lo;
64066   }
64067 
64068   #elif defined(_MSC_VER)
64069 
64070   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
64071      __asm {
64072         rdtsc
64073         ret       ; return value at EDX:EAX
64074      }
64075   }
64076 
64077   #endif
64078 
64079 #elif (defined(__GNUC__) && defined(__x86_64__))
64080 
64081   __inline__ sqlite_uint64 sqlite3Hwtime(void){
64082       unsigned long val;
64083       __asm__ __volatile__ ("rdtsc" : "=A" (val));
64084       return val;
64085   }
64086 
64087 #elif (defined(__GNUC__) && defined(__ppc__))
64088 
64089   __inline__ sqlite_uint64 sqlite3Hwtime(void){
64090       unsigned long long retval;
64091       unsigned long junk;
64092       __asm__ __volatile__ ("\n\
64093           1:      mftbu   %1\n\
64094                   mftb    %L0\n\
64095                   mftbu   %0\n\
64096                   cmpw    %0,%1\n\
64097                   bne     1b"
64098                   : "=r" (retval), "=r" (junk));
64099       return retval;
64100   }
64101 
64102 #else
64103 
64104   #error Need implementation of sqlite3Hwtime() for your platform.
64105 
64106   /*
64107   ** To compile without implementing sqlite3Hwtime() for your platform,
64108   ** you can remove the above #error and use the following
64109   ** stub function.  You will lose timing support for many
64110   ** of the debugging and testing utilities, but it should at
64111   ** least compile and run.
64112   */
64113 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
64114 
64115 #endif
64116 
64117 #endif /* !defined(_HWTIME_H_) */
64118 
64119 /************** End of hwtime.h **********************************************/
64120 /************** Continuing where we left off in vdbe.c ***********************/
64121 
64122 #endif
64123 
64124 /*
64125 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
64126 ** sqlite3_interrupt() routine has been called.  If it has been, then
64127 ** processing of the VDBE program is interrupted.
64128 **
64129 ** This macro added to every instruction that does a jump in order to
64130 ** implement a loop.  This test used to be on every single instruction,
64131 ** but that meant we more testing than we needed.  By only testing the
64132 ** flag on jump instructions, we get a (small) speed improvement.
64133 */
64134 #define CHECK_FOR_INTERRUPT \
64135    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
64136 
64137 
64138 #ifndef NDEBUG
64139 /*
64140 ** This function is only called from within an assert() expression. It
64141 ** checks that the sqlite3.nTransaction variable is correctly set to
64142 ** the number of non-transaction savepoints currently in the
64143 ** linked list starting at sqlite3.pSavepoint.
64144 **
64145 ** Usage:
64146 **
64147 **     assert( checkSavepointCount(db) );
64148 */
64149 static int checkSavepointCount(sqlite3 *db){
64150   int n = 0;
64151   Savepoint *p;
64152   for(p=db->pSavepoint; p; p=p->pNext) n++;
64153   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
64154   return 1;
64155 }
64156 #endif
64157 
64158 /*
64159 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
64160 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
64161 ** in memory obtained from sqlite3DbMalloc).
64162 */
64163 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
64164   sqlite3 *db = p->db;
64165   sqlite3DbFree(db, p->zErrMsg);
64166   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
64167   sqlite3_free(pVtab->zErrMsg);
64168   pVtab->zErrMsg = 0;
64169 }
64170 
64171 
64172 /*
64173 ** Execute as much of a VDBE program as we can then return.
64174 **
64175 ** sqlite3VdbeMakeReady() must be called before this routine in order to
64176 ** close the program with a final OP_Halt and to set up the callbacks
64177 ** and the error message pointer.
64178 **
64179 ** Whenever a row or result data is available, this routine will either
64180 ** invoke the result callback (if there is one) or return with
64181 ** SQLITE_ROW.
64182 **
64183 ** If an attempt is made to open a locked database, then this routine
64184 ** will either invoke the busy callback (if there is one) or it will
64185 ** return SQLITE_BUSY.
64186 **
64187 ** If an error occurs, an error message is written to memory obtained
64188 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
64189 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
64190 **
64191 ** If the callback ever returns non-zero, then the program exits
64192 ** immediately.  There will be no error message but the p->rc field is
64193 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
64194 **
64195 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
64196 ** routine to return SQLITE_ERROR.
64197 **
64198 ** Other fatal errors return SQLITE_ERROR.
64199 **
64200 ** After this routine has finished, sqlite3VdbeFinalize() should be
64201 ** used to clean up the mess that was left behind.
64202 */
64203 SQLITE_PRIVATE int sqlite3VdbeExec(
64204   Vdbe *p                    /* The VDBE */
64205 ){
64206   int pc=0;                  /* The program counter */
64207   Op *aOp = p->aOp;          /* Copy of p->aOp */
64208   Op *pOp;                   /* Current operation */
64209   int rc = SQLITE_OK;        /* Value to return */
64210   sqlite3 *db = p->db;       /* The database */
64211   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64212   u8 encoding = ENC(db);     /* The database encoding */
64213 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64214   int checkProgress;         /* True if progress callbacks are enabled */
64215   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64216 #endif
64217   Mem *aMem = p->aMem;       /* Copy of p->aMem */
64218   Mem *pIn1 = 0;             /* 1st input operand */
64219   Mem *pIn2 = 0;             /* 2nd input operand */
64220   Mem *pIn3 = 0;             /* 3rd input operand */
64221   Mem *pOut = 0;             /* Output operand */
64222   int iCompare = 0;          /* Result of last OP_Compare operation */
64223   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
64224   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
64225 #ifdef VDBE_PROFILE
64226   u64 start;                 /* CPU clock count at start of opcode */
64227   int origPc;                /* Program counter at start of opcode */
64228 #endif
64229   /********************************************************************
64230   ** Automatically generated code
64231   **
64232   ** The following union is automatically generated by the
64233   ** vdbe-compress.tcl script.  The purpose of this union is to
64234   ** reduce the amount of stack space required by this function.
64235   ** See comments in the vdbe-compress.tcl script for details.
64236   */
64237   union vdbeExecUnion {
64238     struct OP_Yield_stack_vars {
64239       int pcDest;
64240     } aa;
64241     struct OP_Null_stack_vars {
64242       int cnt;
64243       u16 nullFlag;
64244     } ab;
64245     struct OP_Variable_stack_vars {
64246       Mem *pVar;       /* Value being transferred */
64247     } ac;
64248     struct OP_Move_stack_vars {
64249       char *zMalloc;   /* Holding variable for allocated memory */
64250       int n;           /* Number of registers left to copy */
64251       int p1;          /* Register to copy from */
64252       int p2;          /* Register to copy to */
64253     } ad;
64254     struct OP_Copy_stack_vars {
64255       int n;
64256     } ae;
64257     struct OP_ResultRow_stack_vars {
64258       Mem *pMem;
64259       int i;
64260     } af;
64261     struct OP_Concat_stack_vars {
64262       i64 nByte;
64263     } ag;
64264     struct OP_Remainder_stack_vars {
64265       char bIntint;   /* Started out as two integer operands */
64266       int flags;      /* Combined MEM_* flags from both inputs */
64267       i64 iA;         /* Integer value of left operand */
64268       i64 iB;         /* Integer value of right operand */
64269       double rA;      /* Real value of left operand */
64270       double rB;      /* Real value of right operand */
64271     } ah;
64272     struct OP_Function_stack_vars {
64273       int i;
64274       Mem *pArg;
64275       sqlite3_context ctx;
64276       sqlite3_value **apVal;
64277       int n;
64278     } ai;
64279     struct OP_ShiftRight_stack_vars {
64280       i64 iA;
64281       u64 uA;
64282       i64 iB;
64283       u8 op;
64284     } aj;
64285     struct OP_Ge_stack_vars {
64286       int res;            /* Result of the comparison of pIn1 against pIn3 */
64287       char affinity;      /* Affinity to use for comparison */
64288       u16 flags1;         /* Copy of initial value of pIn1->flags */
64289       u16 flags3;         /* Copy of initial value of pIn3->flags */
64290     } ak;
64291     struct OP_Compare_stack_vars {
64292       int n;
64293       int i;
64294       int p1;
64295       int p2;
64296       const KeyInfo *pKeyInfo;
64297       int idx;
64298       CollSeq *pColl;    /* Collating sequence to use on this term */
64299       int bRev;          /* True for DESCENDING sort order */
64300     } al;
64301     struct OP_Or_stack_vars {
64302       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64303       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64304     } am;
64305     struct OP_IfNot_stack_vars {
64306       int c;
64307     } an;
64308     struct OP_Column_stack_vars {
64309       u32 payloadSize;   /* Number of bytes in the record */
64310       i64 payloadSize64; /* Number of bytes in the record */
64311       int p1;            /* P1 value of the opcode */
64312       int p2;            /* column number to retrieve */
64313       VdbeCursor *pC;    /* The VDBE cursor */
64314       char *zRec;        /* Pointer to complete record-data */
64315       BtCursor *pCrsr;   /* The BTree cursor */
64316       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64317       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64318       int nField;        /* number of fields in the record */
64319       int len;           /* The length of the serialized data for the column */
64320       int i;             /* Loop counter */
64321       char *zData;       /* Part of the record being decoded */
64322       Mem *pDest;        /* Where to write the extracted value */
64323       Mem sMem;          /* For storing the record being decoded */
64324       u8 *zIdx;          /* Index into header */
64325       u8 *zEndHdr;       /* Pointer to first byte after the header */
64326       u32 offset;        /* Offset into the data */
64327       u32 szField;       /* Number of bytes in the content of a field */
64328       int szHdr;         /* Size of the header size field at start of record */
64329       int avail;         /* Number of bytes of available data */
64330       u32 t;             /* A type code from the record header */
64331       Mem *pReg;         /* PseudoTable input register */
64332     } ao;
64333     struct OP_Affinity_stack_vars {
64334       const char *zAffinity;   /* The affinity to be applied */
64335       char cAff;               /* A single character of affinity */
64336     } ap;
64337     struct OP_MakeRecord_stack_vars {
64338       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
64339       Mem *pRec;             /* The new record */
64340       u64 nData;             /* Number of bytes of data space */
64341       int nHdr;              /* Number of bytes of header space */
64342       i64 nByte;             /* Data space required for this record */
64343       int nZero;             /* Number of zero bytes at the end of the record */
64344       int nVarint;           /* Number of bytes in a varint */
64345       u32 serial_type;       /* Type field */
64346       Mem *pData0;           /* First field to be combined into the record */
64347       Mem *pLast;            /* Last field of the record */
64348       int nField;            /* Number of fields in the record */
64349       char *zAffinity;       /* The affinity string for the record */
64350       int file_format;       /* File format to use for encoding */
64351       int i;                 /* Space used in zNewRecord[] */
64352       int len;               /* Length of a field */
64353     } aq;
64354     struct OP_Count_stack_vars {
64355       i64 nEntry;
64356       BtCursor *pCrsr;
64357     } ar;
64358     struct OP_Savepoint_stack_vars {
64359       int p1;                         /* Value of P1 operand */
64360       char *zName;                    /* Name of savepoint */
64361       int nName;
64362       Savepoint *pNew;
64363       Savepoint *pSavepoint;
64364       Savepoint *pTmp;
64365       int iSavepoint;
64366       int ii;
64367     } as;
64368     struct OP_AutoCommit_stack_vars {
64369       int desiredAutoCommit;
64370       int iRollback;
64371       int turnOnAC;
64372     } at;
64373     struct OP_Transaction_stack_vars {
64374       Btree *pBt;
64375     } au;
64376     struct OP_ReadCookie_stack_vars {
64377       int iMeta;
64378       int iDb;
64379       int iCookie;
64380     } av;
64381     struct OP_SetCookie_stack_vars {
64382       Db *pDb;
64383     } aw;
64384     struct OP_VerifyCookie_stack_vars {
64385       int iMeta;
64386       int iGen;
64387       Btree *pBt;
64388     } ax;
64389     struct OP_OpenWrite_stack_vars {
64390       int nField;
64391       KeyInfo *pKeyInfo;
64392       int p2;
64393       int iDb;
64394       int wrFlag;
64395       Btree *pX;
64396       VdbeCursor *pCur;
64397       Db *pDb;
64398     } ay;
64399     struct OP_OpenEphemeral_stack_vars {
64400       VdbeCursor *pCx;
64401     } az;
64402     struct OP_SorterOpen_stack_vars {
64403       VdbeCursor *pCx;
64404     } ba;
64405     struct OP_OpenPseudo_stack_vars {
64406       VdbeCursor *pCx;
64407     } bb;
64408     struct OP_SeekGt_stack_vars {
64409       int res;
64410       int oc;
64411       VdbeCursor *pC;
64412       UnpackedRecord r;
64413       int nField;
64414       i64 iKey;      /* The rowid we are to seek to */
64415     } bc;
64416     struct OP_Seek_stack_vars {
64417       VdbeCursor *pC;
64418     } bd;
64419     struct OP_Found_stack_vars {
64420       int alreadyExists;
64421       VdbeCursor *pC;
64422       int res;
64423       char *pFree;
64424       UnpackedRecord *pIdxKey;
64425       UnpackedRecord r;
64426       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
64427     } be;
64428     struct OP_IsUnique_stack_vars {
64429       u16 ii;
64430       VdbeCursor *pCx;
64431       BtCursor *pCrsr;
64432       u16 nField;
64433       Mem *aMx;
64434       UnpackedRecord r;                  /* B-Tree index search key */
64435       i64 R;                             /* Rowid stored in register P3 */
64436     } bf;
64437     struct OP_NotExists_stack_vars {
64438       VdbeCursor *pC;
64439       BtCursor *pCrsr;
64440       int res;
64441       u64 iKey;
64442     } bg;
64443     struct OP_NewRowid_stack_vars {
64444       i64 v;                 /* The new rowid */
64445       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
64446       int res;               /* Result of an sqlite3BtreeLast() */
64447       int cnt;               /* Counter to limit the number of searches */
64448       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
64449       VdbeFrame *pFrame;     /* Root frame of VDBE */
64450     } bh;
64451     struct OP_InsertInt_stack_vars {
64452       Mem *pData;       /* MEM cell holding data for the record to be inserted */
64453       Mem *pKey;        /* MEM cell holding key  for the record */
64454       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
64455       VdbeCursor *pC;   /* Cursor to table into which insert is written */
64456       int nZero;        /* Number of zero-bytes to append */
64457       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
64458       const char *zDb;  /* database name - used by the update hook */
64459       const char *zTbl; /* Table name - used by the opdate hook */
64460       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
64461     } bi;
64462     struct OP_Delete_stack_vars {
64463       i64 iKey;
64464       VdbeCursor *pC;
64465     } bj;
64466     struct OP_SorterCompare_stack_vars {
64467       VdbeCursor *pC;
64468       int res;
64469     } bk;
64470     struct OP_SorterData_stack_vars {
64471       VdbeCursor *pC;
64472     } bl;
64473     struct OP_RowData_stack_vars {
64474       VdbeCursor *pC;
64475       BtCursor *pCrsr;
64476       u32 n;
64477       i64 n64;
64478     } bm;
64479     struct OP_Rowid_stack_vars {
64480       VdbeCursor *pC;
64481       i64 v;
64482       sqlite3_vtab *pVtab;
64483       const sqlite3_module *pModule;
64484     } bn;
64485     struct OP_NullRow_stack_vars {
64486       VdbeCursor *pC;
64487     } bo;
64488     struct OP_Last_stack_vars {
64489       VdbeCursor *pC;
64490       BtCursor *pCrsr;
64491       int res;
64492     } bp;
64493     struct OP_Rewind_stack_vars {
64494       VdbeCursor *pC;
64495       BtCursor *pCrsr;
64496       int res;
64497     } bq;
64498     struct OP_Next_stack_vars {
64499       VdbeCursor *pC;
64500       int res;
64501     } br;
64502     struct OP_IdxInsert_stack_vars {
64503       VdbeCursor *pC;
64504       BtCursor *pCrsr;
64505       int nKey;
64506       const char *zKey;
64507     } bs;
64508     struct OP_IdxDelete_stack_vars {
64509       VdbeCursor *pC;
64510       BtCursor *pCrsr;
64511       int res;
64512       UnpackedRecord r;
64513     } bt;
64514     struct OP_IdxRowid_stack_vars {
64515       BtCursor *pCrsr;
64516       VdbeCursor *pC;
64517       i64 rowid;
64518     } bu;
64519     struct OP_IdxGE_stack_vars {
64520       VdbeCursor *pC;
64521       int res;
64522       UnpackedRecord r;
64523     } bv;
64524     struct OP_Destroy_stack_vars {
64525       int iMoved;
64526       int iCnt;
64527       Vdbe *pVdbe;
64528       int iDb;
64529     } bw;
64530     struct OP_Clear_stack_vars {
64531       int nChange;
64532     } bx;
64533     struct OP_CreateTable_stack_vars {
64534       int pgno;
64535       int flags;
64536       Db *pDb;
64537     } by;
64538     struct OP_ParseSchema_stack_vars {
64539       int iDb;
64540       const char *zMaster;
64541       char *zSql;
64542       InitData initData;
64543     } bz;
64544     struct OP_IntegrityCk_stack_vars {
64545       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
64546       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
64547       int j;          /* Loop counter */
64548       int nErr;       /* Number of errors reported */
64549       char *z;        /* Text of the error report */
64550       Mem *pnErr;     /* Register keeping track of errors remaining */
64551     } ca;
64552     struct OP_RowSetRead_stack_vars {
64553       i64 val;
64554     } cb;
64555     struct OP_RowSetTest_stack_vars {
64556       int iSet;
64557       int exists;
64558     } cc;
64559     struct OP_Program_stack_vars {
64560       int nMem;               /* Number of memory registers for sub-program */
64561       int nByte;              /* Bytes of runtime space required for sub-program */
64562       Mem *pRt;               /* Register to allocate runtime space */
64563       Mem *pMem;              /* Used to iterate through memory cells */
64564       Mem *pEnd;              /* Last memory cell in new array */
64565       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
64566       SubProgram *pProgram;   /* Sub-program to execute */
64567       void *t;                /* Token identifying trigger */
64568     } cd;
64569     struct OP_Param_stack_vars {
64570       VdbeFrame *pFrame;
64571       Mem *pIn;
64572     } ce;
64573     struct OP_MemMax_stack_vars {
64574       Mem *pIn1;
64575       VdbeFrame *pFrame;
64576     } cf;
64577     struct OP_AggStep_stack_vars {
64578       int n;
64579       int i;
64580       Mem *pMem;
64581       Mem *pRec;
64582       sqlite3_context ctx;
64583       sqlite3_value **apVal;
64584     } cg;
64585     struct OP_AggFinal_stack_vars {
64586       Mem *pMem;
64587     } ch;
64588     struct OP_Checkpoint_stack_vars {
64589       int i;                          /* Loop counter */
64590       int aRes[3];                    /* Results */
64591       Mem *pMem;                      /* Write results here */
64592     } ci;
64593     struct OP_JournalMode_stack_vars {
64594       Btree *pBt;                     /* Btree to change journal mode of */
64595       Pager *pPager;                  /* Pager associated with pBt */
64596       int eNew;                       /* New journal mode */
64597       int eOld;                       /* The old journal mode */
64598 #ifndef SQLITE_OMIT_WAL
64599       const char *zFilename;          /* Name of database file for pPager */
64600 #endif
64601     } cj;
64602     struct OP_IncrVacuum_stack_vars {
64603       Btree *pBt;
64604     } ck;
64605     struct OP_VBegin_stack_vars {
64606       VTable *pVTab;
64607     } cl;
64608     struct OP_VOpen_stack_vars {
64609       VdbeCursor *pCur;
64610       sqlite3_vtab_cursor *pVtabCursor;
64611       sqlite3_vtab *pVtab;
64612       sqlite3_module *pModule;
64613     } cm;
64614     struct OP_VFilter_stack_vars {
64615       int nArg;
64616       int iQuery;
64617       const sqlite3_module *pModule;
64618       Mem *pQuery;
64619       Mem *pArgc;
64620       sqlite3_vtab_cursor *pVtabCursor;
64621       sqlite3_vtab *pVtab;
64622       VdbeCursor *pCur;
64623       int res;
64624       int i;
64625       Mem **apArg;
64626     } cn;
64627     struct OP_VColumn_stack_vars {
64628       sqlite3_vtab *pVtab;
64629       const sqlite3_module *pModule;
64630       Mem *pDest;
64631       sqlite3_context sContext;
64632     } co;
64633     struct OP_VNext_stack_vars {
64634       sqlite3_vtab *pVtab;
64635       const sqlite3_module *pModule;
64636       int res;
64637       VdbeCursor *pCur;
64638     } cp;
64639     struct OP_VRename_stack_vars {
64640       sqlite3_vtab *pVtab;
64641       Mem *pName;
64642     } cq;
64643     struct OP_VUpdate_stack_vars {
64644       sqlite3_vtab *pVtab;
64645       sqlite3_module *pModule;
64646       int nArg;
64647       int i;
64648       sqlite_int64 rowid;
64649       Mem **apArg;
64650       Mem *pX;
64651     } cr;
64652     struct OP_Trace_stack_vars {
64653       char *zTrace;
64654       char *z;
64655     } cs;
64656   } u;
64657   /* End automatically generated code
64658   ********************************************************************/
64659 
64660   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
64661   sqlite3VdbeEnter(p);
64662   if( p->rc==SQLITE_NOMEM ){
64663     /* This happens if a malloc() inside a call to sqlite3_column_text() or
64664     ** sqlite3_column_text16() failed.  */
64665     goto no_mem;
64666   }
64667   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
64668   p->rc = SQLITE_OK;
64669   assert( p->explain==0 );
64670   p->pResultSet = 0;
64671   db->busyHandler.nBusy = 0;
64672   CHECK_FOR_INTERRUPT;
64673   sqlite3VdbeIOTraceSql(p);
64674 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64675   checkProgress = db->xProgress!=0;
64676 #endif
64677 #ifdef SQLITE_DEBUG
64678   sqlite3BeginBenignMalloc();
64679   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
64680     int i;
64681     printf("VDBE Program Listing:\n");
64682     sqlite3VdbePrintSql(p);
64683     for(i=0; i<p->nOp; i++){
64684       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
64685     }
64686   }
64687   sqlite3EndBenignMalloc();
64688 #endif
64689   for(pc=p->pc; rc==SQLITE_OK; pc++){
64690     assert( pc>=0 && pc<p->nOp );
64691     if( db->mallocFailed ) goto no_mem;
64692 #ifdef VDBE_PROFILE
64693     origPc = pc;
64694     start = sqlite3Hwtime();
64695 #endif
64696     pOp = &aOp[pc];
64697 
64698     /* Only allow tracing if SQLITE_DEBUG is defined.
64699     */
64700 #ifdef SQLITE_DEBUG
64701     if( p->trace ){
64702       if( pc==0 ){
64703         printf("VDBE Execution Trace:\n");
64704         sqlite3VdbePrintSql(p);
64705       }
64706       sqlite3VdbePrintOp(p->trace, pc, pOp);
64707     }
64708 #endif
64709 
64710 
64711     /* Check to see if we need to simulate an interrupt.  This only happens
64712     ** if we have a special test build.
64713     */
64714 #ifdef SQLITE_TEST
64715     if( sqlite3_interrupt_count>0 ){
64716       sqlite3_interrupt_count--;
64717       if( sqlite3_interrupt_count==0 ){
64718         sqlite3_interrupt(db);
64719       }
64720     }
64721 #endif
64722 
64723 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64724     /* Call the progress callback if it is configured and the required number
64725     ** of VDBE ops have been executed (either since this invocation of
64726     ** sqlite3VdbeExec() or since last time the progress callback was called).
64727     ** If the progress callback returns non-zero, exit the virtual machine with
64728     ** a return code SQLITE_ABORT.
64729     */
64730     if( checkProgress ){
64731       if( db->nProgressOps==nProgressOps ){
64732         int prc;
64733         prc = db->xProgress(db->pProgressArg);
64734         if( prc!=0 ){
64735           rc = SQLITE_INTERRUPT;
64736           goto vdbe_error_halt;
64737         }
64738         nProgressOps = 0;
64739       }
64740       nProgressOps++;
64741     }
64742 #endif
64743 
64744     /* On any opcode with the "out2-prerelease" tag, free any
64745     ** external allocations out of mem[p2] and set mem[p2] to be
64746     ** an undefined integer.  Opcodes will either fill in the integer
64747     ** value or convert mem[p2] to a different type.
64748     */
64749     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
64750     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
64751       assert( pOp->p2>0 );
64752       assert( pOp->p2<=p->nMem );
64753       pOut = &aMem[pOp->p2];
64754       memAboutToChange(p, pOut);
64755       VdbeMemRelease(pOut);
64756       pOut->flags = MEM_Int;
64757     }
64758 
64759     /* Sanity checking on other operands */
64760 #ifdef SQLITE_DEBUG
64761     if( (pOp->opflags & OPFLG_IN1)!=0 ){
64762       assert( pOp->p1>0 );
64763       assert( pOp->p1<=p->nMem );
64764       assert( memIsValid(&aMem[pOp->p1]) );
64765       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
64766     }
64767     if( (pOp->opflags & OPFLG_IN2)!=0 ){
64768       assert( pOp->p2>0 );
64769       assert( pOp->p2<=p->nMem );
64770       assert( memIsValid(&aMem[pOp->p2]) );
64771       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
64772     }
64773     if( (pOp->opflags & OPFLG_IN3)!=0 ){
64774       assert( pOp->p3>0 );
64775       assert( pOp->p3<=p->nMem );
64776       assert( memIsValid(&aMem[pOp->p3]) );
64777       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
64778     }
64779     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
64780       assert( pOp->p2>0 );
64781       assert( pOp->p2<=p->nMem );
64782       memAboutToChange(p, &aMem[pOp->p2]);
64783     }
64784     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
64785       assert( pOp->p3>0 );
64786       assert( pOp->p3<=p->nMem );
64787       memAboutToChange(p, &aMem[pOp->p3]);
64788     }
64789 #endif
64790 
64791     switch( pOp->opcode ){
64792 
64793 /*****************************************************************************
64794 ** What follows is a massive switch statement where each case implements a
64795 ** separate instruction in the virtual machine.  If we follow the usual
64796 ** indentation conventions, each case should be indented by 6 spaces.  But
64797 ** that is a lot of wasted space on the left margin.  So the code within
64798 ** the switch statement will break with convention and be flush-left. Another
64799 ** big comment (similar to this one) will mark the point in the code where
64800 ** we transition back to normal indentation.
64801 **
64802 ** The formatting of each case is important.  The makefile for SQLite
64803 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
64804 ** file looking for lines that begin with "case OP_".  The opcodes.h files
64805 ** will be filled with #defines that give unique integer values to each
64806 ** opcode and the opcodes.c file is filled with an array of strings where
64807 ** each string is the symbolic name for the corresponding opcode.  If the
64808 ** case statement is followed by a comment of the form "/# same as ... #/"
64809 ** that comment is used to determine the particular value of the opcode.
64810 **
64811 ** Other keywords in the comment that follows each case are used to
64812 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
64813 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
64814 ** the mkopcodeh.awk script for additional information.
64815 **
64816 ** Documentation about VDBE opcodes is generated by scanning this file
64817 ** for lines of that contain "Opcode:".  That line and all subsequent
64818 ** comment lines are used in the generation of the opcode.html documentation
64819 ** file.
64820 **
64821 ** SUMMARY:
64822 **
64823 **     Formatting is important to scripts that scan this file.
64824 **     Do not deviate from the formatting style currently in use.
64825 **
64826 *****************************************************************************/
64827 
64828 /* Opcode:  Goto * P2 * * *
64829 **
64830 ** An unconditional jump to address P2.
64831 ** The next instruction executed will be
64832 ** the one at index P2 from the beginning of
64833 ** the program.
64834 */
64835 case OP_Goto: {             /* jump */
64836   CHECK_FOR_INTERRUPT;
64837   pc = pOp->p2 - 1;
64838   break;
64839 }
64840 
64841 /* Opcode:  Gosub P1 P2 * * *
64842 **
64843 ** Write the current address onto register P1
64844 ** and then jump to address P2.
64845 */
64846 case OP_Gosub: {            /* jump */
64847   assert( pOp->p1>0 && pOp->p1<=p->nMem );
64848   pIn1 = &aMem[pOp->p1];
64849   assert( (pIn1->flags & MEM_Dyn)==0 );
64850   memAboutToChange(p, pIn1);
64851   pIn1->flags = MEM_Int;
64852   pIn1->u.i = pc;
64853   REGISTER_TRACE(pOp->p1, pIn1);
64854   pc = pOp->p2 - 1;
64855   break;
64856 }
64857 
64858 /* Opcode:  Return P1 * * * *
64859 **
64860 ** Jump to the next instruction after the address in register P1.
64861 */
64862 case OP_Return: {           /* in1 */
64863   pIn1 = &aMem[pOp->p1];
64864   assert( pIn1->flags & MEM_Int );
64865   pc = (int)pIn1->u.i;
64866   break;
64867 }
64868 
64869 /* Opcode:  Yield P1 * * * *
64870 **
64871 ** Swap the program counter with the value in register P1.
64872 */
64873 case OP_Yield: {            /* in1 */
64874 #if 0  /* local variables moved into u.aa */
64875   int pcDest;
64876 #endif /* local variables moved into u.aa */
64877   pIn1 = &aMem[pOp->p1];
64878   assert( (pIn1->flags & MEM_Dyn)==0 );
64879   pIn1->flags = MEM_Int;
64880   u.aa.pcDest = (int)pIn1->u.i;
64881   pIn1->u.i = pc;
64882   REGISTER_TRACE(pOp->p1, pIn1);
64883   pc = u.aa.pcDest;
64884   break;
64885 }
64886 
64887 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
64888 **
64889 ** Check the value in register P3.  If it is NULL then Halt using
64890 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
64891 ** value in register P3 is not NULL, then this routine is a no-op.
64892 */
64893 case OP_HaltIfNull: {      /* in3 */
64894   pIn3 = &aMem[pOp->p3];
64895   if( (pIn3->flags & MEM_Null)==0 ) break;
64896   /* Fall through into OP_Halt */
64897 }
64898 
64899 /* Opcode:  Halt P1 P2 * P4 *
64900 **
64901 ** Exit immediately.  All open cursors, etc are closed
64902 ** automatically.
64903 **
64904 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
64905 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
64906 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
64907 ** whether or not to rollback the current transaction.  Do not rollback
64908 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
64909 ** then back out all changes that have occurred during this execution of the
64910 ** VDBE, but do not rollback the transaction.
64911 **
64912 ** If P4 is not null then it is an error message string.
64913 **
64914 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
64915 ** every program.  So a jump past the last instruction of the program
64916 ** is the same as executing Halt.
64917 */
64918 case OP_Halt: {
64919   if( pOp->p1==SQLITE_OK && p->pFrame ){
64920     /* Halt the sub-program. Return control to the parent frame. */
64921     VdbeFrame *pFrame = p->pFrame;
64922     p->pFrame = pFrame->pParent;
64923     p->nFrame--;
64924     sqlite3VdbeSetChanges(db, p->nChange);
64925     pc = sqlite3VdbeFrameRestore(pFrame);
64926     lastRowid = db->lastRowid;
64927     if( pOp->p2==OE_Ignore ){
64928       /* Instruction pc is the OP_Program that invoked the sub-program
64929       ** currently being halted. If the p2 instruction of this OP_Halt
64930       ** instruction is set to OE_Ignore, then the sub-program is throwing
64931       ** an IGNORE exception. In this case jump to the address specified
64932       ** as the p2 of the calling OP_Program.  */
64933       pc = p->aOp[pc].p2-1;
64934     }
64935     aOp = p->aOp;
64936     aMem = p->aMem;
64937     break;
64938   }
64939 
64940   p->rc = pOp->p1;
64941   p->errorAction = (u8)pOp->p2;
64942   p->pc = pc;
64943   if( pOp->p4.z ){
64944     assert( p->rc!=SQLITE_OK );
64945     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
64946     testcase( sqlite3GlobalConfig.xLog!=0 );
64947     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
64948   }else if( p->rc ){
64949     testcase( sqlite3GlobalConfig.xLog!=0 );
64950     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
64951   }
64952   rc = sqlite3VdbeHalt(p);
64953   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
64954   if( rc==SQLITE_BUSY ){
64955     p->rc = rc = SQLITE_BUSY;
64956   }else{
64957     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
64958     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
64959     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
64960   }
64961   goto vdbe_return;
64962 }
64963 
64964 /* Opcode: Integer P1 P2 * * *
64965 **
64966 ** The 32-bit integer value P1 is written into register P2.
64967 */
64968 case OP_Integer: {         /* out2-prerelease */
64969   pOut->u.i = pOp->p1;
64970   break;
64971 }
64972 
64973 /* Opcode: Int64 * P2 * P4 *
64974 **
64975 ** P4 is a pointer to a 64-bit integer value.
64976 ** Write that value into register P2.
64977 */
64978 case OP_Int64: {           /* out2-prerelease */
64979   assert( pOp->p4.pI64!=0 );
64980   pOut->u.i = *pOp->p4.pI64;
64981   break;
64982 }
64983 
64984 #ifndef SQLITE_OMIT_FLOATING_POINT
64985 /* Opcode: Real * P2 * P4 *
64986 **
64987 ** P4 is a pointer to a 64-bit floating point value.
64988 ** Write that value into register P2.
64989 */
64990 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
64991   pOut->flags = MEM_Real;
64992   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
64993   pOut->r = *pOp->p4.pReal;
64994   break;
64995 }
64996 #endif
64997 
64998 /* Opcode: String8 * P2 * P4 *
64999 **
65000 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
65001 ** into an OP_String before it is executed for the first time.
65002 */
65003 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
65004   assert( pOp->p4.z!=0 );
65005   pOp->opcode = OP_String;
65006   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
65007 
65008 #ifndef SQLITE_OMIT_UTF16
65009   if( encoding!=SQLITE_UTF8 ){
65010     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
65011     if( rc==SQLITE_TOOBIG ) goto too_big;
65012     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
65013     assert( pOut->zMalloc==pOut->z );
65014     assert( pOut->flags & MEM_Dyn );
65015     pOut->zMalloc = 0;
65016     pOut->flags |= MEM_Static;
65017     pOut->flags &= ~MEM_Dyn;
65018     if( pOp->p4type==P4_DYNAMIC ){
65019       sqlite3DbFree(db, pOp->p4.z);
65020     }
65021     pOp->p4type = P4_DYNAMIC;
65022     pOp->p4.z = pOut->z;
65023     pOp->p1 = pOut->n;
65024   }
65025 #endif
65026   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65027     goto too_big;
65028   }
65029   /* Fall through to the next case, OP_String */
65030 }
65031 
65032 /* Opcode: String P1 P2 * P4 *
65033 **
65034 ** The string value P4 of length P1 (bytes) is stored in register P2.
65035 */
65036 case OP_String: {          /* out2-prerelease */
65037   assert( pOp->p4.z!=0 );
65038   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65039   pOut->z = pOp->p4.z;
65040   pOut->n = pOp->p1;
65041   pOut->enc = encoding;
65042   UPDATE_MAX_BLOBSIZE(pOut);
65043   break;
65044 }
65045 
65046 /* Opcode: Null P1 P2 P3 * *
65047 **
65048 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
65049 ** NULL into register P3 and every register in between P2 and P3.  If P3
65050 ** is less than P2 (typically P3 is zero) then only register P2 is
65051 ** set to NULL.
65052 **
65053 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
65054 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
65055 ** OP_Ne or OP_Eq.
65056 */
65057 case OP_Null: {           /* out2-prerelease */
65058 #if 0  /* local variables moved into u.ab */
65059   int cnt;
65060   u16 nullFlag;
65061 #endif /* local variables moved into u.ab */
65062   u.ab.cnt = pOp->p3-pOp->p2;
65063   assert( pOp->p3<=p->nMem );
65064   pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
65065   while( u.ab.cnt>0 ){
65066     pOut++;
65067     memAboutToChange(p, pOut);
65068     VdbeMemRelease(pOut);
65069     pOut->flags = u.ab.nullFlag;
65070     u.ab.cnt--;
65071   }
65072   break;
65073 }
65074 
65075 
65076 /* Opcode: Blob P1 P2 * P4
65077 **
65078 ** P4 points to a blob of data P1 bytes long.  Store this
65079 ** blob in register P2.
65080 */
65081 case OP_Blob: {                /* out2-prerelease */
65082   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
65083   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
65084   pOut->enc = encoding;
65085   UPDATE_MAX_BLOBSIZE(pOut);
65086   break;
65087 }
65088 
65089 /* Opcode: Variable P1 P2 * P4 *
65090 **
65091 ** Transfer the values of bound parameter P1 into register P2
65092 **
65093 ** If the parameter is named, then its name appears in P4 and P3==1.
65094 ** The P4 value is used by sqlite3_bind_parameter_name().
65095 */
65096 case OP_Variable: {            /* out2-prerelease */
65097 #if 0  /* local variables moved into u.ac */
65098   Mem *pVar;       /* Value being transferred */
65099 #endif /* local variables moved into u.ac */
65100 
65101   assert( pOp->p1>0 && pOp->p1<=p->nVar );
65102   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
65103   u.ac.pVar = &p->aVar[pOp->p1 - 1];
65104   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
65105     goto too_big;
65106   }
65107   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
65108   UPDATE_MAX_BLOBSIZE(pOut);
65109   break;
65110 }
65111 
65112 /* Opcode: Move P1 P2 P3 * *
65113 **
65114 ** Move the values in register P1..P1+P3 over into
65115 ** registers P2..P2+P3.  Registers P1..P1+P3 are
65116 ** left holding a NULL.  It is an error for register ranges
65117 ** P1..P1+P3 and P2..P2+P3 to overlap.
65118 */
65119 case OP_Move: {
65120 #if 0  /* local variables moved into u.ad */
65121   char *zMalloc;   /* Holding variable for allocated memory */
65122   int n;           /* Number of registers left to copy */
65123   int p1;          /* Register to copy from */
65124   int p2;          /* Register to copy to */
65125 #endif /* local variables moved into u.ad */
65126 
65127   u.ad.n = pOp->p3 + 1;
65128   u.ad.p1 = pOp->p1;
65129   u.ad.p2 = pOp->p2;
65130   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
65131   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
65132 
65133   pIn1 = &aMem[u.ad.p1];
65134   pOut = &aMem[u.ad.p2];
65135   while( u.ad.n-- ){
65136     assert( pOut<=&aMem[p->nMem] );
65137     assert( pIn1<=&aMem[p->nMem] );
65138     assert( memIsValid(pIn1) );
65139     memAboutToChange(p, pOut);
65140     u.ad.zMalloc = pOut->zMalloc;
65141     pOut->zMalloc = 0;
65142     sqlite3VdbeMemMove(pOut, pIn1);
65143 #ifdef SQLITE_DEBUG
65144     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
65145       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
65146     }
65147 #endif
65148     pIn1->zMalloc = u.ad.zMalloc;
65149     REGISTER_TRACE(u.ad.p2++, pOut);
65150     pIn1++;
65151     pOut++;
65152   }
65153   break;
65154 }
65155 
65156 /* Opcode: Copy P1 P2 P3 * *
65157 **
65158 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
65159 **
65160 ** This instruction makes a deep copy of the value.  A duplicate
65161 ** is made of any string or blob constant.  See also OP_SCopy.
65162 */
65163 case OP_Copy: {
65164 #if 0  /* local variables moved into u.ae */
65165   int n;
65166 #endif /* local variables moved into u.ae */
65167 
65168   u.ae.n = pOp->p3;
65169   pIn1 = &aMem[pOp->p1];
65170   pOut = &aMem[pOp->p2];
65171   assert( pOut!=pIn1 );
65172   while( 1 ){
65173     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65174     Deephemeralize(pOut);
65175 #ifdef SQLITE_DEBUG
65176     pOut->pScopyFrom = 0;
65177 #endif
65178     REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
65179     if( (u.ae.n--)==0 ) break;
65180     pOut++;
65181     pIn1++;
65182   }
65183   break;
65184 }
65185 
65186 /* Opcode: SCopy P1 P2 * * *
65187 **
65188 ** Make a shallow copy of register P1 into register P2.
65189 **
65190 ** This instruction makes a shallow copy of the value.  If the value
65191 ** is a string or blob, then the copy is only a pointer to the
65192 ** original and hence if the original changes so will the copy.
65193 ** Worse, if the original is deallocated, the copy becomes invalid.
65194 ** Thus the program must guarantee that the original will not change
65195 ** during the lifetime of the copy.  Use OP_Copy to make a complete
65196 ** copy.
65197 */
65198 case OP_SCopy: {            /* in1, out2 */
65199   pIn1 = &aMem[pOp->p1];
65200   pOut = &aMem[pOp->p2];
65201   assert( pOut!=pIn1 );
65202   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65203 #ifdef SQLITE_DEBUG
65204   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65205 #endif
65206   REGISTER_TRACE(pOp->p2, pOut);
65207   break;
65208 }
65209 
65210 /* Opcode: ResultRow P1 P2 * * *
65211 **
65212 ** The registers P1 through P1+P2-1 contain a single row of
65213 ** results. This opcode causes the sqlite3_step() call to terminate
65214 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
65215 ** structure to provide access to the top P1 values as the result
65216 ** row.
65217 */
65218 case OP_ResultRow: {
65219 #if 0  /* local variables moved into u.af */
65220   Mem *pMem;
65221   int i;
65222 #endif /* local variables moved into u.af */
65223   assert( p->nResColumn==pOp->p2 );
65224   assert( pOp->p1>0 );
65225   assert( pOp->p1+pOp->p2<=p->nMem+1 );
65226 
65227   /* If this statement has violated immediate foreign key constraints, do
65228   ** not return the number of rows modified. And do not RELEASE the statement
65229   ** transaction. It needs to be rolled back.  */
65230   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
65231     assert( db->flags&SQLITE_CountRows );
65232     assert( p->usesStmtJournal );
65233     break;
65234   }
65235 
65236   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
65237   ** DML statements invoke this opcode to return the number of rows
65238   ** modified to the user. This is the only way that a VM that
65239   ** opens a statement transaction may invoke this opcode.
65240   **
65241   ** In case this is such a statement, close any statement transaction
65242   ** opened by this VM before returning control to the user. This is to
65243   ** ensure that statement-transactions are always nested, not overlapping.
65244   ** If the open statement-transaction is not closed here, then the user
65245   ** may step another VM that opens its own statement transaction. This
65246   ** may lead to overlapping statement transactions.
65247   **
65248   ** The statement transaction is never a top-level transaction.  Hence
65249   ** the RELEASE call below can never fail.
65250   */
65251   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
65252   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
65253   if( NEVER(rc!=SQLITE_OK) ){
65254     break;
65255   }
65256 
65257   /* Invalidate all ephemeral cursor row caches */
65258   p->cacheCtr = (p->cacheCtr + 2)|1;
65259 
65260   /* Make sure the results of the current row are \000 terminated
65261   ** and have an assigned type.  The results are de-ephemeralized as
65262   ** a side effect.
65263   */
65264   u.af.pMem = p->pResultSet = &aMem[pOp->p1];
65265   for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
65266     assert( memIsValid(&u.af.pMem[u.af.i]) );
65267     Deephemeralize(&u.af.pMem[u.af.i]);
65268     assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
65269             || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
65270     sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
65271     sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
65272     REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
65273   }
65274   if( db->mallocFailed ) goto no_mem;
65275 
65276   /* Return SQLITE_ROW
65277   */
65278   p->pc = pc + 1;
65279   rc = SQLITE_ROW;
65280   goto vdbe_return;
65281 }
65282 
65283 /* Opcode: Concat P1 P2 P3 * *
65284 **
65285 ** Add the text in register P1 onto the end of the text in
65286 ** register P2 and store the result in register P3.
65287 ** If either the P1 or P2 text are NULL then store NULL in P3.
65288 **
65289 **   P3 = P2 || P1
65290 **
65291 ** It is illegal for P1 and P3 to be the same register. Sometimes,
65292 ** if P3 is the same register as P2, the implementation is able
65293 ** to avoid a memcpy().
65294 */
65295 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
65296 #if 0  /* local variables moved into u.ag */
65297   i64 nByte;
65298 #endif /* local variables moved into u.ag */
65299 
65300   pIn1 = &aMem[pOp->p1];
65301   pIn2 = &aMem[pOp->p2];
65302   pOut = &aMem[pOp->p3];
65303   assert( pIn1!=pOut );
65304   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65305     sqlite3VdbeMemSetNull(pOut);
65306     break;
65307   }
65308   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
65309   Stringify(pIn1, encoding);
65310   Stringify(pIn2, encoding);
65311   u.ag.nByte = pIn1->n + pIn2->n;
65312   if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65313     goto too_big;
65314   }
65315   MemSetTypeFlag(pOut, MEM_Str);
65316   if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
65317     goto no_mem;
65318   }
65319   if( pOut!=pIn2 ){
65320     memcpy(pOut->z, pIn2->z, pIn2->n);
65321   }
65322   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
65323   pOut->z[u.ag.nByte] = 0;
65324   pOut->z[u.ag.nByte+1] = 0;
65325   pOut->flags |= MEM_Term;
65326   pOut->n = (int)u.ag.nByte;
65327   pOut->enc = encoding;
65328   UPDATE_MAX_BLOBSIZE(pOut);
65329   break;
65330 }
65331 
65332 /* Opcode: Add P1 P2 P3 * *
65333 **
65334 ** Add the value in register P1 to the value in register P2
65335 ** and store the result in register P3.
65336 ** If either input is NULL, the result is NULL.
65337 */
65338 /* Opcode: Multiply P1 P2 P3 * *
65339 **
65340 **
65341 ** Multiply the value in register P1 by the value in register P2
65342 ** and store the result in register P3.
65343 ** If either input is NULL, the result is NULL.
65344 */
65345 /* Opcode: Subtract P1 P2 P3 * *
65346 **
65347 ** Subtract the value in register P1 from the value in register P2
65348 ** and store the result in register P3.
65349 ** If either input is NULL, the result is NULL.
65350 */
65351 /* Opcode: Divide P1 P2 P3 * *
65352 **
65353 ** Divide the value in register P1 by the value in register P2
65354 ** and store the result in register P3 (P3=P2/P1). If the value in
65355 ** register P1 is zero, then the result is NULL. If either input is
65356 ** NULL, the result is NULL.
65357 */
65358 /* Opcode: Remainder P1 P2 P3 * *
65359 **
65360 ** Compute the remainder after integer division of the value in
65361 ** register P1 by the value in register P2 and store the result in P3.
65362 ** If the value in register P2 is zero the result is NULL.
65363 ** If either operand is NULL, the result is NULL.
65364 */
65365 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
65366 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
65367 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
65368 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
65369 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
65370 #if 0  /* local variables moved into u.ah */
65371   char bIntint;   /* Started out as two integer operands */
65372   int flags;      /* Combined MEM_* flags from both inputs */
65373   i64 iA;         /* Integer value of left operand */
65374   i64 iB;         /* Integer value of right operand */
65375   double rA;      /* Real value of left operand */
65376   double rB;      /* Real value of right operand */
65377 #endif /* local variables moved into u.ah */
65378 
65379   pIn1 = &aMem[pOp->p1];
65380   applyNumericAffinity(pIn1);
65381   pIn2 = &aMem[pOp->p2];
65382   applyNumericAffinity(pIn2);
65383   pOut = &aMem[pOp->p3];
65384   u.ah.flags = pIn1->flags | pIn2->flags;
65385   if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
65386   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
65387     u.ah.iA = pIn1->u.i;
65388     u.ah.iB = pIn2->u.i;
65389     u.ah.bIntint = 1;
65390     switch( pOp->opcode ){
65391       case OP_Add:       if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65392       case OP_Subtract:  if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65393       case OP_Multiply:  if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
65394       case OP_Divide: {
65395         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65396         if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
65397         u.ah.iB /= u.ah.iA;
65398         break;
65399       }
65400       default: {
65401         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65402         if( u.ah.iA==-1 ) u.ah.iA = 1;
65403         u.ah.iB %= u.ah.iA;
65404         break;
65405       }
65406     }
65407     pOut->u.i = u.ah.iB;
65408     MemSetTypeFlag(pOut, MEM_Int);
65409   }else{
65410     u.ah.bIntint = 0;
65411 fp_math:
65412     u.ah.rA = sqlite3VdbeRealValue(pIn1);
65413     u.ah.rB = sqlite3VdbeRealValue(pIn2);
65414     switch( pOp->opcode ){
65415       case OP_Add:         u.ah.rB += u.ah.rA;       break;
65416       case OP_Subtract:    u.ah.rB -= u.ah.rA;       break;
65417       case OP_Multiply:    u.ah.rB *= u.ah.rA;       break;
65418       case OP_Divide: {
65419         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
65420         if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
65421         u.ah.rB /= u.ah.rA;
65422         break;
65423       }
65424       default: {
65425         u.ah.iA = (i64)u.ah.rA;
65426         u.ah.iB = (i64)u.ah.rB;
65427         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
65428         if( u.ah.iA==-1 ) u.ah.iA = 1;
65429         u.ah.rB = (double)(u.ah.iB % u.ah.iA);
65430         break;
65431       }
65432     }
65433 #ifdef SQLITE_OMIT_FLOATING_POINT
65434     pOut->u.i = u.ah.rB;
65435     MemSetTypeFlag(pOut, MEM_Int);
65436 #else
65437     if( sqlite3IsNaN(u.ah.rB) ){
65438       goto arithmetic_result_is_null;
65439     }
65440     pOut->r = u.ah.rB;
65441     MemSetTypeFlag(pOut, MEM_Real);
65442     if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
65443       sqlite3VdbeIntegerAffinity(pOut);
65444     }
65445 #endif
65446   }
65447   break;
65448 
65449 arithmetic_result_is_null:
65450   sqlite3VdbeMemSetNull(pOut);
65451   break;
65452 }
65453 
65454 /* Opcode: CollSeq P1 * * P4
65455 **
65456 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
65457 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
65458 ** be returned. This is used by the built-in min(), max() and nullif()
65459 ** functions.
65460 **
65461 ** If P1 is not zero, then it is a register that a subsequent min() or
65462 ** max() aggregate will set to 1 if the current row is not the minimum or
65463 ** maximum.  The P1 register is initialized to 0 by this instruction.
65464 **
65465 ** The interface used by the implementation of the aforementioned functions
65466 ** to retrieve the collation sequence set by this opcode is not available
65467 ** publicly, only to user functions defined in func.c.
65468 */
65469 case OP_CollSeq: {
65470   assert( pOp->p4type==P4_COLLSEQ );
65471   if( pOp->p1 ){
65472     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
65473   }
65474   break;
65475 }
65476 
65477 /* Opcode: Function P1 P2 P3 P4 P5
65478 **
65479 ** Invoke a user function (P4 is a pointer to a Function structure that
65480 ** defines the function) with P5 arguments taken from register P2 and
65481 ** successors.  The result of the function is stored in register P3.
65482 ** Register P3 must not be one of the function inputs.
65483 **
65484 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
65485 ** function was determined to be constant at compile time. If the first
65486 ** argument was constant then bit 0 of P1 is set. This is used to determine
65487 ** whether meta data associated with a user function argument using the
65488 ** sqlite3_set_auxdata() API may be safely retained until the next
65489 ** invocation of this opcode.
65490 **
65491 ** See also: AggStep and AggFinal
65492 */
65493 case OP_Function: {
65494 #if 0  /* local variables moved into u.ai */
65495   int i;
65496   Mem *pArg;
65497   sqlite3_context ctx;
65498   sqlite3_value **apVal;
65499   int n;
65500 #endif /* local variables moved into u.ai */
65501 
65502   u.ai.n = pOp->p5;
65503   u.ai.apVal = p->apArg;
65504   assert( u.ai.apVal || u.ai.n==0 );
65505   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65506   pOut = &aMem[pOp->p3];
65507   memAboutToChange(p, pOut);
65508 
65509   assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
65510   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
65511   u.ai.pArg = &aMem[pOp->p2];
65512   for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
65513     assert( memIsValid(u.ai.pArg) );
65514     u.ai.apVal[u.ai.i] = u.ai.pArg;
65515     Deephemeralize(u.ai.pArg);
65516     sqlite3VdbeMemStoreType(u.ai.pArg);
65517     REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
65518   }
65519 
65520   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
65521   if( pOp->p4type==P4_FUNCDEF ){
65522     u.ai.ctx.pFunc = pOp->p4.pFunc;
65523     u.ai.ctx.pVdbeFunc = 0;
65524   }else{
65525     u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
65526     u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
65527   }
65528 
65529   u.ai.ctx.s.flags = MEM_Null;
65530   u.ai.ctx.s.db = db;
65531   u.ai.ctx.s.xDel = 0;
65532   u.ai.ctx.s.zMalloc = 0;
65533 
65534   /* The output cell may already have a buffer allocated. Move
65535   ** the pointer to u.ai.ctx.s so in case the user-function can use
65536   ** the already allocated buffer instead of allocating a new one.
65537   */
65538   sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
65539   MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
65540 
65541   u.ai.ctx.isError = 0;
65542   if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
65543     assert( pOp>aOp );
65544     assert( pOp[-1].p4type==P4_COLLSEQ );
65545     assert( pOp[-1].opcode==OP_CollSeq );
65546     u.ai.ctx.pColl = pOp[-1].p4.pColl;
65547   }
65548   db->lastRowid = lastRowid;
65549   (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
65550   lastRowid = db->lastRowid;
65551 
65552   /* If any auxiliary data functions have been called by this user function,
65553   ** immediately call the destructor for any non-static values.
65554   */
65555   if( u.ai.ctx.pVdbeFunc ){
65556     sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
65557     pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
65558     pOp->p4type = P4_VDBEFUNC;
65559   }
65560 
65561   if( db->mallocFailed ){
65562     /* Even though a malloc() has failed, the implementation of the
65563     ** user function may have called an sqlite3_result_XXX() function
65564     ** to return a value. The following call releases any resources
65565     ** associated with such a value.
65566     */
65567     sqlite3VdbeMemRelease(&u.ai.ctx.s);
65568     goto no_mem;
65569   }
65570 
65571   /* If the function returned an error, throw an exception */
65572   if( u.ai.ctx.isError ){
65573     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
65574     rc = u.ai.ctx.isError;
65575   }
65576 
65577   /* Copy the result of the function into register P3 */
65578   sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
65579   sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
65580   if( sqlite3VdbeMemTooBig(pOut) ){
65581     goto too_big;
65582   }
65583 
65584 #if 0
65585   /* The app-defined function has done something that as caused this
65586   ** statement to expire.  (Perhaps the function called sqlite3_exec()
65587   ** with a CREATE TABLE statement.)
65588   */
65589   if( p->expired ) rc = SQLITE_ABORT;
65590 #endif
65591 
65592   REGISTER_TRACE(pOp->p3, pOut);
65593   UPDATE_MAX_BLOBSIZE(pOut);
65594   break;
65595 }
65596 
65597 /* Opcode: BitAnd P1 P2 P3 * *
65598 **
65599 ** Take the bit-wise AND of the values in register P1 and P2 and
65600 ** store the result in register P3.
65601 ** If either input is NULL, the result is NULL.
65602 */
65603 /* Opcode: BitOr P1 P2 P3 * *
65604 **
65605 ** Take the bit-wise OR of the values in register P1 and P2 and
65606 ** store the result in register P3.
65607 ** If either input is NULL, the result is NULL.
65608 */
65609 /* Opcode: ShiftLeft P1 P2 P3 * *
65610 **
65611 ** Shift the integer value in register P2 to the left by the
65612 ** number of bits specified by the integer in register P1.
65613 ** Store the result in register P3.
65614 ** If either input is NULL, the result is NULL.
65615 */
65616 /* Opcode: ShiftRight P1 P2 P3 * *
65617 **
65618 ** Shift the integer value in register P2 to the right by the
65619 ** number of bits specified by the integer in register P1.
65620 ** Store the result in register P3.
65621 ** If either input is NULL, the result is NULL.
65622 */
65623 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
65624 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
65625 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
65626 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
65627 #if 0  /* local variables moved into u.aj */
65628   i64 iA;
65629   u64 uA;
65630   i64 iB;
65631   u8 op;
65632 #endif /* local variables moved into u.aj */
65633 
65634   pIn1 = &aMem[pOp->p1];
65635   pIn2 = &aMem[pOp->p2];
65636   pOut = &aMem[pOp->p3];
65637   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65638     sqlite3VdbeMemSetNull(pOut);
65639     break;
65640   }
65641   u.aj.iA = sqlite3VdbeIntValue(pIn2);
65642   u.aj.iB = sqlite3VdbeIntValue(pIn1);
65643   u.aj.op = pOp->opcode;
65644   if( u.aj.op==OP_BitAnd ){
65645     u.aj.iA &= u.aj.iB;
65646   }else if( u.aj.op==OP_BitOr ){
65647     u.aj.iA |= u.aj.iB;
65648   }else if( u.aj.iB!=0 ){
65649     assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
65650 
65651     /* If shifting by a negative amount, shift in the other direction */
65652     if( u.aj.iB<0 ){
65653       assert( OP_ShiftRight==OP_ShiftLeft+1 );
65654       u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
65655       u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
65656     }
65657 
65658     if( u.aj.iB>=64 ){
65659       u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
65660     }else{
65661       memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
65662       if( u.aj.op==OP_ShiftLeft ){
65663         u.aj.uA <<= u.aj.iB;
65664       }else{
65665         u.aj.uA >>= u.aj.iB;
65666         /* Sign-extend on a right shift of a negative number */
65667         if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
65668       }
65669       memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
65670     }
65671   }
65672   pOut->u.i = u.aj.iA;
65673   MemSetTypeFlag(pOut, MEM_Int);
65674   break;
65675 }
65676 
65677 /* Opcode: AddImm  P1 P2 * * *
65678 **
65679 ** Add the constant P2 to the value in register P1.
65680 ** The result is always an integer.
65681 **
65682 ** To force any register to be an integer, just add 0.
65683 */
65684 case OP_AddImm: {            /* in1 */
65685   pIn1 = &aMem[pOp->p1];
65686   memAboutToChange(p, pIn1);
65687   sqlite3VdbeMemIntegerify(pIn1);
65688   pIn1->u.i += pOp->p2;
65689   break;
65690 }
65691 
65692 /* Opcode: MustBeInt P1 P2 * * *
65693 **
65694 ** Force the value in register P1 to be an integer.  If the value
65695 ** in P1 is not an integer and cannot be converted into an integer
65696 ** without data loss, then jump immediately to P2, or if P2==0
65697 ** raise an SQLITE_MISMATCH exception.
65698 */
65699 case OP_MustBeInt: {            /* jump, in1 */
65700   pIn1 = &aMem[pOp->p1];
65701   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
65702   if( (pIn1->flags & MEM_Int)==0 ){
65703     if( pOp->p2==0 ){
65704       rc = SQLITE_MISMATCH;
65705       goto abort_due_to_error;
65706     }else{
65707       pc = pOp->p2 - 1;
65708     }
65709   }else{
65710     MemSetTypeFlag(pIn1, MEM_Int);
65711   }
65712   break;
65713 }
65714 
65715 #ifndef SQLITE_OMIT_FLOATING_POINT
65716 /* Opcode: RealAffinity P1 * * * *
65717 **
65718 ** If register P1 holds an integer convert it to a real value.
65719 **
65720 ** This opcode is used when extracting information from a column that
65721 ** has REAL affinity.  Such column values may still be stored as
65722 ** integers, for space efficiency, but after extraction we want them
65723 ** to have only a real value.
65724 */
65725 case OP_RealAffinity: {                  /* in1 */
65726   pIn1 = &aMem[pOp->p1];
65727   if( pIn1->flags & MEM_Int ){
65728     sqlite3VdbeMemRealify(pIn1);
65729   }
65730   break;
65731 }
65732 #endif
65733 
65734 #ifndef SQLITE_OMIT_CAST
65735 /* Opcode: ToText P1 * * * *
65736 **
65737 ** Force the value in register P1 to be text.
65738 ** If the value is numeric, convert it to a string using the
65739 ** equivalent of printf().  Blob values are unchanged and
65740 ** are afterwards simply interpreted as text.
65741 **
65742 ** A NULL value is not changed by this routine.  It remains NULL.
65743 */
65744 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
65745   pIn1 = &aMem[pOp->p1];
65746   memAboutToChange(p, pIn1);
65747   if( pIn1->flags & MEM_Null ) break;
65748   assert( MEM_Str==(MEM_Blob>>3) );
65749   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
65750   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65751   rc = ExpandBlob(pIn1);
65752   assert( pIn1->flags & MEM_Str || db->mallocFailed );
65753   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65754   UPDATE_MAX_BLOBSIZE(pIn1);
65755   break;
65756 }
65757 
65758 /* Opcode: ToBlob P1 * * * *
65759 **
65760 ** Force the value in register P1 to be a BLOB.
65761 ** If the value is numeric, convert it to a string first.
65762 ** Strings are simply reinterpreted as blobs with no change
65763 ** to the underlying data.
65764 **
65765 ** A NULL value is not changed by this routine.  It remains NULL.
65766 */
65767 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
65768   pIn1 = &aMem[pOp->p1];
65769   if( pIn1->flags & MEM_Null ) break;
65770   if( (pIn1->flags & MEM_Blob)==0 ){
65771     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65772     assert( pIn1->flags & MEM_Str || db->mallocFailed );
65773     MemSetTypeFlag(pIn1, MEM_Blob);
65774   }else{
65775     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
65776   }
65777   UPDATE_MAX_BLOBSIZE(pIn1);
65778   break;
65779 }
65780 
65781 /* Opcode: ToNumeric P1 * * * *
65782 **
65783 ** Force the value in register P1 to be numeric (either an
65784 ** integer or a floating-point number.)
65785 ** If the value is text or blob, try to convert it to an using the
65786 ** equivalent of atoi() or atof() and store 0 if no such conversion
65787 ** is possible.
65788 **
65789 ** A NULL value is not changed by this routine.  It remains NULL.
65790 */
65791 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
65792   pIn1 = &aMem[pOp->p1];
65793   sqlite3VdbeMemNumerify(pIn1);
65794   break;
65795 }
65796 #endif /* SQLITE_OMIT_CAST */
65797 
65798 /* Opcode: ToInt P1 * * * *
65799 **
65800 ** Force the value in register P1 to be an integer.  If
65801 ** The value is currently a real number, drop its fractional part.
65802 ** If the value is text or blob, try to convert it to an integer using the
65803 ** equivalent of atoi() and store 0 if no such conversion is possible.
65804 **
65805 ** A NULL value is not changed by this routine.  It remains NULL.
65806 */
65807 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
65808   pIn1 = &aMem[pOp->p1];
65809   if( (pIn1->flags & MEM_Null)==0 ){
65810     sqlite3VdbeMemIntegerify(pIn1);
65811   }
65812   break;
65813 }
65814 
65815 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
65816 /* Opcode: ToReal P1 * * * *
65817 **
65818 ** Force the value in register P1 to be a floating point number.
65819 ** If The value is currently an integer, convert it.
65820 ** If the value is text or blob, try to convert it to an integer using the
65821 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
65822 **
65823 ** A NULL value is not changed by this routine.  It remains NULL.
65824 */
65825 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
65826   pIn1 = &aMem[pOp->p1];
65827   memAboutToChange(p, pIn1);
65828   if( (pIn1->flags & MEM_Null)==0 ){
65829     sqlite3VdbeMemRealify(pIn1);
65830   }
65831   break;
65832 }
65833 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
65834 
65835 /* Opcode: Lt P1 P2 P3 P4 P5
65836 **
65837 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
65838 ** jump to address P2.
65839 **
65840 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
65841 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
65842 ** bit is clear then fall through if either operand is NULL.
65843 **
65844 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
65845 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
65846 ** to coerce both inputs according to this affinity before the
65847 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
65848 ** affinity is used. Note that the affinity conversions are stored
65849 ** back into the input registers P1 and P3.  So this opcode can cause
65850 ** persistent changes to registers P1 and P3.
65851 **
65852 ** Once any conversions have taken place, and neither value is NULL,
65853 ** the values are compared. If both values are blobs then memcmp() is
65854 ** used to determine the results of the comparison.  If both values
65855 ** are text, then the appropriate collating function specified in
65856 ** P4 is  used to do the comparison.  If P4 is not specified then
65857 ** memcmp() is used to compare text string.  If both values are
65858 ** numeric, then a numeric comparison is used. If the two values
65859 ** are of different types, then numbers are considered less than
65860 ** strings and strings are considered less than blobs.
65861 **
65862 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
65863 ** store a boolean result (either 0, or 1, or NULL) in register P2.
65864 **
65865 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
65866 ** equal to one another, provided that they do not have their MEM_Cleared
65867 ** bit set.
65868 */
65869 /* Opcode: Ne P1 P2 P3 P4 P5
65870 **
65871 ** This works just like the Lt opcode except that the jump is taken if
65872 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
65873 ** additional information.
65874 **
65875 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65876 ** true or false and is never NULL.  If both operands are NULL then the result
65877 ** of comparison is false.  If either operand is NULL then the result is true.
65878 ** If neither operand is NULL the result is the same as it would be if
65879 ** the SQLITE_NULLEQ flag were omitted from P5.
65880 */
65881 /* Opcode: Eq P1 P2 P3 P4 P5
65882 **
65883 ** This works just like the Lt opcode except that the jump is taken if
65884 ** the operands in registers P1 and P3 are equal.
65885 ** See the Lt opcode for additional information.
65886 **
65887 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65888 ** true or false and is never NULL.  If both operands are NULL then the result
65889 ** of comparison is true.  If either operand is NULL then the result is false.
65890 ** If neither operand is NULL the result is the same as it would be if
65891 ** the SQLITE_NULLEQ flag were omitted from P5.
65892 */
65893 /* Opcode: Le P1 P2 P3 P4 P5
65894 **
65895 ** This works just like the Lt opcode except that the jump is taken if
65896 ** the content of register P3 is less than or equal to the content of
65897 ** register P1.  See the Lt opcode for additional information.
65898 */
65899 /* Opcode: Gt P1 P2 P3 P4 P5
65900 **
65901 ** This works just like the Lt opcode except that the jump is taken if
65902 ** the content of register P3 is greater than the content of
65903 ** register P1.  See the Lt opcode for additional information.
65904 */
65905 /* Opcode: Ge P1 P2 P3 P4 P5
65906 **
65907 ** This works just like the Lt opcode except that the jump is taken if
65908 ** the content of register P3 is greater than or equal to the content of
65909 ** register P1.  See the Lt opcode for additional information.
65910 */
65911 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
65912 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
65913 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
65914 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
65915 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
65916 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
65917 #if 0  /* local variables moved into u.ak */
65918   int res;            /* Result of the comparison of pIn1 against pIn3 */
65919   char affinity;      /* Affinity to use for comparison */
65920   u16 flags1;         /* Copy of initial value of pIn1->flags */
65921   u16 flags3;         /* Copy of initial value of pIn3->flags */
65922 #endif /* local variables moved into u.ak */
65923 
65924   pIn1 = &aMem[pOp->p1];
65925   pIn3 = &aMem[pOp->p3];
65926   u.ak.flags1 = pIn1->flags;
65927   u.ak.flags3 = pIn3->flags;
65928   if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
65929     /* One or both operands are NULL */
65930     if( pOp->p5 & SQLITE_NULLEQ ){
65931       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
65932       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
65933       ** or not both operands are null.
65934       */
65935       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
65936       assert( (u.ak.flags1 & MEM_Cleared)==0 );
65937       if( (u.ak.flags1&MEM_Null)!=0
65938        && (u.ak.flags3&MEM_Null)!=0
65939        && (u.ak.flags3&MEM_Cleared)==0
65940       ){
65941         u.ak.res = 0;  /* Results are equal */
65942       }else{
65943         u.ak.res = 1;  /* Results are not equal */
65944       }
65945     }else{
65946       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
65947       ** then the result is always NULL.
65948       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
65949       */
65950       if( pOp->p5 & SQLITE_STOREP2 ){
65951         pOut = &aMem[pOp->p2];
65952         MemSetTypeFlag(pOut, MEM_Null);
65953         REGISTER_TRACE(pOp->p2, pOut);
65954       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
65955         pc = pOp->p2-1;
65956       }
65957       break;
65958     }
65959   }else{
65960     /* Neither operand is NULL.  Do a comparison. */
65961     u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
65962     if( u.ak.affinity ){
65963       applyAffinity(pIn1, u.ak.affinity, encoding);
65964       applyAffinity(pIn3, u.ak.affinity, encoding);
65965       if( db->mallocFailed ) goto no_mem;
65966     }
65967 
65968     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
65969     ExpandBlob(pIn1);
65970     ExpandBlob(pIn3);
65971     u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
65972   }
65973   switch( pOp->opcode ){
65974     case OP_Eq:    u.ak.res = u.ak.res==0;     break;
65975     case OP_Ne:    u.ak.res = u.ak.res!=0;     break;
65976     case OP_Lt:    u.ak.res = u.ak.res<0;      break;
65977     case OP_Le:    u.ak.res = u.ak.res<=0;     break;
65978     case OP_Gt:    u.ak.res = u.ak.res>0;      break;
65979     default:       u.ak.res = u.ak.res>=0;     break;
65980   }
65981 
65982   if( pOp->p5 & SQLITE_STOREP2 ){
65983     pOut = &aMem[pOp->p2];
65984     memAboutToChange(p, pOut);
65985     MemSetTypeFlag(pOut, MEM_Int);
65986     pOut->u.i = u.ak.res;
65987     REGISTER_TRACE(pOp->p2, pOut);
65988   }else if( u.ak.res ){
65989     pc = pOp->p2-1;
65990   }
65991 
65992   /* Undo any changes made by applyAffinity() to the input registers. */
65993   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
65994   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
65995   break;
65996 }
65997 
65998 /* Opcode: Permutation * * * P4 *
65999 **
66000 ** Set the permutation used by the OP_Compare operator to be the array
66001 ** of integers in P4.
66002 **
66003 ** The permutation is only valid until the next OP_Compare that has
66004 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
66005 ** occur immediately prior to the OP_Compare.
66006 */
66007 case OP_Permutation: {
66008   assert( pOp->p4type==P4_INTARRAY );
66009   assert( pOp->p4.ai );
66010   aPermute = pOp->p4.ai;
66011   break;
66012 }
66013 
66014 /* Opcode: Compare P1 P2 P3 P4 P5
66015 **
66016 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
66017 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
66018 ** the comparison for use by the next OP_Jump instruct.
66019 **
66020 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
66021 ** determined by the most recent OP_Permutation operator.  If the
66022 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
66023 ** order.
66024 **
66025 ** P4 is a KeyInfo structure that defines collating sequences and sort
66026 ** orders for the comparison.  The permutation applies to registers
66027 ** only.  The KeyInfo elements are used sequentially.
66028 **
66029 ** The comparison is a sort comparison, so NULLs compare equal,
66030 ** NULLs are less than numbers, numbers are less than strings,
66031 ** and strings are less than blobs.
66032 */
66033 case OP_Compare: {
66034 #if 0  /* local variables moved into u.al */
66035   int n;
66036   int i;
66037   int p1;
66038   int p2;
66039   const KeyInfo *pKeyInfo;
66040   int idx;
66041   CollSeq *pColl;    /* Collating sequence to use on this term */
66042   int bRev;          /* True for DESCENDING sort order */
66043 #endif /* local variables moved into u.al */
66044 
66045   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
66046   u.al.n = pOp->p3;
66047   u.al.pKeyInfo = pOp->p4.pKeyInfo;
66048   assert( u.al.n>0 );
66049   assert( u.al.pKeyInfo!=0 );
66050   u.al.p1 = pOp->p1;
66051   u.al.p2 = pOp->p2;
66052 #if SQLITE_DEBUG
66053   if( aPermute ){
66054     int k, mx = 0;
66055     for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
66056     assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
66057     assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
66058   }else{
66059     assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
66060     assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
66061   }
66062 #endif /* SQLITE_DEBUG */
66063   for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
66064     u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
66065     assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
66066     assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
66067     REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
66068     REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
66069     assert( u.al.i<u.al.pKeyInfo->nField );
66070     u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
66071     u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
66072     iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
66073     if( iCompare ){
66074       if( u.al.bRev ) iCompare = -iCompare;
66075       break;
66076     }
66077   }
66078   aPermute = 0;
66079   break;
66080 }
66081 
66082 /* Opcode: Jump P1 P2 P3 * *
66083 **
66084 ** Jump to the instruction at address P1, P2, or P3 depending on whether
66085 ** in the most recent OP_Compare instruction the P1 vector was less than
66086 ** equal to, or greater than the P2 vector, respectively.
66087 */
66088 case OP_Jump: {             /* jump */
66089   if( iCompare<0 ){
66090     pc = pOp->p1 - 1;
66091   }else if( iCompare==0 ){
66092     pc = pOp->p2 - 1;
66093   }else{
66094     pc = pOp->p3 - 1;
66095   }
66096   break;
66097 }
66098 
66099 /* Opcode: And P1 P2 P3 * *
66100 **
66101 ** Take the logical AND of the values in registers P1 and P2 and
66102 ** write the result into register P3.
66103 **
66104 ** If either P1 or P2 is 0 (false) then the result is 0 even if
66105 ** the other input is NULL.  A NULL and true or two NULLs give
66106 ** a NULL output.
66107 */
66108 /* Opcode: Or P1 P2 P3 * *
66109 **
66110 ** Take the logical OR of the values in register P1 and P2 and
66111 ** store the answer in register P3.
66112 **
66113 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
66114 ** even if the other input is NULL.  A NULL and false or two NULLs
66115 ** give a NULL output.
66116 */
66117 case OP_And:              /* same as TK_AND, in1, in2, out3 */
66118 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
66119 #if 0  /* local variables moved into u.am */
66120   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66121   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66122 #endif /* local variables moved into u.am */
66123 
66124   pIn1 = &aMem[pOp->p1];
66125   if( pIn1->flags & MEM_Null ){
66126     u.am.v1 = 2;
66127   }else{
66128     u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
66129   }
66130   pIn2 = &aMem[pOp->p2];
66131   if( pIn2->flags & MEM_Null ){
66132     u.am.v2 = 2;
66133   }else{
66134     u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
66135   }
66136   if( pOp->opcode==OP_And ){
66137     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
66138     u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
66139   }else{
66140     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
66141     u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
66142   }
66143   pOut = &aMem[pOp->p3];
66144   if( u.am.v1==2 ){
66145     MemSetTypeFlag(pOut, MEM_Null);
66146   }else{
66147     pOut->u.i = u.am.v1;
66148     MemSetTypeFlag(pOut, MEM_Int);
66149   }
66150   break;
66151 }
66152 
66153 /* Opcode: Not P1 P2 * * *
66154 **
66155 ** Interpret the value in register P1 as a boolean value.  Store the
66156 ** boolean complement in register P2.  If the value in register P1 is
66157 ** NULL, then a NULL is stored in P2.
66158 */
66159 case OP_Not: {                /* same as TK_NOT, in1, out2 */
66160   pIn1 = &aMem[pOp->p1];
66161   pOut = &aMem[pOp->p2];
66162   if( pIn1->flags & MEM_Null ){
66163     sqlite3VdbeMemSetNull(pOut);
66164   }else{
66165     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
66166   }
66167   break;
66168 }
66169 
66170 /* Opcode: BitNot P1 P2 * * *
66171 **
66172 ** Interpret the content of register P1 as an integer.  Store the
66173 ** ones-complement of the P1 value into register P2.  If P1 holds
66174 ** a NULL then store a NULL in P2.
66175 */
66176 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66177   pIn1 = &aMem[pOp->p1];
66178   pOut = &aMem[pOp->p2];
66179   if( pIn1->flags & MEM_Null ){
66180     sqlite3VdbeMemSetNull(pOut);
66181   }else{
66182     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
66183   }
66184   break;
66185 }
66186 
66187 /* Opcode: Once P1 P2 * * *
66188 **
66189 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
66190 ** set the flag and fall through to the next instruction.
66191 */
66192 case OP_Once: {             /* jump */
66193   assert( pOp->p1<p->nOnceFlag );
66194   if( p->aOnceFlag[pOp->p1] ){
66195     pc = pOp->p2-1;
66196   }else{
66197     p->aOnceFlag[pOp->p1] = 1;
66198   }
66199   break;
66200 }
66201 
66202 /* Opcode: If P1 P2 P3 * *
66203 **
66204 ** Jump to P2 if the value in register P1 is true.  The value
66205 ** is considered true if it is numeric and non-zero.  If the value
66206 ** in P1 is NULL then take the jump if P3 is non-zero.
66207 */
66208 /* Opcode: IfNot P1 P2 P3 * *
66209 **
66210 ** Jump to P2 if the value in register P1 is False.  The value
66211 ** is considered false if it has a numeric value of zero.  If the value
66212 ** in P1 is NULL then take the jump if P3 is zero.
66213 */
66214 case OP_If:                 /* jump, in1 */
66215 case OP_IfNot: {            /* jump, in1 */
66216 #if 0  /* local variables moved into u.an */
66217   int c;
66218 #endif /* local variables moved into u.an */
66219   pIn1 = &aMem[pOp->p1];
66220   if( pIn1->flags & MEM_Null ){
66221     u.an.c = pOp->p3;
66222   }else{
66223 #ifdef SQLITE_OMIT_FLOATING_POINT
66224     u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
66225 #else
66226     u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
66227 #endif
66228     if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
66229   }
66230   if( u.an.c ){
66231     pc = pOp->p2-1;
66232   }
66233   break;
66234 }
66235 
66236 /* Opcode: IsNull P1 P2 * * *
66237 **
66238 ** Jump to P2 if the value in register P1 is NULL.
66239 */
66240 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66241   pIn1 = &aMem[pOp->p1];
66242   if( (pIn1->flags & MEM_Null)!=0 ){
66243     pc = pOp->p2 - 1;
66244   }
66245   break;
66246 }
66247 
66248 /* Opcode: NotNull P1 P2 * * *
66249 **
66250 ** Jump to P2 if the value in register P1 is not NULL.
66251 */
66252 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66253   pIn1 = &aMem[pOp->p1];
66254   if( (pIn1->flags & MEM_Null)==0 ){
66255     pc = pOp->p2 - 1;
66256   }
66257   break;
66258 }
66259 
66260 /* Opcode: Column P1 P2 P3 P4 P5
66261 **
66262 ** Interpret the data that cursor P1 points to as a structure built using
66263 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
66264 ** information about the format of the data.)  Extract the P2-th column
66265 ** from this record.  If there are less that (P2+1)
66266 ** values in the record, extract a NULL.
66267 **
66268 ** The value extracted is stored in register P3.
66269 **
66270 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
66271 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
66272 ** the result.
66273 **
66274 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
66275 ** then the cache of the cursor is reset prior to extracting the column.
66276 ** The first OP_Column against a pseudo-table after the value of the content
66277 ** register has changed should have this bit set.
66278 **
66279 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
66280 ** the result is guaranteed to only be used as the argument of a length()
66281 ** or typeof() function, respectively.  The loading of large blobs can be
66282 ** skipped for length() and all content loading can be skipped for typeof().
66283 */
66284 case OP_Column: {
66285 #if 0  /* local variables moved into u.ao */
66286   u32 payloadSize;   /* Number of bytes in the record */
66287   i64 payloadSize64; /* Number of bytes in the record */
66288   int p1;            /* P1 value of the opcode */
66289   int p2;            /* column number to retrieve */
66290   VdbeCursor *pC;    /* The VDBE cursor */
66291   char *zRec;        /* Pointer to complete record-data */
66292   BtCursor *pCrsr;   /* The BTree cursor */
66293   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
66294   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
66295   int nField;        /* number of fields in the record */
66296   int len;           /* The length of the serialized data for the column */
66297   int i;             /* Loop counter */
66298   char *zData;       /* Part of the record being decoded */
66299   Mem *pDest;        /* Where to write the extracted value */
66300   Mem sMem;          /* For storing the record being decoded */
66301   u8 *zIdx;          /* Index into header */
66302   u8 *zEndHdr;       /* Pointer to first byte after the header */
66303   u32 offset;        /* Offset into the data */
66304   u32 szField;       /* Number of bytes in the content of a field */
66305   int szHdr;         /* Size of the header size field at start of record */
66306   int avail;         /* Number of bytes of available data */
66307   u32 t;             /* A type code from the record header */
66308   Mem *pReg;         /* PseudoTable input register */
66309 #endif /* local variables moved into u.ao */
66310 
66311 
66312   u.ao.p1 = pOp->p1;
66313   u.ao.p2 = pOp->p2;
66314   u.ao.pC = 0;
66315   memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
66316   assert( u.ao.p1<p->nCursor );
66317   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66318   u.ao.pDest = &aMem[pOp->p3];
66319   memAboutToChange(p, u.ao.pDest);
66320   u.ao.zRec = 0;
66321 
66322   /* This block sets the variable u.ao.payloadSize to be the total number of
66323   ** bytes in the record.
66324   **
66325   ** u.ao.zRec is set to be the complete text of the record if it is available.
66326   ** The complete record text is always available for pseudo-tables
66327   ** If the record is stored in a cursor, the complete record text
66328   ** might be available in the  u.ao.pC->aRow cache.  Or it might not be.
66329   ** If the data is unavailable,  u.ao.zRec is set to NULL.
66330   **
66331   ** We also compute the number of columns in the record.  For cursors,
66332   ** the number of columns is stored in the VdbeCursor.nField element.
66333   */
66334   u.ao.pC = p->apCsr[u.ao.p1];
66335   assert( u.ao.pC!=0 );
66336 #ifndef SQLITE_OMIT_VIRTUALTABLE
66337   assert( u.ao.pC->pVtabCursor==0 );
66338 #endif
66339   u.ao.pCrsr = u.ao.pC->pCursor;
66340   if( u.ao.pCrsr!=0 ){
66341     /* The record is stored in a B-Tree */
66342     rc = sqlite3VdbeCursorMoveto(u.ao.pC);
66343     if( rc ) goto abort_due_to_error;
66344     if( u.ao.pC->nullRow ){
66345       u.ao.payloadSize = 0;
66346     }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
66347       u.ao.payloadSize = u.ao.pC->payloadSize;
66348       u.ao.zRec = (char*)u.ao.pC->aRow;
66349     }else if( u.ao.pC->isIndex ){
66350       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
66351       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
66352       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
66353       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
66354       ** payload size, so it is impossible for u.ao.payloadSize64 to be
66355       ** larger than 32 bits. */
66356       assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
66357       u.ao.payloadSize = (u32)u.ao.payloadSize64;
66358     }else{
66359       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
66360       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
66361       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
66362     }
66363   }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
66364     u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
66365     if( u.ao.pC->multiPseudo ){
66366       sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
66367       Deephemeralize(u.ao.pDest);
66368       goto op_column_out;
66369     }
66370     assert( u.ao.pReg->flags & MEM_Blob );
66371     assert( memIsValid(u.ao.pReg) );
66372     u.ao.payloadSize = u.ao.pReg->n;
66373     u.ao.zRec = u.ao.pReg->z;
66374     u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
66375     assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
66376   }else{
66377     /* Consider the row to be NULL */
66378     u.ao.payloadSize = 0;
66379   }
66380 
66381   /* If u.ao.payloadSize is 0, then just store a NULL.  This can happen because of
66382   ** nullRow or because of a corrupt database. */
66383   if( u.ao.payloadSize==0 ){
66384     MemSetTypeFlag(u.ao.pDest, MEM_Null);
66385     goto op_column_out;
66386   }
66387   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
66388   if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66389     goto too_big;
66390   }
66391 
66392   u.ao.nField = u.ao.pC->nField;
66393   assert( u.ao.p2<u.ao.nField );
66394 
66395   /* Read and parse the table header.  Store the results of the parse
66396   ** into the record header cache fields of the cursor.
66397   */
66398   u.ao.aType = u.ao.pC->aType;
66399   if( u.ao.pC->cacheStatus==p->cacheCtr ){
66400     u.ao.aOffset = u.ao.pC->aOffset;
66401   }else{
66402     assert(u.ao.aType);
66403     u.ao.avail = 0;
66404     u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
66405     u.ao.pC->payloadSize = u.ao.payloadSize;
66406     u.ao.pC->cacheStatus = p->cacheCtr;
66407 
66408     /* Figure out how many bytes are in the header */
66409     if( u.ao.zRec ){
66410       u.ao.zData = u.ao.zRec;
66411     }else{
66412       if( u.ao.pC->isIndex ){
66413         u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
66414       }else{
66415         u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
66416       }
66417       /* If KeyFetch()/DataFetch() managed to get the entire payload,
66418       ** save the payload in the u.ao.pC->aRow cache.  That will save us from
66419       ** having to make additional calls to fetch the content portion of
66420       ** the record.
66421       */
66422       assert( u.ao.avail>=0 );
66423       if( u.ao.payloadSize <= (u32)u.ao.avail ){
66424         u.ao.zRec = u.ao.zData;
66425         u.ao.pC->aRow = (u8*)u.ao.zData;
66426       }else{
66427         u.ao.pC->aRow = 0;
66428       }
66429     }
66430     /* The following assert is true in all cases except when
66431     ** the database file has been corrupted externally.
66432     **    assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
66433     u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
66434 
66435     /* Make sure a corrupt database has not given us an oversize header.
66436     ** Do this now to avoid an oversize memory allocation.
66437     **
66438     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
66439     ** types use so much data space that there can only be 4096 and 32 of
66440     ** them, respectively.  So the maximum header length results from a
66441     ** 3-byte type for each of the maximum of 32768 columns plus three
66442     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
66443     */
66444     if( u.ao.offset > 98307 ){
66445       rc = SQLITE_CORRUPT_BKPT;
66446       goto op_column_out;
66447     }
66448 
66449     /* Compute in u.ao.len the number of bytes of data we need to read in order
66450     ** to get u.ao.nField type values.  u.ao.offset is an upper bound on this.  But
66451     ** u.ao.nField might be significantly less than the true number of columns
66452     ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
66453     ** We want to minimize u.ao.len in order to limit the size of the memory
66454     ** allocation, especially if a corrupt database file has caused u.ao.offset
66455     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
66456     ** still exceed Robson memory allocation limits on some configurations.
66457     ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
66458     ** will likely be much smaller since u.ao.nField will likely be less than
66459     ** 20 or so.  This insures that Robson memory allocation limits are
66460     ** not exceeded even for corrupt database files.
66461     */
66462     u.ao.len = u.ao.nField*5 + 3;
66463     if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
66464 
66465     /* The KeyFetch() or DataFetch() above are fast and will get the entire
66466     ** record header in most cases.  But they will fail to get the complete
66467     ** record header if the record header does not fit on a single page
66468     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
66469     ** acquire the complete header text.
66470     */
66471     if( !u.ao.zRec && u.ao.avail<u.ao.len ){
66472       u.ao.sMem.flags = 0;
66473       u.ao.sMem.db = 0;
66474       rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
66475       if( rc!=SQLITE_OK ){
66476         goto op_column_out;
66477       }
66478       u.ao.zData = u.ao.sMem.z;
66479     }
66480     u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
66481     u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
66482 
66483     /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
66484     ** arrays.  u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
66485     ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
66486     ** of the record to the start of the data for the u.ao.i-th column
66487     */
66488     for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
66489       if( u.ao.zIdx<u.ao.zEndHdr ){
66490         u.ao.aOffset[u.ao.i] = u.ao.offset;
66491         if( u.ao.zIdx[0]<0x80 ){
66492           u.ao.t = u.ao.zIdx[0];
66493           u.ao.zIdx++;
66494         }else{
66495           u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
66496         }
66497         u.ao.aType[u.ao.i] = u.ao.t;
66498         u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
66499         u.ao.offset += u.ao.szField;
66500         if( u.ao.offset<u.ao.szField ){  /* True if u.ao.offset overflows */
66501           u.ao.zIdx = &u.ao.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
66502           break;
66503         }
66504       }else{
66505         /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
66506         ** record than SetNumColumns indicated there are columns in the
66507         ** table. Set the u.ao.offset for any extra columns not present in
66508         ** the record to 0. This tells code below to store the default value
66509         ** for the column instead of deserializing a value from the record.
66510         */
66511         u.ao.aOffset[u.ao.i] = 0;
66512       }
66513     }
66514     sqlite3VdbeMemRelease(&u.ao.sMem);
66515     u.ao.sMem.flags = MEM_Null;
66516 
66517     /* If we have read more header data than was contained in the header,
66518     ** or if the end of the last field appears to be past the end of the
66519     ** record, or if the end of the last field appears to be before the end
66520     ** of the record (when all fields present), then we must be dealing
66521     ** with a corrupt database.
66522     */
66523     if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
66524          || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
66525       rc = SQLITE_CORRUPT_BKPT;
66526       goto op_column_out;
66527     }
66528   }
66529 
66530   /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
66531   ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
66532   ** then there are not enough fields in the record to satisfy the
66533   ** request.  In this case, set the value NULL or to P4 if P4 is
66534   ** a pointer to a Mem object.
66535   */
66536   if( u.ao.aOffset[u.ao.p2] ){
66537     assert( rc==SQLITE_OK );
66538     if( u.ao.zRec ){
66539       /* This is the common case where the whole row fits on a single page */
66540       VdbeMemRelease(u.ao.pDest);
66541       sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
66542     }else{
66543       /* This branch happens only when the row overflows onto multiple pages */
66544       u.ao.t = u.ao.aType[u.ao.p2];
66545       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
66546        && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
66547       ){
66548         /* Content is irrelevant for the typeof() function and for
66549         ** the length(X) function if X is a blob.  So we might as well use
66550         ** bogus content rather than reading content from disk.  NULL works
66551         ** for text and blob and whatever is in the u.ao.payloadSize64 variable
66552         ** will work for everything else. */
66553         u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
66554       }else{
66555         u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
66556         sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
66557         rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len,  u.ao.pC->isIndex,
66558                                      &u.ao.sMem);
66559         if( rc!=SQLITE_OK ){
66560           goto op_column_out;
66561         }
66562         u.ao.zData = u.ao.sMem.z;
66563       }
66564       sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
66565     }
66566     u.ao.pDest->enc = encoding;
66567   }else{
66568     if( pOp->p4type==P4_MEM ){
66569       sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
66570     }else{
66571       MemSetTypeFlag(u.ao.pDest, MEM_Null);
66572     }
66573   }
66574 
66575   /* If we dynamically allocated space to hold the data (in the
66576   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
66577   ** dynamically allocated space over to the u.ao.pDest structure.
66578   ** This prevents a memory copy.
66579   */
66580   if( u.ao.sMem.zMalloc ){
66581     assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
66582     assert( !(u.ao.pDest->flags & MEM_Dyn) );
66583     assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
66584     u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
66585     u.ao.pDest->flags |= MEM_Term;
66586     u.ao.pDest->z = u.ao.sMem.z;
66587     u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
66588   }
66589 
66590   rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
66591 
66592 op_column_out:
66593   UPDATE_MAX_BLOBSIZE(u.ao.pDest);
66594   REGISTER_TRACE(pOp->p3, u.ao.pDest);
66595   break;
66596 }
66597 
66598 /* Opcode: Affinity P1 P2 * P4 *
66599 **
66600 ** Apply affinities to a range of P2 registers starting with P1.
66601 **
66602 ** P4 is a string that is P2 characters long. The nth character of the
66603 ** string indicates the column affinity that should be used for the nth
66604 ** memory cell in the range.
66605 */
66606 case OP_Affinity: {
66607 #if 0  /* local variables moved into u.ap */
66608   const char *zAffinity;   /* The affinity to be applied */
66609   char cAff;               /* A single character of affinity */
66610 #endif /* local variables moved into u.ap */
66611 
66612   u.ap.zAffinity = pOp->p4.z;
66613   assert( u.ap.zAffinity!=0 );
66614   assert( u.ap.zAffinity[pOp->p2]==0 );
66615   pIn1 = &aMem[pOp->p1];
66616   while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
66617     assert( pIn1 <= &p->aMem[p->nMem] );
66618     assert( memIsValid(pIn1) );
66619     ExpandBlob(pIn1);
66620     applyAffinity(pIn1, u.ap.cAff, encoding);
66621     pIn1++;
66622   }
66623   break;
66624 }
66625 
66626 /* Opcode: MakeRecord P1 P2 P3 P4 *
66627 **
66628 ** Convert P2 registers beginning with P1 into the [record format]
66629 ** use as a data record in a database table or as a key
66630 ** in an index.  The OP_Column opcode can decode the record later.
66631 **
66632 ** P4 may be a string that is P2 characters long.  The nth character of the
66633 ** string indicates the column affinity that should be used for the nth
66634 ** field of the index key.
66635 **
66636 ** The mapping from character to affinity is given by the SQLITE_AFF_
66637 ** macros defined in sqliteInt.h.
66638 **
66639 ** If P4 is NULL then all index fields have the affinity NONE.
66640 */
66641 case OP_MakeRecord: {
66642 #if 0  /* local variables moved into u.aq */
66643   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
66644   Mem *pRec;             /* The new record */
66645   u64 nData;             /* Number of bytes of data space */
66646   int nHdr;              /* Number of bytes of header space */
66647   i64 nByte;             /* Data space required for this record */
66648   int nZero;             /* Number of zero bytes at the end of the record */
66649   int nVarint;           /* Number of bytes in a varint */
66650   u32 serial_type;       /* Type field */
66651   Mem *pData0;           /* First field to be combined into the record */
66652   Mem *pLast;            /* Last field of the record */
66653   int nField;            /* Number of fields in the record */
66654   char *zAffinity;       /* The affinity string for the record */
66655   int file_format;       /* File format to use for encoding */
66656   int i;                 /* Space used in zNewRecord[] */
66657   int len;               /* Length of a field */
66658 #endif /* local variables moved into u.aq */
66659 
66660   /* Assuming the record contains N fields, the record format looks
66661   ** like this:
66662   **
66663   ** ------------------------------------------------------------------------
66664   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
66665   ** ------------------------------------------------------------------------
66666   **
66667   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
66668   ** and so froth.
66669   **
66670   ** Each type field is a varint representing the serial type of the
66671   ** corresponding data element (see sqlite3VdbeSerialType()). The
66672   ** hdr-size field is also a varint which is the offset from the beginning
66673   ** of the record to data0.
66674   */
66675   u.aq.nData = 0;         /* Number of bytes of data space */
66676   u.aq.nHdr = 0;          /* Number of bytes of header space */
66677   u.aq.nZero = 0;         /* Number of zero bytes at the end of the record */
66678   u.aq.nField = pOp->p1;
66679   u.aq.zAffinity = pOp->p4.z;
66680   assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
66681   u.aq.pData0 = &aMem[u.aq.nField];
66682   u.aq.nField = pOp->p2;
66683   u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
66684   u.aq.file_format = p->minWriteFileFormat;
66685 
66686   /* Identify the output register */
66687   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
66688   pOut = &aMem[pOp->p3];
66689   memAboutToChange(p, pOut);
66690 
66691   /* Loop through the elements that will make up the record to figure
66692   ** out how much space is required for the new record.
66693   */
66694   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
66695     assert( memIsValid(u.aq.pRec) );
66696     if( u.aq.zAffinity ){
66697       applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
66698     }
66699     if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
66700       sqlite3VdbeMemExpandBlob(u.aq.pRec);
66701     }
66702     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
66703     u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
66704     u.aq.nData += u.aq.len;
66705     u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
66706     if( u.aq.pRec->flags & MEM_Zero ){
66707       /* Only pure zero-filled BLOBs can be input to this Opcode.
66708       ** We do not allow blobs with a prefix and a zero-filled tail. */
66709       u.aq.nZero += u.aq.pRec->u.nZero;
66710     }else if( u.aq.len ){
66711       u.aq.nZero = 0;
66712     }
66713   }
66714 
66715   /* Add the initial header varint and total the size */
66716   u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
66717   if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
66718     u.aq.nHdr++;
66719   }
66720   u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
66721   if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66722     goto too_big;
66723   }
66724 
66725   /* Make sure the output register has a buffer large enough to store
66726   ** the new record. The output register (pOp->p3) is not allowed to
66727   ** be one of the input registers (because the following call to
66728   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
66729   */
66730   if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
66731     goto no_mem;
66732   }
66733   u.aq.zNewRecord = (u8 *)pOut->z;
66734 
66735   /* Write the record */
66736   u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
66737   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
66738     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
66739     u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type);      /* serial type */
66740   }
66741   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){  /* serial data */
66742     u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
66743   }
66744   assert( u.aq.i==u.aq.nByte );
66745 
66746   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66747   pOut->n = (int)u.aq.nByte;
66748   pOut->flags = MEM_Blob | MEM_Dyn;
66749   pOut->xDel = 0;
66750   if( u.aq.nZero ){
66751     pOut->u.nZero = u.aq.nZero;
66752     pOut->flags |= MEM_Zero;
66753   }
66754   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
66755   REGISTER_TRACE(pOp->p3, pOut);
66756   UPDATE_MAX_BLOBSIZE(pOut);
66757   break;
66758 }
66759 
66760 /* Opcode: Count P1 P2 * * *
66761 **
66762 ** Store the number of entries (an integer value) in the table or index
66763 ** opened by cursor P1 in register P2
66764 */
66765 #ifndef SQLITE_OMIT_BTREECOUNT
66766 case OP_Count: {         /* out2-prerelease */
66767 #if 0  /* local variables moved into u.ar */
66768   i64 nEntry;
66769   BtCursor *pCrsr;
66770 #endif /* local variables moved into u.ar */
66771 
66772   u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
66773   if( ALWAYS(u.ar.pCrsr) ){
66774     rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
66775   }else{
66776     u.ar.nEntry = 0;
66777   }
66778   pOut->u.i = u.ar.nEntry;
66779   break;
66780 }
66781 #endif
66782 
66783 /* Opcode: Savepoint P1 * * P4 *
66784 **
66785 ** Open, release or rollback the savepoint named by parameter P4, depending
66786 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
66787 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
66788 */
66789 case OP_Savepoint: {
66790 #if 0  /* local variables moved into u.as */
66791   int p1;                         /* Value of P1 operand */
66792   char *zName;                    /* Name of savepoint */
66793   int nName;
66794   Savepoint *pNew;
66795   Savepoint *pSavepoint;
66796   Savepoint *pTmp;
66797   int iSavepoint;
66798   int ii;
66799 #endif /* local variables moved into u.as */
66800 
66801   u.as.p1 = pOp->p1;
66802   u.as.zName = pOp->p4.z;
66803 
66804   /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
66805   ** transaction, then there cannot be any savepoints.
66806   */
66807   assert( db->pSavepoint==0 || db->autoCommit==0 );
66808   assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
66809   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
66810   assert( checkSavepointCount(db) );
66811 
66812   if( u.as.p1==SAVEPOINT_BEGIN ){
66813     if( db->writeVdbeCnt>0 ){
66814       /* A new savepoint cannot be created if there are active write
66815       ** statements (i.e. open read/write incremental blob handles).
66816       */
66817       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
66818         "SQL statements in progress");
66819       rc = SQLITE_BUSY;
66820     }else{
66821       u.as.nName = sqlite3Strlen30(u.as.zName);
66822 
66823 #ifndef SQLITE_OMIT_VIRTUALTABLE
66824       /* This call is Ok even if this savepoint is actually a transaction
66825       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
66826       ** If this is a transaction savepoint being opened, it is guaranteed
66827       ** that the db->aVTrans[] array is empty.  */
66828       assert( db->autoCommit==0 || db->nVTrans==0 );
66829       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
66830                                 db->nStatement+db->nSavepoint);
66831       if( rc!=SQLITE_OK ) goto abort_due_to_error;
66832 #endif
66833 
66834       /* Create a new savepoint structure. */
66835       u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
66836       if( u.as.pNew ){
66837         u.as.pNew->zName = (char *)&u.as.pNew[1];
66838         memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
66839 
66840         /* If there is no open transaction, then mark this as a special
66841         ** "transaction savepoint". */
66842         if( db->autoCommit ){
66843           db->autoCommit = 0;
66844           db->isTransactionSavepoint = 1;
66845         }else{
66846           db->nSavepoint++;
66847         }
66848 
66849         /* Link the new savepoint into the database handle's list. */
66850         u.as.pNew->pNext = db->pSavepoint;
66851         db->pSavepoint = u.as.pNew;
66852         u.as.pNew->nDeferredCons = db->nDeferredCons;
66853       }
66854     }
66855   }else{
66856     u.as.iSavepoint = 0;
66857 
66858     /* Find the named savepoint. If there is no such savepoint, then an
66859     ** an error is returned to the user.  */
66860     for(
66861       u.as.pSavepoint = db->pSavepoint;
66862       u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
66863       u.as.pSavepoint = u.as.pSavepoint->pNext
66864     ){
66865       u.as.iSavepoint++;
66866     }
66867     if( !u.as.pSavepoint ){
66868       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
66869       rc = SQLITE_ERROR;
66870     }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
66871       /* It is not possible to release (commit) a savepoint if there are
66872       ** active write statements.
66873       */
66874       sqlite3SetString(&p->zErrMsg, db,
66875         "cannot release savepoint - SQL statements in progress"
66876       );
66877       rc = SQLITE_BUSY;
66878     }else{
66879 
66880       /* Determine whether or not this is a transaction savepoint. If so,
66881       ** and this is a RELEASE command, then the current transaction
66882       ** is committed.
66883       */
66884       int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
66885       if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
66886         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66887           goto vdbe_return;
66888         }
66889         db->autoCommit = 1;
66890         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66891           p->pc = pc;
66892           db->autoCommit = 0;
66893           p->rc = rc = SQLITE_BUSY;
66894           goto vdbe_return;
66895         }
66896         db->isTransactionSavepoint = 0;
66897         rc = p->rc;
66898       }else{
66899         u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
66900         if( u.as.p1==SAVEPOINT_ROLLBACK ){
66901           for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
66902             sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
66903           }
66904         }
66905         for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
66906           rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
66907           if( rc!=SQLITE_OK ){
66908             goto abort_due_to_error;
66909           }
66910         }
66911         if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
66912           sqlite3ExpirePreparedStatements(db);
66913           sqlite3ResetAllSchemasOfConnection(db);
66914           db->flags = (db->flags | SQLITE_InternChanges);
66915         }
66916       }
66917 
66918       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
66919       ** savepoints nested inside of the savepoint being operated on. */
66920       while( db->pSavepoint!=u.as.pSavepoint ){
66921         u.as.pTmp = db->pSavepoint;
66922         db->pSavepoint = u.as.pTmp->pNext;
66923         sqlite3DbFree(db, u.as.pTmp);
66924         db->nSavepoint--;
66925       }
66926 
66927       /* If it is a RELEASE, then destroy the savepoint being operated on
66928       ** too. If it is a ROLLBACK TO, then set the number of deferred
66929       ** constraint violations present in the database to the value stored
66930       ** when the savepoint was created.  */
66931       if( u.as.p1==SAVEPOINT_RELEASE ){
66932         assert( u.as.pSavepoint==db->pSavepoint );
66933         db->pSavepoint = u.as.pSavepoint->pNext;
66934         sqlite3DbFree(db, u.as.pSavepoint);
66935         if( !isTransaction ){
66936           db->nSavepoint--;
66937         }
66938       }else{
66939         db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
66940       }
66941 
66942       if( !isTransaction ){
66943         rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
66944         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66945       }
66946     }
66947   }
66948 
66949   break;
66950 }
66951 
66952 /* Opcode: AutoCommit P1 P2 * * *
66953 **
66954 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
66955 ** back any currently active btree transactions. If there are any active
66956 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
66957 ** there are active writing VMs or active VMs that use shared cache.
66958 **
66959 ** This instruction causes the VM to halt.
66960 */
66961 case OP_AutoCommit: {
66962 #if 0  /* local variables moved into u.at */
66963   int desiredAutoCommit;
66964   int iRollback;
66965   int turnOnAC;
66966 #endif /* local variables moved into u.at */
66967 
66968   u.at.desiredAutoCommit = pOp->p1;
66969   u.at.iRollback = pOp->p2;
66970   u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
66971   assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
66972   assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
66973   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
66974 
66975 #if 0
66976   if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
66977     /* If this instruction implements a ROLLBACK and other VMs are
66978     ** still running, and a transaction is active, return an error indicating
66979     ** that the other VMs must complete first.
66980     */
66981     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
66982         "SQL statements in progress");
66983     rc = SQLITE_BUSY;
66984   }else
66985 #endif
66986   if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
66987     /* If this instruction implements a COMMIT and other VMs are writing
66988     ** return an error indicating that the other VMs must complete first.
66989     */
66990     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
66991         "SQL statements in progress");
66992     rc = SQLITE_BUSY;
66993   }else if( u.at.desiredAutoCommit!=db->autoCommit ){
66994     if( u.at.iRollback ){
66995       assert( u.at.desiredAutoCommit==1 );
66996       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
66997       db->autoCommit = 1;
66998     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66999       goto vdbe_return;
67000     }else{
67001       db->autoCommit = (u8)u.at.desiredAutoCommit;
67002       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
67003         p->pc = pc;
67004         db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
67005         p->rc = rc = SQLITE_BUSY;
67006         goto vdbe_return;
67007       }
67008     }
67009     assert( db->nStatement==0 );
67010     sqlite3CloseSavepoints(db);
67011     if( p->rc==SQLITE_OK ){
67012       rc = SQLITE_DONE;
67013     }else{
67014       rc = SQLITE_ERROR;
67015     }
67016     goto vdbe_return;
67017   }else{
67018     sqlite3SetString(&p->zErrMsg, db,
67019         (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
67020         (u.at.iRollback)?"cannot rollback - no transaction is active":
67021                    "cannot commit - no transaction is active"));
67022 
67023     rc = SQLITE_ERROR;
67024   }
67025   break;
67026 }
67027 
67028 /* Opcode: Transaction P1 P2 * * *
67029 **
67030 ** Begin a transaction.  The transaction ends when a Commit or Rollback
67031 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
67032 ** transaction might also be rolled back if an error is encountered.
67033 **
67034 ** P1 is the index of the database file on which the transaction is
67035 ** started.  Index 0 is the main database file and index 1 is the
67036 ** file used for temporary tables.  Indices of 2 or more are used for
67037 ** attached databases.
67038 **
67039 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
67040 ** obtained on the database file when a write-transaction is started.  No
67041 ** other process can start another write transaction while this transaction is
67042 ** underway.  Starting a write transaction also creates a rollback journal. A
67043 ** write transaction must be started before any changes can be made to the
67044 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
67045 ** on the file.
67046 **
67047 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
67048 ** true (this flag is set if the Vdbe may modify more than one row and may
67049 ** throw an ABORT exception), a statement transaction may also be opened.
67050 ** More specifically, a statement transaction is opened iff the database
67051 ** connection is currently not in autocommit mode, or if there are other
67052 ** active statements. A statement transaction allows the changes made by this
67053 ** VDBE to be rolled back after an error without having to roll back the
67054 ** entire transaction. If no error is encountered, the statement transaction
67055 ** will automatically commit when the VDBE halts.
67056 **
67057 ** If P2 is zero, then a read-lock is obtained on the database file.
67058 */
67059 case OP_Transaction: {
67060 #if 0  /* local variables moved into u.au */
67061   Btree *pBt;
67062 #endif /* local variables moved into u.au */
67063 
67064   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67065   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67066   u.au.pBt = db->aDb[pOp->p1].pBt;
67067 
67068   if( u.au.pBt ){
67069     rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
67070     if( rc==SQLITE_BUSY ){
67071       p->pc = pc;
67072       p->rc = rc = SQLITE_BUSY;
67073       goto vdbe_return;
67074     }
67075     if( rc!=SQLITE_OK ){
67076       goto abort_due_to_error;
67077     }
67078 
67079     if( pOp->p2 && p->usesStmtJournal
67080      && (db->autoCommit==0 || db->activeVdbeCnt>1)
67081     ){
67082       assert( sqlite3BtreeIsInTrans(u.au.pBt) );
67083       if( p->iStatement==0 ){
67084         assert( db->nStatement>=0 && db->nSavepoint>=0 );
67085         db->nStatement++;
67086         p->iStatement = db->nSavepoint + db->nStatement;
67087       }
67088 
67089       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
67090       if( rc==SQLITE_OK ){
67091         rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
67092       }
67093 
67094       /* Store the current value of the database handles deferred constraint
67095       ** counter. If the statement transaction needs to be rolled back,
67096       ** the value of this counter needs to be restored too.  */
67097       p->nStmtDefCons = db->nDeferredCons;
67098     }
67099   }
67100   break;
67101 }
67102 
67103 /* Opcode: ReadCookie P1 P2 P3 * *
67104 **
67105 ** Read cookie number P3 from database P1 and write it into register P2.
67106 ** P3==1 is the schema version.  P3==2 is the database format.
67107 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
67108 ** the main database file and P1==1 is the database file used to store
67109 ** temporary tables.
67110 **
67111 ** There must be a read-lock on the database (either a transaction
67112 ** must be started or there must be an open cursor) before
67113 ** executing this instruction.
67114 */
67115 case OP_ReadCookie: {               /* out2-prerelease */
67116 #if 0  /* local variables moved into u.av */
67117   int iMeta;
67118   int iDb;
67119   int iCookie;
67120 #endif /* local variables moved into u.av */
67121 
67122   u.av.iDb = pOp->p1;
67123   u.av.iCookie = pOp->p3;
67124   assert( pOp->p3<SQLITE_N_BTREE_META );
67125   assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
67126   assert( db->aDb[u.av.iDb].pBt!=0 );
67127   assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
67128 
67129   sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
67130   pOut->u.i = u.av.iMeta;
67131   break;
67132 }
67133 
67134 /* Opcode: SetCookie P1 P2 P3 * *
67135 **
67136 ** Write the content of register P3 (interpreted as an integer)
67137 ** into cookie number P2 of database P1.  P2==1 is the schema version.
67138 ** P2==2 is the database format. P2==3 is the recommended pager cache
67139 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
67140 ** database file used to store temporary tables.
67141 **
67142 ** A transaction must be started before executing this opcode.
67143 */
67144 case OP_SetCookie: {       /* in3 */
67145 #if 0  /* local variables moved into u.aw */
67146   Db *pDb;
67147 #endif /* local variables moved into u.aw */
67148   assert( pOp->p2<SQLITE_N_BTREE_META );
67149   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67150   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67151   u.aw.pDb = &db->aDb[pOp->p1];
67152   assert( u.aw.pDb->pBt!=0 );
67153   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67154   pIn3 = &aMem[pOp->p3];
67155   sqlite3VdbeMemIntegerify(pIn3);
67156   /* See note about index shifting on OP_ReadCookie */
67157   rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
67158   if( pOp->p2==BTREE_SCHEMA_VERSION ){
67159     /* When the schema cookie changes, record the new cookie internally */
67160     u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
67161     db->flags |= SQLITE_InternChanges;
67162   }else if( pOp->p2==BTREE_FILE_FORMAT ){
67163     /* Record changes in the file format */
67164     u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
67165   }
67166   if( pOp->p1==1 ){
67167     /* Invalidate all prepared statements whenever the TEMP database
67168     ** schema is changed.  Ticket #1644 */
67169     sqlite3ExpirePreparedStatements(db);
67170     p->expired = 0;
67171   }
67172   break;
67173 }
67174 
67175 /* Opcode: VerifyCookie P1 P2 P3 * *
67176 **
67177 ** Check the value of global database parameter number 0 (the
67178 ** schema version) and make sure it is equal to P2 and that the
67179 ** generation counter on the local schema parse equals P3.
67180 **
67181 ** P1 is the database number which is 0 for the main database file
67182 ** and 1 for the file holding temporary tables and some higher number
67183 ** for auxiliary databases.
67184 **
67185 ** The cookie changes its value whenever the database schema changes.
67186 ** This operation is used to detect when that the cookie has changed
67187 ** and that the current process needs to reread the schema.
67188 **
67189 ** Either a transaction needs to have been started or an OP_Open needs
67190 ** to be executed (to establish a read lock) before this opcode is
67191 ** invoked.
67192 */
67193 case OP_VerifyCookie: {
67194 #if 0  /* local variables moved into u.ax */
67195   int iMeta;
67196   int iGen;
67197   Btree *pBt;
67198 #endif /* local variables moved into u.ax */
67199 
67200   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67201   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67202   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67203   u.ax.pBt = db->aDb[pOp->p1].pBt;
67204   if( u.ax.pBt ){
67205     sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
67206     u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67207   }else{
67208     u.ax.iGen = u.ax.iMeta = 0;
67209   }
67210   if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
67211     sqlite3DbFree(db, p->zErrMsg);
67212     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
67213     /* If the schema-cookie from the database file matches the cookie
67214     ** stored with the in-memory representation of the schema, do
67215     ** not reload the schema from the database file.
67216     **
67217     ** If virtual-tables are in use, this is not just an optimization.
67218     ** Often, v-tables store their data in other SQLite tables, which
67219     ** are queried from within xNext() and other v-table methods using
67220     ** prepared queries. If such a query is out-of-date, we do not want to
67221     ** discard the database schema, as the user code implementing the
67222     ** v-table would have to be ready for the sqlite3_vtab structure itself
67223     ** to be invalidated whenever sqlite3_step() is called from within
67224     ** a v-table method.
67225     */
67226     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
67227       sqlite3ResetOneSchema(db, pOp->p1);
67228     }
67229 
67230     p->expired = 1;
67231     rc = SQLITE_SCHEMA;
67232   }
67233   break;
67234 }
67235 
67236 /* Opcode: OpenRead P1 P2 P3 P4 P5
67237 **
67238 ** Open a read-only cursor for the database table whose root page is
67239 ** P2 in a database file.  The database file is determined by P3.
67240 ** P3==0 means the main database, P3==1 means the database used for
67241 ** temporary tables, and P3>1 means used the corresponding attached
67242 ** database.  Give the new cursor an identifier of P1.  The P1
67243 ** values need not be contiguous but all P1 values should be small integers.
67244 ** It is an error for P1 to be negative.
67245 **
67246 ** If P5!=0 then use the content of register P2 as the root page, not
67247 ** the value of P2 itself.
67248 **
67249 ** There will be a read lock on the database whenever there is an
67250 ** open cursor.  If the database was unlocked prior to this instruction
67251 ** then a read lock is acquired as part of this instruction.  A read
67252 ** lock allows other processes to read the database but prohibits
67253 ** any other process from modifying the database.  The read lock is
67254 ** released when all cursors are closed.  If this instruction attempts
67255 ** to get a read lock but fails, the script terminates with an
67256 ** SQLITE_BUSY error code.
67257 **
67258 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67259 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
67260 ** structure, then said structure defines the content and collating
67261 ** sequence of the index being opened. Otherwise, if P4 is an integer
67262 ** value, it is set to the number of columns in the table.
67263 **
67264 ** See also OpenWrite.
67265 */
67266 /* Opcode: OpenWrite P1 P2 P3 P4 P5
67267 **
67268 ** Open a read/write cursor named P1 on the table or index whose root
67269 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
67270 ** root page.
67271 **
67272 ** The P4 value may be either an integer (P4_INT32) or a pointer to
67273 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
67274 ** structure, then said structure defines the content and collating
67275 ** sequence of the index being opened. Otherwise, if P4 is an integer
67276 ** value, it is set to the number of columns in the table, or to the
67277 ** largest index of any column of the table that is actually used.
67278 **
67279 ** This instruction works just like OpenRead except that it opens the cursor
67280 ** in read/write mode.  For a given table, there can be one or more read-only
67281 ** cursors or a single read/write cursor but not both.
67282 **
67283 ** See also OpenRead.
67284 */
67285 case OP_OpenRead:
67286 case OP_OpenWrite: {
67287 #if 0  /* local variables moved into u.ay */
67288   int nField;
67289   KeyInfo *pKeyInfo;
67290   int p2;
67291   int iDb;
67292   int wrFlag;
67293   Btree *pX;
67294   VdbeCursor *pCur;
67295   Db *pDb;
67296 #endif /* local variables moved into u.ay */
67297 
67298   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
67299   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
67300 
67301   if( p->expired ){
67302     rc = SQLITE_ABORT;
67303     break;
67304   }
67305 
67306   u.ay.nField = 0;
67307   u.ay.pKeyInfo = 0;
67308   u.ay.p2 = pOp->p2;
67309   u.ay.iDb = pOp->p3;
67310   assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
67311   assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
67312   u.ay.pDb = &db->aDb[u.ay.iDb];
67313   u.ay.pX = u.ay.pDb->pBt;
67314   assert( u.ay.pX!=0 );
67315   if( pOp->opcode==OP_OpenWrite ){
67316     u.ay.wrFlag = 1;
67317     assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
67318     if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
67319       p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
67320     }
67321   }else{
67322     u.ay.wrFlag = 0;
67323   }
67324   if( pOp->p5 & OPFLAG_P2ISREG ){
67325     assert( u.ay.p2>0 );
67326     assert( u.ay.p2<=p->nMem );
67327     pIn2 = &aMem[u.ay.p2];
67328     assert( memIsValid(pIn2) );
67329     assert( (pIn2->flags & MEM_Int)!=0 );
67330     sqlite3VdbeMemIntegerify(pIn2);
67331     u.ay.p2 = (int)pIn2->u.i;
67332     /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
67333     ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
67334     ** If there were a failure, the prepared statement would have halted
67335     ** before reaching this instruction. */
67336     if( NEVER(u.ay.p2<2) ) {
67337       rc = SQLITE_CORRUPT_BKPT;
67338       goto abort_due_to_error;
67339     }
67340   }
67341   if( pOp->p4type==P4_KEYINFO ){
67342     u.ay.pKeyInfo = pOp->p4.pKeyInfo;
67343     u.ay.pKeyInfo->enc = ENC(p->db);
67344     u.ay.nField = u.ay.pKeyInfo->nField+1;
67345   }else if( pOp->p4type==P4_INT32 ){
67346     u.ay.nField = pOp->p4.i;
67347   }
67348   assert( pOp->p1>=0 );
67349   u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
67350   if( u.ay.pCur==0 ) goto no_mem;
67351   u.ay.pCur->nullRow = 1;
67352   u.ay.pCur->isOrdered = 1;
67353   rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
67354   u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
67355   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
67356   sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
67357 
67358   /* Since it performs no memory allocation or IO, the only value that
67359   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
67360   assert( rc==SQLITE_OK );
67361 
67362   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
67363   ** SQLite used to check if the root-page flags were sane at this point
67364   ** and report database corruption if they were not, but this check has
67365   ** since moved into the btree layer.  */
67366   u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
67367   u.ay.pCur->isIndex = !u.ay.pCur->isTable;
67368   break;
67369 }
67370 
67371 /* Opcode: OpenEphemeral P1 P2 * P4 P5
67372 **
67373 ** Open a new cursor P1 to a transient table.
67374 ** The cursor is always opened read/write even if
67375 ** the main database is read-only.  The ephemeral
67376 ** table is deleted automatically when the cursor is closed.
67377 **
67378 ** P2 is the number of columns in the ephemeral table.
67379 ** The cursor points to a BTree table if P4==0 and to a BTree index
67380 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
67381 ** that defines the format of keys in the index.
67382 **
67383 ** This opcode was once called OpenTemp.  But that created
67384 ** confusion because the term "temp table", might refer either
67385 ** to a TEMP table at the SQL level, or to a table opened by
67386 ** this opcode.  Then this opcode was call OpenVirtual.  But
67387 ** that created confusion with the whole virtual-table idea.
67388 **
67389 ** The P5 parameter can be a mask of the BTREE_* flags defined
67390 ** in btree.h.  These flags control aspects of the operation of
67391 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
67392 ** added automatically.
67393 */
67394 /* Opcode: OpenAutoindex P1 P2 * P4 *
67395 **
67396 ** This opcode works the same as OP_OpenEphemeral.  It has a
67397 ** different name to distinguish its use.  Tables created using
67398 ** by this opcode will be used for automatically created transient
67399 ** indices in joins.
67400 */
67401 case OP_OpenAutoindex:
67402 case OP_OpenEphemeral: {
67403 #if 0  /* local variables moved into u.az */
67404   VdbeCursor *pCx;
67405 #endif /* local variables moved into u.az */
67406   static const int vfsFlags =
67407       SQLITE_OPEN_READWRITE |
67408       SQLITE_OPEN_CREATE |
67409       SQLITE_OPEN_EXCLUSIVE |
67410       SQLITE_OPEN_DELETEONCLOSE |
67411       SQLITE_OPEN_TRANSIENT_DB;
67412 
67413   assert( pOp->p1>=0 );
67414   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
67415   if( u.az.pCx==0 ) goto no_mem;
67416   u.az.pCx->nullRow = 1;
67417   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
67418                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
67419   if( rc==SQLITE_OK ){
67420     rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
67421   }
67422   if( rc==SQLITE_OK ){
67423     /* If a transient index is required, create it by calling
67424     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
67425     ** opening it. If a transient table is required, just use the
67426     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
67427     */
67428     if( pOp->p4.pKeyInfo ){
67429       int pgno;
67430       assert( pOp->p4type==P4_KEYINFO );
67431       rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
67432       if( rc==SQLITE_OK ){
67433         assert( pgno==MASTER_ROOT+1 );
67434         rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
67435                                 (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
67436         u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
67437         u.az.pCx->pKeyInfo->enc = ENC(p->db);
67438       }
67439       u.az.pCx->isTable = 0;
67440     }else{
67441       rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
67442       u.az.pCx->isTable = 1;
67443     }
67444   }
67445   u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
67446   u.az.pCx->isIndex = !u.az.pCx->isTable;
67447   break;
67448 }
67449 
67450 /* Opcode: SorterOpen P1 P2 * P4 *
67451 **
67452 ** This opcode works like OP_OpenEphemeral except that it opens
67453 ** a transient index that is specifically designed to sort large
67454 ** tables using an external merge-sort algorithm.
67455 */
67456 case OP_SorterOpen: {
67457 #if 0  /* local variables moved into u.ba */
67458   VdbeCursor *pCx;
67459 #endif /* local variables moved into u.ba */
67460 
67461   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
67462   if( u.ba.pCx==0 ) goto no_mem;
67463   u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
67464   u.ba.pCx->pKeyInfo->enc = ENC(p->db);
67465   u.ba.pCx->isSorter = 1;
67466   rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
67467   break;
67468 }
67469 
67470 /* Opcode: OpenPseudo P1 P2 P3 * P5
67471 **
67472 ** Open a new cursor that points to a fake table that contains a single
67473 ** row of data.  The content of that one row in the content of memory
67474 ** register P2 when P5==0.  In other words, cursor P1 becomes an alias for the
67475 ** MEM_Blob content contained in register P2.  When P5==1, then the
67476 ** row is represented by P3 consecutive registers beginning with P2.
67477 **
67478 ** A pseudo-table created by this opcode is used to hold a single
67479 ** row output from the sorter so that the row can be decomposed into
67480 ** individual columns using the OP_Column opcode.  The OP_Column opcode
67481 ** is the only cursor opcode that works with a pseudo-table.
67482 **
67483 ** P3 is the number of fields in the records that will be stored by
67484 ** the pseudo-table.
67485 */
67486 case OP_OpenPseudo: {
67487 #if 0  /* local variables moved into u.bb */
67488   VdbeCursor *pCx;
67489 #endif /* local variables moved into u.bb */
67490 
67491   assert( pOp->p1>=0 );
67492   u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
67493   if( u.bb.pCx==0 ) goto no_mem;
67494   u.bb.pCx->nullRow = 1;
67495   u.bb.pCx->pseudoTableReg = pOp->p2;
67496   u.bb.pCx->isTable = 1;
67497   u.bb.pCx->isIndex = 0;
67498   u.bb.pCx->multiPseudo = pOp->p5;
67499   break;
67500 }
67501 
67502 /* Opcode: Close P1 * * * *
67503 **
67504 ** Close a cursor previously opened as P1.  If P1 is not
67505 ** currently open, this instruction is a no-op.
67506 */
67507 case OP_Close: {
67508   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67509   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
67510   p->apCsr[pOp->p1] = 0;
67511   break;
67512 }
67513 
67514 /* Opcode: SeekGe P1 P2 P3 P4 *
67515 **
67516 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
67517 ** use the value in register P3 as the key.  If cursor P1 refers
67518 ** to an SQL index, then P3 is the first in an array of P4 registers
67519 ** that are used as an unpacked index key.
67520 **
67521 ** Reposition cursor P1 so that  it points to the smallest entry that
67522 ** is greater than or equal to the key value. If there are no records
67523 ** greater than or equal to the key and P2 is not zero, then jump to P2.
67524 **
67525 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
67526 */
67527 /* Opcode: SeekGt P1 P2 P3 P4 *
67528 **
67529 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
67530 ** use the value in register P3 as a key. If cursor P1 refers
67531 ** to an SQL index, then P3 is the first in an array of P4 registers
67532 ** that are used as an unpacked index key.
67533 **
67534 ** Reposition cursor P1 so that  it points to the smallest entry that
67535 ** is greater than the key value. If there are no records greater than
67536 ** the key and P2 is not zero, then jump to P2.
67537 **
67538 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
67539 */
67540 /* Opcode: SeekLt P1 P2 P3 P4 *
67541 **
67542 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
67543 ** use the value in register P3 as a key. If cursor P1 refers
67544 ** to an SQL index, then P3 is the first in an array of P4 registers
67545 ** that are used as an unpacked index key.
67546 **
67547 ** Reposition cursor P1 so that  it points to the largest entry that
67548 ** is less than the key value. If there are no records less than
67549 ** the key and P2 is not zero, then jump to P2.
67550 **
67551 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
67552 */
67553 /* Opcode: SeekLe P1 P2 P3 P4 *
67554 **
67555 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
67556 ** use the value in register P3 as a key. If cursor P1 refers
67557 ** to an SQL index, then P3 is the first in an array of P4 registers
67558 ** that are used as an unpacked index key.
67559 **
67560 ** Reposition cursor P1 so that it points to the largest entry that
67561 ** is less than or equal to the key value. If there are no records
67562 ** less than or equal to the key and P2 is not zero, then jump to P2.
67563 **
67564 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
67565 */
67566 case OP_SeekLt:         /* jump, in3 */
67567 case OP_SeekLe:         /* jump, in3 */
67568 case OP_SeekGe:         /* jump, in3 */
67569 case OP_SeekGt: {       /* jump, in3 */
67570 #if 0  /* local variables moved into u.bc */
67571   int res;
67572   int oc;
67573   VdbeCursor *pC;
67574   UnpackedRecord r;
67575   int nField;
67576   i64 iKey;      /* The rowid we are to seek to */
67577 #endif /* local variables moved into u.bc */
67578 
67579   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67580   assert( pOp->p2!=0 );
67581   u.bc.pC = p->apCsr[pOp->p1];
67582   assert( u.bc.pC!=0 );
67583   assert( u.bc.pC->pseudoTableReg==0 );
67584   assert( OP_SeekLe == OP_SeekLt+1 );
67585   assert( OP_SeekGe == OP_SeekLt+2 );
67586   assert( OP_SeekGt == OP_SeekLt+3 );
67587   assert( u.bc.pC->isOrdered );
67588   if( ALWAYS(u.bc.pC->pCursor!=0) ){
67589     u.bc.oc = pOp->opcode;
67590     u.bc.pC->nullRow = 0;
67591     if( u.bc.pC->isTable ){
67592       /* The input value in P3 might be of any type: integer, real, string,
67593       ** blob, or NULL.  But it needs to be an integer before we can do
67594       ** the seek, so covert it. */
67595       pIn3 = &aMem[pOp->p3];
67596       applyNumericAffinity(pIn3);
67597       u.bc.iKey = sqlite3VdbeIntValue(pIn3);
67598       u.bc.pC->rowidIsValid = 0;
67599 
67600       /* If the P3 value could not be converted into an integer without
67601       ** loss of information, then special processing is required... */
67602       if( (pIn3->flags & MEM_Int)==0 ){
67603         if( (pIn3->flags & MEM_Real)==0 ){
67604           /* If the P3 value cannot be converted into any kind of a number,
67605           ** then the seek is not possible, so jump to P2 */
67606           pc = pOp->p2 - 1;
67607           break;
67608         }
67609         /* If we reach this point, then the P3 value must be a floating
67610         ** point number. */
67611         assert( (pIn3->flags & MEM_Real)!=0 );
67612 
67613         if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
67614           /* The P3 value is too large in magnitude to be expressed as an
67615           ** integer. */
67616           u.bc.res = 1;
67617           if( pIn3->r<0 ){
67618             if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
67619               rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
67620               if( rc!=SQLITE_OK ) goto abort_due_to_error;
67621             }
67622           }else{
67623             if( u.bc.oc<=OP_SeekLe ){  assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
67624               rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
67625               if( rc!=SQLITE_OK ) goto abort_due_to_error;
67626             }
67627           }
67628           if( u.bc.res ){
67629             pc = pOp->p2 - 1;
67630           }
67631           break;
67632         }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
67633           /* Use the ceiling() function to convert real->int */
67634           if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
67635         }else{
67636           /* Use the floor() function to convert real->int */
67637           assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
67638           if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
67639         }
67640       }
67641       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
67642       if( rc!=SQLITE_OK ){
67643         goto abort_due_to_error;
67644       }
67645       if( u.bc.res==0 ){
67646         u.bc.pC->rowidIsValid = 1;
67647         u.bc.pC->lastRowid = u.bc.iKey;
67648       }
67649     }else{
67650       u.bc.nField = pOp->p4.i;
67651       assert( pOp->p4type==P4_INT32 );
67652       assert( u.bc.nField>0 );
67653       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
67654       u.bc.r.nField = (u16)u.bc.nField;
67655 
67656       /* The next line of code computes as follows, only faster:
67657       **   if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
67658       **     u.bc.r.flags = UNPACKED_INCRKEY;
67659       **   }else{
67660       **     u.bc.r.flags = 0;
67661       **   }
67662       */
67663       u.bc.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
67664       assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
67665       assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
67666       assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
67667       assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
67668 
67669       u.bc.r.aMem = &aMem[pOp->p3];
67670 #ifdef SQLITE_DEBUG
67671       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
67672 #endif
67673       ExpandBlob(u.bc.r.aMem);
67674       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
67675       if( rc!=SQLITE_OK ){
67676         goto abort_due_to_error;
67677       }
67678       u.bc.pC->rowidIsValid = 0;
67679     }
67680     u.bc.pC->deferredMoveto = 0;
67681     u.bc.pC->cacheStatus = CACHE_STALE;
67682 #ifdef SQLITE_TEST
67683     sqlite3_search_count++;
67684 #endif
67685     if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
67686       if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
67687         rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
67688         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67689         u.bc.pC->rowidIsValid = 0;
67690       }else{
67691         u.bc.res = 0;
67692       }
67693     }else{
67694       assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
67695       if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
67696         rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
67697         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67698         u.bc.pC->rowidIsValid = 0;
67699       }else{
67700         /* u.bc.res might be negative because the table is empty.  Check to
67701         ** see if this is the case.
67702         */
67703         u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
67704       }
67705     }
67706     assert( pOp->p2>0 );
67707     if( u.bc.res ){
67708       pc = pOp->p2 - 1;
67709     }
67710   }else{
67711     /* This happens when attempting to open the sqlite3_master table
67712     ** for read access returns SQLITE_EMPTY. In this case always
67713     ** take the jump (since there are no records in the table).
67714     */
67715     pc = pOp->p2 - 1;
67716   }
67717   break;
67718 }
67719 
67720 /* Opcode: Seek P1 P2 * * *
67721 **
67722 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
67723 ** for P1 to move so that it points to the rowid given by P2.
67724 **
67725 ** This is actually a deferred seek.  Nothing actually happens until
67726 ** the cursor is used to read a record.  That way, if no reads
67727 ** occur, no unnecessary I/O happens.
67728 */
67729 case OP_Seek: {    /* in2 */
67730 #if 0  /* local variables moved into u.bd */
67731   VdbeCursor *pC;
67732 #endif /* local variables moved into u.bd */
67733 
67734   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67735   u.bd.pC = p->apCsr[pOp->p1];
67736   assert( u.bd.pC!=0 );
67737   if( ALWAYS(u.bd.pC->pCursor!=0) ){
67738     assert( u.bd.pC->isTable );
67739     u.bd.pC->nullRow = 0;
67740     pIn2 = &aMem[pOp->p2];
67741     u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
67742     u.bd.pC->rowidIsValid = 0;
67743     u.bd.pC->deferredMoveto = 1;
67744   }
67745   break;
67746 }
67747 
67748 
67749 /* Opcode: Found P1 P2 P3 P4 *
67750 **
67751 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67752 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67753 ** record.
67754 **
67755 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67756 ** is a prefix of any entry in P1 then a jump is made to P2 and
67757 ** P1 is left pointing at the matching entry.
67758 */
67759 /* Opcode: NotFound P1 P2 P3 P4 *
67760 **
67761 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67762 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67763 ** record.
67764 **
67765 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67766 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
67767 ** does contain an entry whose prefix matches the P3/P4 record then control
67768 ** falls through to the next instruction and P1 is left pointing at the
67769 ** matching entry.
67770 **
67771 ** See also: Found, NotExists, IsUnique
67772 */
67773 case OP_NotFound:       /* jump, in3 */
67774 case OP_Found: {        /* jump, in3 */
67775 #if 0  /* local variables moved into u.be */
67776   int alreadyExists;
67777   VdbeCursor *pC;
67778   int res;
67779   char *pFree;
67780   UnpackedRecord *pIdxKey;
67781   UnpackedRecord r;
67782   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
67783 #endif /* local variables moved into u.be */
67784 
67785 #ifdef SQLITE_TEST
67786   sqlite3_found_count++;
67787 #endif
67788 
67789   u.be.alreadyExists = 0;
67790   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67791   assert( pOp->p4type==P4_INT32 );
67792   u.be.pC = p->apCsr[pOp->p1];
67793   assert( u.be.pC!=0 );
67794   pIn3 = &aMem[pOp->p3];
67795   if( ALWAYS(u.be.pC->pCursor!=0) ){
67796 
67797     assert( u.be.pC->isTable==0 );
67798     if( pOp->p4.i>0 ){
67799       u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
67800       u.be.r.nField = (u16)pOp->p4.i;
67801       u.be.r.aMem = pIn3;
67802 #ifdef SQLITE_DEBUG
67803       { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
67804 #endif
67805       u.be.r.flags = UNPACKED_PREFIX_MATCH;
67806       u.be.pIdxKey = &u.be.r;
67807     }else{
67808       u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
67809           u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
67810       );
67811       if( u.be.pIdxKey==0 ) goto no_mem;
67812       assert( pIn3->flags & MEM_Blob );
67813       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
67814       sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
67815       u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
67816     }
67817     rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
67818     if( pOp->p4.i==0 ){
67819       sqlite3DbFree(db, u.be.pFree);
67820     }
67821     if( rc!=SQLITE_OK ){
67822       break;
67823     }
67824     u.be.alreadyExists = (u.be.res==0);
67825     u.be.pC->deferredMoveto = 0;
67826     u.be.pC->cacheStatus = CACHE_STALE;
67827   }
67828   if( pOp->opcode==OP_Found ){
67829     if( u.be.alreadyExists ) pc = pOp->p2 - 1;
67830   }else{
67831     if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
67832   }
67833   break;
67834 }
67835 
67836 /* Opcode: IsUnique P1 P2 P3 P4 *
67837 **
67838 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
67839 ** no data and where the key are records generated by OP_MakeRecord with
67840 ** the list field being the integer ROWID of the entry that the index
67841 ** entry refers to.
67842 **
67843 ** The P3 register contains an integer record number. Call this record
67844 ** number R. Register P4 is the first in a set of N contiguous registers
67845 ** that make up an unpacked index key that can be used with cursor P1.
67846 ** The value of N can be inferred from the cursor. N includes the rowid
67847 ** value appended to the end of the index record. This rowid value may
67848 ** or may not be the same as R.
67849 **
67850 ** If any of the N registers beginning with register P4 contains a NULL
67851 ** value, jump immediately to P2.
67852 **
67853 ** Otherwise, this instruction checks if cursor P1 contains an entry
67854 ** where the first (N-1) fields match but the rowid value at the end
67855 ** of the index entry is not R. If there is no such entry, control jumps
67856 ** to instruction P2. Otherwise, the rowid of the conflicting index
67857 ** entry is copied to register P3 and control falls through to the next
67858 ** instruction.
67859 **
67860 ** See also: NotFound, NotExists, Found
67861 */
67862 case OP_IsUnique: {        /* jump, in3 */
67863 #if 0  /* local variables moved into u.bf */
67864   u16 ii;
67865   VdbeCursor *pCx;
67866   BtCursor *pCrsr;
67867   u16 nField;
67868   Mem *aMx;
67869   UnpackedRecord r;                  /* B-Tree index search key */
67870   i64 R;                             /* Rowid stored in register P3 */
67871 #endif /* local variables moved into u.bf */
67872 
67873   pIn3 = &aMem[pOp->p3];
67874   u.bf.aMx = &aMem[pOp->p4.i];
67875   /* Assert that the values of parameters P1 and P4 are in range. */
67876   assert( pOp->p4type==P4_INT32 );
67877   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
67878   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67879 
67880   /* Find the index cursor. */
67881   u.bf.pCx = p->apCsr[pOp->p1];
67882   assert( u.bf.pCx->deferredMoveto==0 );
67883   u.bf.pCx->seekResult = 0;
67884   u.bf.pCx->cacheStatus = CACHE_STALE;
67885   u.bf.pCrsr = u.bf.pCx->pCursor;
67886 
67887   /* If any of the values are NULL, take the jump. */
67888   u.bf.nField = u.bf.pCx->pKeyInfo->nField;
67889   for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
67890     if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
67891       pc = pOp->p2 - 1;
67892       u.bf.pCrsr = 0;
67893       break;
67894     }
67895   }
67896   assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
67897 
67898   if( u.bf.pCrsr!=0 ){
67899     /* Populate the index search key. */
67900     u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
67901     u.bf.r.nField = u.bf.nField + 1;
67902     u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
67903     u.bf.r.aMem = u.bf.aMx;
67904 #ifdef SQLITE_DEBUG
67905     { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
67906 #endif
67907 
67908     /* Extract the value of u.bf.R from register P3. */
67909     sqlite3VdbeMemIntegerify(pIn3);
67910     u.bf.R = pIn3->u.i;
67911 
67912     /* Search the B-Tree index. If no conflicting record is found, jump
67913     ** to P2. Otherwise, copy the rowid of the conflicting record to
67914     ** register P3 and fall through to the next instruction.  */
67915     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
67916     if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
67917       pc = pOp->p2 - 1;
67918     }else{
67919       pIn3->u.i = u.bf.r.rowid;
67920     }
67921   }
67922   break;
67923 }
67924 
67925 /* Opcode: NotExists P1 P2 P3 * *
67926 **
67927 ** Use the content of register P3 as an integer key.  If a record
67928 ** with that key does not exist in table of P1, then jump to P2.
67929 ** If the record does exist, then fall through.  The cursor is left
67930 ** pointing to the record if it exists.
67931 **
67932 ** The difference between this operation and NotFound is that this
67933 ** operation assumes the key is an integer and that P1 is a table whereas
67934 ** NotFound assumes key is a blob constructed from MakeRecord and
67935 ** P1 is an index.
67936 **
67937 ** See also: Found, NotFound, IsUnique
67938 */
67939 case OP_NotExists: {        /* jump, in3 */
67940 #if 0  /* local variables moved into u.bg */
67941   VdbeCursor *pC;
67942   BtCursor *pCrsr;
67943   int res;
67944   u64 iKey;
67945 #endif /* local variables moved into u.bg */
67946 
67947   pIn3 = &aMem[pOp->p3];
67948   assert( pIn3->flags & MEM_Int );
67949   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67950   u.bg.pC = p->apCsr[pOp->p1];
67951   assert( u.bg.pC!=0 );
67952   assert( u.bg.pC->isTable );
67953   assert( u.bg.pC->pseudoTableReg==0 );
67954   u.bg.pCrsr = u.bg.pC->pCursor;
67955   if( ALWAYS(u.bg.pCrsr!=0) ){
67956     u.bg.res = 0;
67957     u.bg.iKey = pIn3->u.i;
67958     rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
67959     u.bg.pC->lastRowid = pIn3->u.i;
67960     u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
67961     u.bg.pC->nullRow = 0;
67962     u.bg.pC->cacheStatus = CACHE_STALE;
67963     u.bg.pC->deferredMoveto = 0;
67964     if( u.bg.res!=0 ){
67965       pc = pOp->p2 - 1;
67966       assert( u.bg.pC->rowidIsValid==0 );
67967     }
67968     u.bg.pC->seekResult = u.bg.res;
67969   }else{
67970     /* This happens when an attempt to open a read cursor on the
67971     ** sqlite_master table returns SQLITE_EMPTY.
67972     */
67973     pc = pOp->p2 - 1;
67974     assert( u.bg.pC->rowidIsValid==0 );
67975     u.bg.pC->seekResult = 0;
67976   }
67977   break;
67978 }
67979 
67980 /* Opcode: Sequence P1 P2 * * *
67981 **
67982 ** Find the next available sequence number for cursor P1.
67983 ** Write the sequence number into register P2.
67984 ** The sequence number on the cursor is incremented after this
67985 ** instruction.
67986 */
67987 case OP_Sequence: {           /* out2-prerelease */
67988   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67989   assert( p->apCsr[pOp->p1]!=0 );
67990   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
67991   break;
67992 }
67993 
67994 
67995 /* Opcode: NewRowid P1 P2 P3 * *
67996 **
67997 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
67998 ** The record number is not previously used as a key in the database
67999 ** table that cursor P1 points to.  The new record number is written
68000 ** written to register P2.
68001 **
68002 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
68003 ** the largest previously generated record number. No new record numbers are
68004 ** allowed to be less than this value. When this value reaches its maximum,
68005 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
68006 ** generated record number. This P3 mechanism is used to help implement the
68007 ** AUTOINCREMENT feature.
68008 */
68009 case OP_NewRowid: {           /* out2-prerelease */
68010 #if 0  /* local variables moved into u.bh */
68011   i64 v;                 /* The new rowid */
68012   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
68013   int res;               /* Result of an sqlite3BtreeLast() */
68014   int cnt;               /* Counter to limit the number of searches */
68015   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
68016   VdbeFrame *pFrame;     /* Root frame of VDBE */
68017 #endif /* local variables moved into u.bh */
68018 
68019   u.bh.v = 0;
68020   u.bh.res = 0;
68021   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68022   u.bh.pC = p->apCsr[pOp->p1];
68023   assert( u.bh.pC!=0 );
68024   if( NEVER(u.bh.pC->pCursor==0) ){
68025     /* The zero initialization above is all that is needed */
68026   }else{
68027     /* The next rowid or record number (different terms for the same
68028     ** thing) is obtained in a two-step algorithm.
68029     **
68030     ** First we attempt to find the largest existing rowid and add one
68031     ** to that.  But if the largest existing rowid is already the maximum
68032     ** positive integer, we have to fall through to the second
68033     ** probabilistic algorithm
68034     **
68035     ** The second algorithm is to select a rowid at random and see if
68036     ** it already exists in the table.  If it does not exist, we have
68037     ** succeeded.  If the random rowid does exist, we select a new one
68038     ** and try again, up to 100 times.
68039     */
68040     assert( u.bh.pC->isTable );
68041 
68042 #ifdef SQLITE_32BIT_ROWID
68043 #   define MAX_ROWID 0x7fffffff
68044 #else
68045     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
68046     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
68047     ** to provide the constant while making all compilers happy.
68048     */
68049 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
68050 #endif
68051 
68052     if( !u.bh.pC->useRandomRowid ){
68053       u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
68054       if( u.bh.v==0 ){
68055         rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
68056         if( rc!=SQLITE_OK ){
68057           goto abort_due_to_error;
68058         }
68059         if( u.bh.res ){
68060           u.bh.v = 1;   /* IMP: R-61914-48074 */
68061         }else{
68062           assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
68063           rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
68064           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
68065           if( u.bh.v>=MAX_ROWID ){
68066             u.bh.pC->useRandomRowid = 1;
68067           }else{
68068             u.bh.v++;   /* IMP: R-29538-34987 */
68069           }
68070         }
68071       }
68072 
68073 #ifndef SQLITE_OMIT_AUTOINCREMENT
68074       if( pOp->p3 ){
68075         /* Assert that P3 is a valid memory cell. */
68076         assert( pOp->p3>0 );
68077         if( p->pFrame ){
68078           for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
68079           /* Assert that P3 is a valid memory cell. */
68080           assert( pOp->p3<=u.bh.pFrame->nMem );
68081           u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
68082         }else{
68083           /* Assert that P3 is a valid memory cell. */
68084           assert( pOp->p3<=p->nMem );
68085           u.bh.pMem = &aMem[pOp->p3];
68086           memAboutToChange(p, u.bh.pMem);
68087         }
68088         assert( memIsValid(u.bh.pMem) );
68089 
68090         REGISTER_TRACE(pOp->p3, u.bh.pMem);
68091         sqlite3VdbeMemIntegerify(u.bh.pMem);
68092         assert( (u.bh.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
68093         if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
68094           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
68095           goto abort_due_to_error;
68096         }
68097         if( u.bh.v<u.bh.pMem->u.i+1 ){
68098           u.bh.v = u.bh.pMem->u.i + 1;
68099         }
68100         u.bh.pMem->u.i = u.bh.v;
68101       }
68102 #endif
68103 
68104       sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
68105     }
68106     if( u.bh.pC->useRandomRowid ){
68107       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
68108       ** largest possible integer (9223372036854775807) then the database
68109       ** engine starts picking positive candidate ROWIDs at random until
68110       ** it finds one that is not previously used. */
68111       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
68112                              ** an AUTOINCREMENT table. */
68113       /* on the first attempt, simply do one more than previous */
68114       u.bh.v = lastRowid;
68115       u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68116       u.bh.v++; /* ensure non-zero */
68117       u.bh.cnt = 0;
68118       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
68119                                                  0, &u.bh.res))==SQLITE_OK)
68120             && (u.bh.res==0)
68121             && (++u.bh.cnt<100)){
68122         /* collision - try another random rowid */
68123         sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
68124         if( u.bh.cnt<5 ){
68125           /* try "small" random rowids for the initial attempts */
68126           u.bh.v &= 0xffffff;
68127         }else{
68128           u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68129         }
68130         u.bh.v++; /* ensure non-zero */
68131       }
68132       if( rc==SQLITE_OK && u.bh.res==0 ){
68133         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
68134         goto abort_due_to_error;
68135       }
68136       assert( u.bh.v>0 );  /* EV: R-40812-03570 */
68137     }
68138     u.bh.pC->rowidIsValid = 0;
68139     u.bh.pC->deferredMoveto = 0;
68140     u.bh.pC->cacheStatus = CACHE_STALE;
68141   }
68142   pOut->u.i = u.bh.v;
68143   break;
68144 }
68145 
68146 /* Opcode: Insert P1 P2 P3 P4 P5
68147 **
68148 ** Write an entry into the table of cursor P1.  A new entry is
68149 ** created if it doesn't already exist or the data for an existing
68150 ** entry is overwritten.  The data is the value MEM_Blob stored in register
68151 ** number P2. The key is stored in register P3. The key must
68152 ** be a MEM_Int.
68153 **
68154 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
68155 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
68156 ** then rowid is stored for subsequent return by the
68157 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
68158 **
68159 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
68160 ** the last seek operation (OP_NotExists) was a success, then this
68161 ** operation will not attempt to find the appropriate row before doing
68162 ** the insert but will instead overwrite the row that the cursor is
68163 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
68164 ** has already positioned the cursor correctly.  This is an optimization
68165 ** that boosts performance by avoiding redundant seeks.
68166 **
68167 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68168 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68169 ** is part of an INSERT operation.  The difference is only important to
68170 ** the update hook.
68171 **
68172 ** Parameter P4 may point to a string containing the table-name, or
68173 ** may be NULL. If it is not NULL, then the update-hook
68174 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
68175 **
68176 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68177 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
68178 ** and register P2 becomes ephemeral.  If the cursor is changed, the
68179 ** value of register P2 will then change.  Make sure this does not
68180 ** cause any problems.)
68181 **
68182 ** This instruction only works on tables.  The equivalent instruction
68183 ** for indices is OP_IdxInsert.
68184 */
68185 /* Opcode: InsertInt P1 P2 P3 P4 P5
68186 **
68187 ** This works exactly like OP_Insert except that the key is the
68188 ** integer value P3, not the value of the integer stored in register P3.
68189 */
68190 case OP_Insert:
68191 case OP_InsertInt: {
68192 #if 0  /* local variables moved into u.bi */
68193   Mem *pData;       /* MEM cell holding data for the record to be inserted */
68194   Mem *pKey;        /* MEM cell holding key  for the record */
68195   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68196   VdbeCursor *pC;   /* Cursor to table into which insert is written */
68197   int nZero;        /* Number of zero-bytes to append */
68198   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68199   const char *zDb;  /* database name - used by the update hook */
68200   const char *zTbl; /* Table name - used by the opdate hook */
68201   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
68202 #endif /* local variables moved into u.bi */
68203 
68204   u.bi.pData = &aMem[pOp->p2];
68205   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68206   assert( memIsValid(u.bi.pData) );
68207   u.bi.pC = p->apCsr[pOp->p1];
68208   assert( u.bi.pC!=0 );
68209   assert( u.bi.pC->pCursor!=0 );
68210   assert( u.bi.pC->pseudoTableReg==0 );
68211   assert( u.bi.pC->isTable );
68212   REGISTER_TRACE(pOp->p2, u.bi.pData);
68213 
68214   if( pOp->opcode==OP_Insert ){
68215     u.bi.pKey = &aMem[pOp->p3];
68216     assert( u.bi.pKey->flags & MEM_Int );
68217     assert( memIsValid(u.bi.pKey) );
68218     REGISTER_TRACE(pOp->p3, u.bi.pKey);
68219     u.bi.iKey = u.bi.pKey->u.i;
68220   }else{
68221     assert( pOp->opcode==OP_InsertInt );
68222     u.bi.iKey = pOp->p3;
68223   }
68224 
68225   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68226   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
68227   if( u.bi.pData->flags & MEM_Null ){
68228     u.bi.pData->z = 0;
68229     u.bi.pData->n = 0;
68230   }else{
68231     assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
68232   }
68233   u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
68234   if( u.bi.pData->flags & MEM_Zero ){
68235     u.bi.nZero = u.bi.pData->u.nZero;
68236   }else{
68237     u.bi.nZero = 0;
68238   }
68239   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
68240   rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
68241                           u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
68242                           pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
68243   );
68244   u.bi.pC->rowidIsValid = 0;
68245   u.bi.pC->deferredMoveto = 0;
68246   u.bi.pC->cacheStatus = CACHE_STALE;
68247 
68248   /* Invoke the update-hook if required. */
68249   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68250     u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
68251     u.bi.zTbl = pOp->p4.z;
68252     u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
68253     assert( u.bi.pC->isTable );
68254     db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
68255     assert( u.bi.pC->iDb>=0 );
68256   }
68257   break;
68258 }
68259 
68260 /* Opcode: Delete P1 P2 * P4 *
68261 **
68262 ** Delete the record at which the P1 cursor is currently pointing.
68263 **
68264 ** The cursor will be left pointing at either the next or the previous
68265 ** record in the table. If it is left pointing at the next record, then
68266 ** the next Next instruction will be a no-op.  Hence it is OK to delete
68267 ** a record from within an Next loop.
68268 **
68269 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68270 ** incremented (otherwise not).
68271 **
68272 ** P1 must not be pseudo-table.  It has to be a real table with
68273 ** multiple rows.
68274 **
68275 ** If P4 is not NULL, then it is the name of the table that P1 is
68276 ** pointing to.  The update hook will be invoked, if it exists.
68277 ** If P4 is not NULL then the P1 cursor must have been positioned
68278 ** using OP_NotFound prior to invoking this opcode.
68279 */
68280 case OP_Delete: {
68281 #if 0  /* local variables moved into u.bj */
68282   i64 iKey;
68283   VdbeCursor *pC;
68284 #endif /* local variables moved into u.bj */
68285 
68286   u.bj.iKey = 0;
68287   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68288   u.bj.pC = p->apCsr[pOp->p1];
68289   assert( u.bj.pC!=0 );
68290   assert( u.bj.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68291 
68292   /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
68293   ** row being deleted.
68294   */
68295   if( db->xUpdateCallback && pOp->p4.z ){
68296     assert( u.bj.pC->isTable );
68297     assert( u.bj.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
68298     u.bj.iKey = u.bj.pC->lastRowid;
68299   }
68300 
68301   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
68302   ** OP_Column on the same table without any intervening operations that
68303   ** might move or invalidate the cursor.  Hence cursor u.bj.pC is always pointing
68304   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
68305   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
68306   ** to guard against future changes to the code generator.
68307   **/
68308   assert( u.bj.pC->deferredMoveto==0 );
68309   rc = sqlite3VdbeCursorMoveto(u.bj.pC);
68310   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
68311 
68312   sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
68313   rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
68314   u.bj.pC->cacheStatus = CACHE_STALE;
68315 
68316   /* Invoke the update-hook if required. */
68317   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68318     const char *zDb = db->aDb[u.bj.pC->iDb].zName;
68319     const char *zTbl = pOp->p4.z;
68320     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
68321     assert( u.bj.pC->iDb>=0 );
68322   }
68323   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
68324   break;
68325 }
68326 /* Opcode: ResetCount * * * * *
68327 **
68328 ** The value of the change counter is copied to the database handle
68329 ** change counter (returned by subsequent calls to sqlite3_changes()).
68330 ** Then the VMs internal change counter resets to 0.
68331 ** This is used by trigger programs.
68332 */
68333 case OP_ResetCount: {
68334   sqlite3VdbeSetChanges(db, p->nChange);
68335   p->nChange = 0;
68336   break;
68337 }
68338 
68339 /* Opcode: SorterCompare P1 P2 P3
68340 **
68341 ** P1 is a sorter cursor. This instruction compares the record blob in
68342 ** register P3 with the entry that the sorter cursor currently points to.
68343 ** If, excluding the rowid fields at the end, the two records are a match,
68344 ** fall through to the next instruction. Otherwise, jump to instruction P2.
68345 */
68346 case OP_SorterCompare: {
68347 #if 0  /* local variables moved into u.bk */
68348   VdbeCursor *pC;
68349   int res;
68350 #endif /* local variables moved into u.bk */
68351 
68352   u.bk.pC = p->apCsr[pOp->p1];
68353   assert( isSorter(u.bk.pC) );
68354   pIn3 = &aMem[pOp->p3];
68355   rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
68356   if( u.bk.res ){
68357     pc = pOp->p2-1;
68358   }
68359   break;
68360 };
68361 
68362 /* Opcode: SorterData P1 P2 * * *
68363 **
68364 ** Write into register P2 the current sorter data for sorter cursor P1.
68365 */
68366 case OP_SorterData: {
68367 #if 0  /* local variables moved into u.bl */
68368   VdbeCursor *pC;
68369 #endif /* local variables moved into u.bl */
68370 
68371   pOut = &aMem[pOp->p2];
68372   u.bl.pC = p->apCsr[pOp->p1];
68373   assert( u.bl.pC->isSorter );
68374   rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
68375   break;
68376 }
68377 
68378 /* Opcode: RowData P1 P2 * * *
68379 **
68380 ** Write into register P2 the complete row data for cursor P1.
68381 ** There is no interpretation of the data.
68382 ** It is just copied onto the P2 register exactly as
68383 ** it is found in the database file.
68384 **
68385 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
68386 ** of a real table, not a pseudo-table.
68387 */
68388 /* Opcode: RowKey P1 P2 * * *
68389 **
68390 ** Write into register P2 the complete row key for cursor P1.
68391 ** There is no interpretation of the data.
68392 ** The key is copied onto the P3 register exactly as
68393 ** it is found in the database file.
68394 **
68395 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
68396 ** of a real table, not a pseudo-table.
68397 */
68398 case OP_RowKey:
68399 case OP_RowData: {
68400 #if 0  /* local variables moved into u.bm */
68401   VdbeCursor *pC;
68402   BtCursor *pCrsr;
68403   u32 n;
68404   i64 n64;
68405 #endif /* local variables moved into u.bm */
68406 
68407   pOut = &aMem[pOp->p2];
68408   memAboutToChange(p, pOut);
68409 
68410   /* Note that RowKey and RowData are really exactly the same instruction */
68411   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68412   u.bm.pC = p->apCsr[pOp->p1];
68413   assert( u.bm.pC->isSorter==0 );
68414   assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
68415   assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
68416   assert( u.bm.pC!=0 );
68417   assert( u.bm.pC->nullRow==0 );
68418   assert( u.bm.pC->pseudoTableReg==0 );
68419   assert( u.bm.pC->pCursor!=0 );
68420   u.bm.pCrsr = u.bm.pC->pCursor;
68421   assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
68422 
68423   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
68424   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
68425   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
68426   ** a no-op and can never fail.  But we leave it in place as a safety.
68427   */
68428   assert( u.bm.pC->deferredMoveto==0 );
68429   rc = sqlite3VdbeCursorMoveto(u.bm.pC);
68430   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
68431 
68432   if( u.bm.pC->isIndex ){
68433     assert( !u.bm.pC->isTable );
68434     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
68435     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
68436     if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68437       goto too_big;
68438     }
68439     u.bm.n = (u32)u.bm.n64;
68440   }else{
68441     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
68442     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
68443     if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
68444       goto too_big;
68445     }
68446   }
68447   if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
68448     goto no_mem;
68449   }
68450   pOut->n = u.bm.n;
68451   MemSetTypeFlag(pOut, MEM_Blob);
68452   if( u.bm.pC->isIndex ){
68453     rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
68454   }else{
68455     rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
68456   }
68457   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
68458   UPDATE_MAX_BLOBSIZE(pOut);
68459   break;
68460 }
68461 
68462 /* Opcode: Rowid P1 P2 * * *
68463 **
68464 ** Store in register P2 an integer which is the key of the table entry that
68465 ** P1 is currently point to.
68466 **
68467 ** P1 can be either an ordinary table or a virtual table.  There used to
68468 ** be a separate OP_VRowid opcode for use with virtual tables, but this
68469 ** one opcode now works for both table types.
68470 */
68471 case OP_Rowid: {                 /* out2-prerelease */
68472 #if 0  /* local variables moved into u.bn */
68473   VdbeCursor *pC;
68474   i64 v;
68475   sqlite3_vtab *pVtab;
68476   const sqlite3_module *pModule;
68477 #endif /* local variables moved into u.bn */
68478 
68479   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68480   u.bn.pC = p->apCsr[pOp->p1];
68481   assert( u.bn.pC!=0 );
68482   assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
68483   if( u.bn.pC->nullRow ){
68484     pOut->flags = MEM_Null;
68485     break;
68486   }else if( u.bn.pC->deferredMoveto ){
68487     u.bn.v = u.bn.pC->movetoTarget;
68488 #ifndef SQLITE_OMIT_VIRTUALTABLE
68489   }else if( u.bn.pC->pVtabCursor ){
68490     u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
68491     u.bn.pModule = u.bn.pVtab->pModule;
68492     assert( u.bn.pModule->xRowid );
68493     rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
68494     importVtabErrMsg(p, u.bn.pVtab);
68495 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68496   }else{
68497     assert( u.bn.pC->pCursor!=0 );
68498     rc = sqlite3VdbeCursorMoveto(u.bn.pC);
68499     if( rc ) goto abort_due_to_error;
68500     if( u.bn.pC->rowidIsValid ){
68501       u.bn.v = u.bn.pC->lastRowid;
68502     }else{
68503       rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
68504       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
68505     }
68506   }
68507   pOut->u.i = u.bn.v;
68508   break;
68509 }
68510 
68511 /* Opcode: NullRow P1 * * * *
68512 **
68513 ** Move the cursor P1 to a null row.  Any OP_Column operations
68514 ** that occur while the cursor is on the null row will always
68515 ** write a NULL.
68516 */
68517 case OP_NullRow: {
68518 #if 0  /* local variables moved into u.bo */
68519   VdbeCursor *pC;
68520 #endif /* local variables moved into u.bo */
68521 
68522   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68523   u.bo.pC = p->apCsr[pOp->p1];
68524   assert( u.bo.pC!=0 );
68525   u.bo.pC->nullRow = 1;
68526   u.bo.pC->rowidIsValid = 0;
68527   assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
68528   if( u.bo.pC->pCursor ){
68529     sqlite3BtreeClearCursor(u.bo.pC->pCursor);
68530   }
68531   break;
68532 }
68533 
68534 /* Opcode: Last P1 P2 * * *
68535 **
68536 ** The next use of the Rowid or Column or Next instruction for P1
68537 ** will refer to the last entry in the database table or index.
68538 ** If the table or index is empty and P2>0, then jump immediately to P2.
68539 ** If P2 is 0 or if the table or index is not empty, fall through
68540 ** to the following instruction.
68541 */
68542 case OP_Last: {        /* jump */
68543 #if 0  /* local variables moved into u.bp */
68544   VdbeCursor *pC;
68545   BtCursor *pCrsr;
68546   int res;
68547 #endif /* local variables moved into u.bp */
68548 
68549   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68550   u.bp.pC = p->apCsr[pOp->p1];
68551   assert( u.bp.pC!=0 );
68552   u.bp.pCrsr = u.bp.pC->pCursor;
68553   u.bp.res = 0;
68554   if( ALWAYS(u.bp.pCrsr!=0) ){
68555     rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
68556   }
68557   u.bp.pC->nullRow = (u8)u.bp.res;
68558   u.bp.pC->deferredMoveto = 0;
68559   u.bp.pC->rowidIsValid = 0;
68560   u.bp.pC->cacheStatus = CACHE_STALE;
68561   if( pOp->p2>0 && u.bp.res ){
68562     pc = pOp->p2 - 1;
68563   }
68564   break;
68565 }
68566 
68567 
68568 /* Opcode: Sort P1 P2 * * *
68569 **
68570 ** This opcode does exactly the same thing as OP_Rewind except that
68571 ** it increments an undocumented global variable used for testing.
68572 **
68573 ** Sorting is accomplished by writing records into a sorting index,
68574 ** then rewinding that index and playing it back from beginning to
68575 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
68576 ** rewinding so that the global variable will be incremented and
68577 ** regression tests can determine whether or not the optimizer is
68578 ** correctly optimizing out sorts.
68579 */
68580 case OP_SorterSort:    /* jump */
68581 case OP_Sort: {        /* jump */
68582 #ifdef SQLITE_TEST
68583   sqlite3_sort_count++;
68584   sqlite3_search_count--;
68585 #endif
68586   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
68587   /* Fall through into OP_Rewind */
68588 }
68589 /* Opcode: Rewind P1 P2 * * *
68590 **
68591 ** The next use of the Rowid or Column or Next instruction for P1
68592 ** will refer to the first entry in the database table or index.
68593 ** If the table or index is empty and P2>0, then jump immediately to P2.
68594 ** If P2 is 0 or if the table or index is not empty, fall through
68595 ** to the following instruction.
68596 */
68597 case OP_Rewind: {        /* jump */
68598 #if 0  /* local variables moved into u.bq */
68599   VdbeCursor *pC;
68600   BtCursor *pCrsr;
68601   int res;
68602 #endif /* local variables moved into u.bq */
68603 
68604   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68605   u.bq.pC = p->apCsr[pOp->p1];
68606   assert( u.bq.pC!=0 );
68607   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
68608   u.bq.res = 1;
68609   if( isSorter(u.bq.pC) ){
68610     rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
68611   }else{
68612     u.bq.pCrsr = u.bq.pC->pCursor;
68613     assert( u.bq.pCrsr );
68614     rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
68615     u.bq.pC->atFirst = u.bq.res==0 ?1:0;
68616     u.bq.pC->deferredMoveto = 0;
68617     u.bq.pC->cacheStatus = CACHE_STALE;
68618     u.bq.pC->rowidIsValid = 0;
68619   }
68620   u.bq.pC->nullRow = (u8)u.bq.res;
68621   assert( pOp->p2>0 && pOp->p2<p->nOp );
68622   if( u.bq.res ){
68623     pc = pOp->p2 - 1;
68624   }
68625   break;
68626 }
68627 
68628 /* Opcode: Next P1 P2 * P4 P5
68629 **
68630 ** Advance cursor P1 so that it points to the next key/data pair in its
68631 ** table or index.  If there are no more key/value pairs then fall through
68632 ** to the following instruction.  But if the cursor advance was successful,
68633 ** jump immediately to P2.
68634 **
68635 ** The P1 cursor must be for a real table, not a pseudo-table.
68636 **
68637 ** P4 is always of type P4_ADVANCE. The function pointer points to
68638 ** sqlite3BtreeNext().
68639 **
68640 ** If P5 is positive and the jump is taken, then event counter
68641 ** number P5-1 in the prepared statement is incremented.
68642 **
68643 ** See also: Prev
68644 */
68645 /* Opcode: Prev P1 P2 * * P5
68646 **
68647 ** Back up cursor P1 so that it points to the previous key/data pair in its
68648 ** table or index.  If there is no previous key/value pairs then fall through
68649 ** to the following instruction.  But if the cursor backup was successful,
68650 ** jump immediately to P2.
68651 **
68652 ** The P1 cursor must be for a real table, not a pseudo-table.
68653 **
68654 ** P4 is always of type P4_ADVANCE. The function pointer points to
68655 ** sqlite3BtreePrevious().
68656 **
68657 ** If P5 is positive and the jump is taken, then event counter
68658 ** number P5-1 in the prepared statement is incremented.
68659 */
68660 case OP_SorterNext:    /* jump */
68661 case OP_Prev:          /* jump */
68662 case OP_Next: {        /* jump */
68663 #if 0  /* local variables moved into u.br */
68664   VdbeCursor *pC;
68665   int res;
68666 #endif /* local variables moved into u.br */
68667 
68668   CHECK_FOR_INTERRUPT;
68669   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68670   assert( pOp->p5<=ArraySize(p->aCounter) );
68671   u.br.pC = p->apCsr[pOp->p1];
68672   if( u.br.pC==0 ){
68673     break;  /* See ticket #2273 */
68674   }
68675   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
68676   if( isSorter(u.br.pC) ){
68677     assert( pOp->opcode==OP_SorterNext );
68678     rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
68679   }else{
68680     u.br.res = 1;
68681     assert( u.br.pC->deferredMoveto==0 );
68682     assert( u.br.pC->pCursor );
68683     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
68684     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
68685     rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
68686   }
68687   u.br.pC->nullRow = (u8)u.br.res;
68688   u.br.pC->cacheStatus = CACHE_STALE;
68689   if( u.br.res==0 ){
68690     pc = pOp->p2 - 1;
68691     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
68692 #ifdef SQLITE_TEST
68693     sqlite3_search_count++;
68694 #endif
68695   }
68696   u.br.pC->rowidIsValid = 0;
68697   break;
68698 }
68699 
68700 /* Opcode: IdxInsert P1 P2 P3 * P5
68701 **
68702 ** Register P2 holds an SQL index key made using the
68703 ** MakeRecord instructions.  This opcode writes that key
68704 ** into the index P1.  Data for the entry is nil.
68705 **
68706 ** P3 is a flag that provides a hint to the b-tree layer that this
68707 ** insert is likely to be an append.
68708 **
68709 ** This instruction only works for indices.  The equivalent instruction
68710 ** for tables is OP_Insert.
68711 */
68712 case OP_SorterInsert:       /* in2 */
68713 case OP_IdxInsert: {        /* in2 */
68714 #if 0  /* local variables moved into u.bs */
68715   VdbeCursor *pC;
68716   BtCursor *pCrsr;
68717   int nKey;
68718   const char *zKey;
68719 #endif /* local variables moved into u.bs */
68720 
68721   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68722   u.bs.pC = p->apCsr[pOp->p1];
68723   assert( u.bs.pC!=0 );
68724   assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
68725   pIn2 = &aMem[pOp->p2];
68726   assert( pIn2->flags & MEM_Blob );
68727   u.bs.pCrsr = u.bs.pC->pCursor;
68728   if( ALWAYS(u.bs.pCrsr!=0) ){
68729     assert( u.bs.pC->isTable==0 );
68730     rc = ExpandBlob(pIn2);
68731     if( rc==SQLITE_OK ){
68732       if( isSorter(u.bs.pC) ){
68733         rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
68734       }else{
68735         u.bs.nKey = pIn2->n;
68736         u.bs.zKey = pIn2->z;
68737         rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
68738             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
68739             );
68740         assert( u.bs.pC->deferredMoveto==0 );
68741         u.bs.pC->cacheStatus = CACHE_STALE;
68742       }
68743     }
68744   }
68745   break;
68746 }
68747 
68748 /* Opcode: IdxDelete P1 P2 P3 * *
68749 **
68750 ** The content of P3 registers starting at register P2 form
68751 ** an unpacked index key. This opcode removes that entry from the
68752 ** index opened by cursor P1.
68753 */
68754 case OP_IdxDelete: {
68755 #if 0  /* local variables moved into u.bt */
68756   VdbeCursor *pC;
68757   BtCursor *pCrsr;
68758   int res;
68759   UnpackedRecord r;
68760 #endif /* local variables moved into u.bt */
68761 
68762   assert( pOp->p3>0 );
68763   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
68764   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68765   u.bt.pC = p->apCsr[pOp->p1];
68766   assert( u.bt.pC!=0 );
68767   u.bt.pCrsr = u.bt.pC->pCursor;
68768   if( ALWAYS(u.bt.pCrsr!=0) ){
68769     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
68770     u.bt.r.nField = (u16)pOp->p3;
68771     u.bt.r.flags = 0;
68772     u.bt.r.aMem = &aMem[pOp->p2];
68773 #ifdef SQLITE_DEBUG
68774     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
68775 #endif
68776     rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
68777     if( rc==SQLITE_OK && u.bt.res==0 ){
68778       rc = sqlite3BtreeDelete(u.bt.pCrsr);
68779     }
68780     assert( u.bt.pC->deferredMoveto==0 );
68781     u.bt.pC->cacheStatus = CACHE_STALE;
68782   }
68783   break;
68784 }
68785 
68786 /* Opcode: IdxRowid P1 P2 * * *
68787 **
68788 ** Write into register P2 an integer which is the last entry in the record at
68789 ** the end of the index key pointed to by cursor P1.  This integer should be
68790 ** the rowid of the table entry to which this index entry points.
68791 **
68792 ** See also: Rowid, MakeRecord.
68793 */
68794 case OP_IdxRowid: {              /* out2-prerelease */
68795 #if 0  /* local variables moved into u.bu */
68796   BtCursor *pCrsr;
68797   VdbeCursor *pC;
68798   i64 rowid;
68799 #endif /* local variables moved into u.bu */
68800 
68801   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68802   u.bu.pC = p->apCsr[pOp->p1];
68803   assert( u.bu.pC!=0 );
68804   u.bu.pCrsr = u.bu.pC->pCursor;
68805   pOut->flags = MEM_Null;
68806   if( ALWAYS(u.bu.pCrsr!=0) ){
68807     rc = sqlite3VdbeCursorMoveto(u.bu.pC);
68808     if( NEVER(rc) ) goto abort_due_to_error;
68809     assert( u.bu.pC->deferredMoveto==0 );
68810     assert( u.bu.pC->isTable==0 );
68811     if( !u.bu.pC->nullRow ){
68812       rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
68813       if( rc!=SQLITE_OK ){
68814         goto abort_due_to_error;
68815       }
68816       pOut->u.i = u.bu.rowid;
68817       pOut->flags = MEM_Int;
68818     }
68819   }
68820   break;
68821 }
68822 
68823 /* Opcode: IdxGE P1 P2 P3 P4 P5
68824 **
68825 ** The P4 register values beginning with P3 form an unpacked index
68826 ** key that omits the ROWID.  Compare this key value against the index
68827 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68828 **
68829 ** If the P1 index entry is greater than or equal to the key value
68830 ** then jump to P2.  Otherwise fall through to the next instruction.
68831 **
68832 ** If P5 is non-zero then the key value is increased by an epsilon
68833 ** prior to the comparison.  This make the opcode work like IdxGT except
68834 ** that if the key from register P3 is a prefix of the key in the cursor,
68835 ** the result is false whereas it would be true with IdxGT.
68836 */
68837 /* Opcode: IdxLT P1 P2 P3 P4 P5
68838 **
68839 ** The P4 register values beginning with P3 form an unpacked index
68840 ** key that omits the ROWID.  Compare this key value against the index
68841 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68842 **
68843 ** If the P1 index entry is less than the key value then jump to P2.
68844 ** Otherwise fall through to the next instruction.
68845 **
68846 ** If P5 is non-zero then the key value is increased by an epsilon prior
68847 ** to the comparison.  This makes the opcode work like IdxLE.
68848 */
68849 case OP_IdxLT:          /* jump */
68850 case OP_IdxGE: {        /* jump */
68851 #if 0  /* local variables moved into u.bv */
68852   VdbeCursor *pC;
68853   int res;
68854   UnpackedRecord r;
68855 #endif /* local variables moved into u.bv */
68856 
68857   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68858   u.bv.pC = p->apCsr[pOp->p1];
68859   assert( u.bv.pC!=0 );
68860   assert( u.bv.pC->isOrdered );
68861   if( ALWAYS(u.bv.pC->pCursor!=0) ){
68862     assert( u.bv.pC->deferredMoveto==0 );
68863     assert( pOp->p5==0 || pOp->p5==1 );
68864     assert( pOp->p4type==P4_INT32 );
68865     u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
68866     u.bv.r.nField = (u16)pOp->p4.i;
68867     if( pOp->p5 ){
68868       u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
68869     }else{
68870       u.bv.r.flags = UNPACKED_PREFIX_MATCH;
68871     }
68872     u.bv.r.aMem = &aMem[pOp->p3];
68873 #ifdef SQLITE_DEBUG
68874     { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
68875 #endif
68876     rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
68877     if( pOp->opcode==OP_IdxLT ){
68878       u.bv.res = -u.bv.res;
68879     }else{
68880       assert( pOp->opcode==OP_IdxGE );
68881       u.bv.res++;
68882     }
68883     if( u.bv.res>0 ){
68884       pc = pOp->p2 - 1 ;
68885     }
68886   }
68887   break;
68888 }
68889 
68890 /* Opcode: Destroy P1 P2 P3 * *
68891 **
68892 ** Delete an entire database table or index whose root page in the database
68893 ** file is given by P1.
68894 **
68895 ** The table being destroyed is in the main database file if P3==0.  If
68896 ** P3==1 then the table to be clear is in the auxiliary database file
68897 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68898 **
68899 ** If AUTOVACUUM is enabled then it is possible that another root page
68900 ** might be moved into the newly deleted root page in order to keep all
68901 ** root pages contiguous at the beginning of the database.  The former
68902 ** value of the root page that moved - its value before the move occurred -
68903 ** is stored in register P2.  If no page
68904 ** movement was required (because the table being dropped was already
68905 ** the last one in the database) then a zero is stored in register P2.
68906 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
68907 **
68908 ** See also: Clear
68909 */
68910 case OP_Destroy: {     /* out2-prerelease */
68911 #if 0  /* local variables moved into u.bw */
68912   int iMoved;
68913   int iCnt;
68914   Vdbe *pVdbe;
68915   int iDb;
68916 #endif /* local variables moved into u.bw */
68917 
68918 #ifndef SQLITE_OMIT_VIRTUALTABLE
68919   u.bw.iCnt = 0;
68920   for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
68921     if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
68922       u.bw.iCnt++;
68923     }
68924   }
68925 #else
68926   u.bw.iCnt = db->activeVdbeCnt;
68927 #endif
68928   pOut->flags = MEM_Null;
68929   if( u.bw.iCnt>1 ){
68930     rc = SQLITE_LOCKED;
68931     p->errorAction = OE_Abort;
68932   }else{
68933     u.bw.iDb = pOp->p3;
68934     assert( u.bw.iCnt==1 );
68935     assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
68936     rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
68937     pOut->flags = MEM_Int;
68938     pOut->u.i = u.bw.iMoved;
68939 #ifndef SQLITE_OMIT_AUTOVACUUM
68940     if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
68941       sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
68942       /* All OP_Destroy operations occur on the same btree */
68943       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
68944       resetSchemaOnFault = u.bw.iDb+1;
68945     }
68946 #endif
68947   }
68948   break;
68949 }
68950 
68951 /* Opcode: Clear P1 P2 P3
68952 **
68953 ** Delete all contents of the database table or index whose root page
68954 ** in the database file is given by P1.  But, unlike Destroy, do not
68955 ** remove the table or index from the database file.
68956 **
68957 ** The table being clear is in the main database file if P2==0.  If
68958 ** P2==1 then the table to be clear is in the auxiliary database file
68959 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68960 **
68961 ** If the P3 value is non-zero, then the table referred to must be an
68962 ** intkey table (an SQL table, not an index). In this case the row change
68963 ** count is incremented by the number of rows in the table being cleared.
68964 ** If P3 is greater than zero, then the value stored in register P3 is
68965 ** also incremented by the number of rows in the table being cleared.
68966 **
68967 ** See also: Destroy
68968 */
68969 case OP_Clear: {
68970 #if 0  /* local variables moved into u.bx */
68971   int nChange;
68972 #endif /* local variables moved into u.bx */
68973 
68974   u.bx.nChange = 0;
68975   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
68976   rc = sqlite3BtreeClearTable(
68977       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
68978   );
68979   if( pOp->p3 ){
68980     p->nChange += u.bx.nChange;
68981     if( pOp->p3>0 ){
68982       assert( memIsValid(&aMem[pOp->p3]) );
68983       memAboutToChange(p, &aMem[pOp->p3]);
68984       aMem[pOp->p3].u.i += u.bx.nChange;
68985     }
68986   }
68987   break;
68988 }
68989 
68990 /* Opcode: CreateTable P1 P2 * * *
68991 **
68992 ** Allocate a new table in the main database file if P1==0 or in the
68993 ** auxiliary database file if P1==1 or in an attached database if
68994 ** P1>1.  Write the root page number of the new table into
68995 ** register P2
68996 **
68997 ** The difference between a table and an index is this:  A table must
68998 ** have a 4-byte integer key and can have arbitrary data.  An index
68999 ** has an arbitrary key but no data.
69000 **
69001 ** See also: CreateIndex
69002 */
69003 /* Opcode: CreateIndex P1 P2 * * *
69004 **
69005 ** Allocate a new index in the main database file if P1==0 or in the
69006 ** auxiliary database file if P1==1 or in an attached database if
69007 ** P1>1.  Write the root page number of the new table into
69008 ** register P2.
69009 **
69010 ** See documentation on OP_CreateTable for additional information.
69011 */
69012 case OP_CreateIndex:            /* out2-prerelease */
69013 case OP_CreateTable: {          /* out2-prerelease */
69014 #if 0  /* local variables moved into u.by */
69015   int pgno;
69016   int flags;
69017   Db *pDb;
69018 #endif /* local variables moved into u.by */
69019 
69020   u.by.pgno = 0;
69021   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69022   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69023   u.by.pDb = &db->aDb[pOp->p1];
69024   assert( u.by.pDb->pBt!=0 );
69025   if( pOp->opcode==OP_CreateTable ){
69026     /* u.by.flags = BTREE_INTKEY; */
69027     u.by.flags = BTREE_INTKEY;
69028   }else{
69029     u.by.flags = BTREE_BLOBKEY;
69030   }
69031   rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
69032   pOut->u.i = u.by.pgno;
69033   break;
69034 }
69035 
69036 /* Opcode: ParseSchema P1 * * P4 *
69037 **
69038 ** Read and parse all entries from the SQLITE_MASTER table of database P1
69039 ** that match the WHERE clause P4.
69040 **
69041 ** This opcode invokes the parser to create a new virtual machine,
69042 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
69043 */
69044 case OP_ParseSchema: {
69045 #if 0  /* local variables moved into u.bz */
69046   int iDb;
69047   const char *zMaster;
69048   char *zSql;
69049   InitData initData;
69050 #endif /* local variables moved into u.bz */
69051 
69052   /* Any prepared statement that invokes this opcode will hold mutexes
69053   ** on every btree.  This is a prerequisite for invoking
69054   ** sqlite3InitCallback().
69055   */
69056 #ifdef SQLITE_DEBUG
69057   for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
69058     assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
69059   }
69060 #endif
69061 
69062   u.bz.iDb = pOp->p1;
69063   assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
69064   assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
69065   /* Used to be a conditional */ {
69066     u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
69067     u.bz.initData.db = db;
69068     u.bz.initData.iDb = pOp->p1;
69069     u.bz.initData.pzErrMsg = &p->zErrMsg;
69070     u.bz.zSql = sqlite3MPrintf(db,
69071        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
69072        db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
69073     if( u.bz.zSql==0 ){
69074       rc = SQLITE_NOMEM;
69075     }else{
69076       assert( db->init.busy==0 );
69077       db->init.busy = 1;
69078       u.bz.initData.rc = SQLITE_OK;
69079       assert( !db->mallocFailed );
69080       rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
69081       if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
69082       sqlite3DbFree(db, u.bz.zSql);
69083       db->init.busy = 0;
69084     }
69085   }
69086   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
69087   if( rc==SQLITE_NOMEM ){
69088     goto no_mem;
69089   }
69090   break;
69091 }
69092 
69093 #if !defined(SQLITE_OMIT_ANALYZE)
69094 /* Opcode: LoadAnalysis P1 * * * *
69095 **
69096 ** Read the sqlite_stat1 table for database P1 and load the content
69097 ** of that table into the internal index hash table.  This will cause
69098 ** the analysis to be used when preparing all subsequent queries.
69099 */
69100 case OP_LoadAnalysis: {
69101   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69102   rc = sqlite3AnalysisLoad(db, pOp->p1);
69103   break;
69104 }
69105 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
69106 
69107 /* Opcode: DropTable P1 * * P4 *
69108 **
69109 ** Remove the internal (in-memory) data structures that describe
69110 ** the table named P4 in database P1.  This is called after a table
69111 ** is dropped in order to keep the internal representation of the
69112 ** schema consistent with what is on disk.
69113 */
69114 case OP_DropTable: {
69115   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
69116   break;
69117 }
69118 
69119 /* Opcode: DropIndex P1 * * P4 *
69120 **
69121 ** Remove the internal (in-memory) data structures that describe
69122 ** the index named P4 in database P1.  This is called after an index
69123 ** is dropped in order to keep the internal representation of the
69124 ** schema consistent with what is on disk.
69125 */
69126 case OP_DropIndex: {
69127   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
69128   break;
69129 }
69130 
69131 /* Opcode: DropTrigger P1 * * P4 *
69132 **
69133 ** Remove the internal (in-memory) data structures that describe
69134 ** the trigger named P4 in database P1.  This is called after a trigger
69135 ** is dropped in order to keep the internal representation of the
69136 ** schema consistent with what is on disk.
69137 */
69138 case OP_DropTrigger: {
69139   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
69140   break;
69141 }
69142 
69143 
69144 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
69145 /* Opcode: IntegrityCk P1 P2 P3 * P5
69146 **
69147 ** Do an analysis of the currently open database.  Store in
69148 ** register P1 the text of an error message describing any problems.
69149 ** If no problems are found, store a NULL in register P1.
69150 **
69151 ** The register P3 contains the maximum number of allowed errors.
69152 ** At most reg(P3) errors will be reported.
69153 ** In other words, the analysis stops as soon as reg(P1) errors are
69154 ** seen.  Reg(P1) is updated with the number of errors remaining.
69155 **
69156 ** The root page numbers of all tables in the database are integer
69157 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69158 ** total.
69159 **
69160 ** If P5 is not zero, the check is done on the auxiliary database
69161 ** file, not the main database file.
69162 **
69163 ** This opcode is used to implement the integrity_check pragma.
69164 */
69165 case OP_IntegrityCk: {
69166 #if 0  /* local variables moved into u.ca */
69167   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69168   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69169   int j;          /* Loop counter */
69170   int nErr;       /* Number of errors reported */
69171   char *z;        /* Text of the error report */
69172   Mem *pnErr;     /* Register keeping track of errors remaining */
69173 #endif /* local variables moved into u.ca */
69174 
69175   u.ca.nRoot = pOp->p2;
69176   assert( u.ca.nRoot>0 );
69177   u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
69178   if( u.ca.aRoot==0 ) goto no_mem;
69179   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69180   u.ca.pnErr = &aMem[pOp->p3];
69181   assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
69182   assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69183   pIn1 = &aMem[pOp->p1];
69184   for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
69185     u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
69186   }
69187   u.ca.aRoot[u.ca.j] = 0;
69188   assert( pOp->p5<db->nDb );
69189   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69190   u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
69191                                  (int)u.ca.pnErr->u.i, &u.ca.nErr);
69192   sqlite3DbFree(db, u.ca.aRoot);
69193   u.ca.pnErr->u.i -= u.ca.nErr;
69194   sqlite3VdbeMemSetNull(pIn1);
69195   if( u.ca.nErr==0 ){
69196     assert( u.ca.z==0 );
69197   }else if( u.ca.z==0 ){
69198     goto no_mem;
69199   }else{
69200     sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
69201   }
69202   UPDATE_MAX_BLOBSIZE(pIn1);
69203   sqlite3VdbeChangeEncoding(pIn1, encoding);
69204   break;
69205 }
69206 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69207 
69208 /* Opcode: RowSetAdd P1 P2 * * *
69209 **
69210 ** Insert the integer value held by register P2 into a boolean index
69211 ** held in register P1.
69212 **
69213 ** An assertion fails if P2 is not an integer.
69214 */
69215 case OP_RowSetAdd: {       /* in1, in2 */
69216   pIn1 = &aMem[pOp->p1];
69217   pIn2 = &aMem[pOp->p2];
69218   assert( (pIn2->flags & MEM_Int)!=0 );
69219   if( (pIn1->flags & MEM_RowSet)==0 ){
69220     sqlite3VdbeMemSetRowSet(pIn1);
69221     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69222   }
69223   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69224   break;
69225 }
69226 
69227 /* Opcode: RowSetRead P1 P2 P3 * *
69228 **
69229 ** Extract the smallest value from boolean index P1 and put that value into
69230 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
69231 ** unchanged and jump to instruction P2.
69232 */
69233 case OP_RowSetRead: {       /* jump, in1, out3 */
69234 #if 0  /* local variables moved into u.cb */
69235   i64 val;
69236 #endif /* local variables moved into u.cb */
69237   CHECK_FOR_INTERRUPT;
69238   pIn1 = &aMem[pOp->p1];
69239   if( (pIn1->flags & MEM_RowSet)==0
69240    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
69241   ){
69242     /* The boolean index is empty */
69243     sqlite3VdbeMemSetNull(pIn1);
69244     pc = pOp->p2 - 1;
69245   }else{
69246     /* A value was pulled from the index */
69247     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
69248   }
69249   break;
69250 }
69251 
69252 /* Opcode: RowSetTest P1 P2 P3 P4
69253 **
69254 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
69255 ** contains a RowSet object and that RowSet object contains
69256 ** the value held in P3, jump to register P2. Otherwise, insert the
69257 ** integer in P3 into the RowSet and continue on to the
69258 ** next opcode.
69259 **
69260 ** The RowSet object is optimized for the case where successive sets
69261 ** of integers, where each set contains no duplicates. Each set
69262 ** of values is identified by a unique P4 value. The first set
69263 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69264 ** non-negative.  For non-negative values of P4 only the lower 4
69265 ** bits are significant.
69266 **
69267 ** This allows optimizations: (a) when P4==0 there is no need to test
69268 ** the rowset object for P3, as it is guaranteed not to contain it,
69269 ** (b) when P4==-1 there is no need to insert the value, as it will
69270 ** never be tested for, and (c) when a value that is part of set X is
69271 ** inserted, there is no need to search to see if the same value was
69272 ** previously inserted as part of set X (only if it was previously
69273 ** inserted as part of some other set).
69274 */
69275 case OP_RowSetTest: {                     /* jump, in1, in3 */
69276 #if 0  /* local variables moved into u.cc */
69277   int iSet;
69278   int exists;
69279 #endif /* local variables moved into u.cc */
69280 
69281   pIn1 = &aMem[pOp->p1];
69282   pIn3 = &aMem[pOp->p3];
69283   u.cc.iSet = pOp->p4.i;
69284   assert( pIn3->flags&MEM_Int );
69285 
69286   /* If there is anything other than a rowset object in memory cell P1,
69287   ** delete it now and initialize P1 with an empty rowset
69288   */
69289   if( (pIn1->flags & MEM_RowSet)==0 ){
69290     sqlite3VdbeMemSetRowSet(pIn1);
69291     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69292   }
69293 
69294   assert( pOp->p4type==P4_INT32 );
69295   assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
69296   if( u.cc.iSet ){
69297     u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
69298                                (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
69299                                pIn3->u.i);
69300     if( u.cc.exists ){
69301       pc = pOp->p2 - 1;
69302       break;
69303     }
69304   }
69305   if( u.cc.iSet>=0 ){
69306     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
69307   }
69308   break;
69309 }
69310 
69311 
69312 #ifndef SQLITE_OMIT_TRIGGER
69313 
69314 /* Opcode: Program P1 P2 P3 P4 *
69315 **
69316 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
69317 **
69318 ** P1 contains the address of the memory cell that contains the first memory
69319 ** cell in an array of values used as arguments to the sub-program. P2
69320 ** contains the address to jump to if the sub-program throws an IGNORE
69321 ** exception using the RAISE() function. Register P3 contains the address
69322 ** of a memory cell in this (the parent) VM that is used to allocate the
69323 ** memory required by the sub-vdbe at runtime.
69324 **
69325 ** P4 is a pointer to the VM containing the trigger program.
69326 */
69327 case OP_Program: {        /* jump */
69328 #if 0  /* local variables moved into u.cd */
69329   int nMem;               /* Number of memory registers for sub-program */
69330   int nByte;              /* Bytes of runtime space required for sub-program */
69331   Mem *pRt;               /* Register to allocate runtime space */
69332   Mem *pMem;              /* Used to iterate through memory cells */
69333   Mem *pEnd;              /* Last memory cell in new array */
69334   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
69335   SubProgram *pProgram;   /* Sub-program to execute */
69336   void *t;                /* Token identifying trigger */
69337 #endif /* local variables moved into u.cd */
69338 
69339   u.cd.pProgram = pOp->p4.pProgram;
69340   u.cd.pRt = &aMem[pOp->p3];
69341   assert( u.cd.pProgram->nOp>0 );
69342 
69343   /* If the p5 flag is clear, then recursive invocation of triggers is
69344   ** disabled for backwards compatibility (p5 is set if this sub-program
69345   ** is really a trigger, not a foreign key action, and the flag set
69346   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
69347   **
69348   ** It is recursive invocation of triggers, at the SQL level, that is
69349   ** disabled. In some cases a single trigger may generate more than one
69350   ** SubProgram (if the trigger may be executed with more than one different
69351   ** ON CONFLICT algorithm). SubProgram structures associated with a
69352   ** single trigger all have the same value for the SubProgram.token
69353   ** variable.  */
69354   if( pOp->p5 ){
69355     u.cd.t = u.cd.pProgram->token;
69356     for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
69357     if( u.cd.pFrame ) break;
69358   }
69359 
69360   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
69361     rc = SQLITE_ERROR;
69362     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
69363     break;
69364   }
69365 
69366   /* Register u.cd.pRt is used to store the memory required to save the state
69367   ** of the current program, and the memory required at runtime to execute
69368   ** the trigger program. If this trigger has been fired before, then u.cd.pRt
69369   ** is already allocated. Otherwise, it must be initialized.  */
69370   if( (u.cd.pRt->flags&MEM_Frame)==0 ){
69371     /* SubProgram.nMem is set to the number of memory cells used by the
69372     ** program stored in SubProgram.aOp. As well as these, one memory
69373     ** cell is required for each cursor used by the program. Set local
69374     ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
69375     */
69376     u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
69377     u.cd.nByte = ROUND8(sizeof(VdbeFrame))
69378               + u.cd.nMem * sizeof(Mem)
69379               + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
69380               + u.cd.pProgram->nOnce * sizeof(u8);
69381     u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
69382     if( !u.cd.pFrame ){
69383       goto no_mem;
69384     }
69385     sqlite3VdbeMemRelease(u.cd.pRt);
69386     u.cd.pRt->flags = MEM_Frame;
69387     u.cd.pRt->u.pFrame = u.cd.pFrame;
69388 
69389     u.cd.pFrame->v = p;
69390     u.cd.pFrame->nChildMem = u.cd.nMem;
69391     u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
69392     u.cd.pFrame->pc = pc;
69393     u.cd.pFrame->aMem = p->aMem;
69394     u.cd.pFrame->nMem = p->nMem;
69395     u.cd.pFrame->apCsr = p->apCsr;
69396     u.cd.pFrame->nCursor = p->nCursor;
69397     u.cd.pFrame->aOp = p->aOp;
69398     u.cd.pFrame->nOp = p->nOp;
69399     u.cd.pFrame->token = u.cd.pProgram->token;
69400     u.cd.pFrame->aOnceFlag = p->aOnceFlag;
69401     u.cd.pFrame->nOnceFlag = p->nOnceFlag;
69402 
69403     u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
69404     for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
69405       u.cd.pMem->flags = MEM_Invalid;
69406       u.cd.pMem->db = db;
69407     }
69408   }else{
69409     u.cd.pFrame = u.cd.pRt->u.pFrame;
69410     assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
69411     assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
69412     assert( pc==u.cd.pFrame->pc );
69413   }
69414 
69415   p->nFrame++;
69416   u.cd.pFrame->pParent = p->pFrame;
69417   u.cd.pFrame->lastRowid = lastRowid;
69418   u.cd.pFrame->nChange = p->nChange;
69419   p->nChange = 0;
69420   p->pFrame = u.cd.pFrame;
69421   p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
69422   p->nMem = u.cd.pFrame->nChildMem;
69423   p->nCursor = (u16)u.cd.pFrame->nChildCsr;
69424   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
69425   p->aOp = aOp = u.cd.pProgram->aOp;
69426   p->nOp = u.cd.pProgram->nOp;
69427   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
69428   p->nOnceFlag = u.cd.pProgram->nOnce;
69429   pc = -1;
69430   memset(p->aOnceFlag, 0, p->nOnceFlag);
69431 
69432   break;
69433 }
69434 
69435 /* Opcode: Param P1 P2 * * *
69436 **
69437 ** This opcode is only ever present in sub-programs called via the
69438 ** OP_Program instruction. Copy a value currently stored in a memory
69439 ** cell of the calling (parent) frame to cell P2 in the current frames
69440 ** address space. This is used by trigger programs to access the new.*
69441 ** and old.* values.
69442 **
69443 ** The address of the cell in the parent frame is determined by adding
69444 ** the value of the P1 argument to the value of the P1 argument to the
69445 ** calling OP_Program instruction.
69446 */
69447 case OP_Param: {           /* out2-prerelease */
69448 #if 0  /* local variables moved into u.ce */
69449   VdbeFrame *pFrame;
69450   Mem *pIn;
69451 #endif /* local variables moved into u.ce */
69452   u.ce.pFrame = p->pFrame;
69453   u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
69454   sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
69455   break;
69456 }
69457 
69458 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
69459 
69460 #ifndef SQLITE_OMIT_FOREIGN_KEY
69461 /* Opcode: FkCounter P1 P2 * * *
69462 **
69463 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
69464 ** If P1 is non-zero, the database constraint counter is incremented
69465 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
69466 ** statement counter is incremented (immediate foreign key constraints).
69467 */
69468 case OP_FkCounter: {
69469   if( pOp->p1 ){
69470     db->nDeferredCons += pOp->p2;
69471   }else{
69472     p->nFkConstraint += pOp->p2;
69473   }
69474   break;
69475 }
69476 
69477 /* Opcode: FkIfZero P1 P2 * * *
69478 **
69479 ** This opcode tests if a foreign key constraint-counter is currently zero.
69480 ** If so, jump to instruction P2. Otherwise, fall through to the next
69481 ** instruction.
69482 **
69483 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
69484 ** is zero (the one that counts deferred constraint violations). If P1 is
69485 ** zero, the jump is taken if the statement constraint-counter is zero
69486 ** (immediate foreign key constraint violations).
69487 */
69488 case OP_FkIfZero: {         /* jump */
69489   if( pOp->p1 ){
69490     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
69491   }else{
69492     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
69493   }
69494   break;
69495 }
69496 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
69497 
69498 #ifndef SQLITE_OMIT_AUTOINCREMENT
69499 /* Opcode: MemMax P1 P2 * * *
69500 **
69501 ** P1 is a register in the root frame of this VM (the root frame is
69502 ** different from the current frame if this instruction is being executed
69503 ** within a sub-program). Set the value of register P1 to the maximum of
69504 ** its current value and the value in register P2.
69505 **
69506 ** This instruction throws an error if the memory cell is not initially
69507 ** an integer.
69508 */
69509 case OP_MemMax: {        /* in2 */
69510 #if 0  /* local variables moved into u.cf */
69511   Mem *pIn1;
69512   VdbeFrame *pFrame;
69513 #endif /* local variables moved into u.cf */
69514   if( p->pFrame ){
69515     for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
69516     u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
69517   }else{
69518     u.cf.pIn1 = &aMem[pOp->p1];
69519   }
69520   assert( memIsValid(u.cf.pIn1) );
69521   sqlite3VdbeMemIntegerify(u.cf.pIn1);
69522   pIn2 = &aMem[pOp->p2];
69523   sqlite3VdbeMemIntegerify(pIn2);
69524   if( u.cf.pIn1->u.i<pIn2->u.i){
69525     u.cf.pIn1->u.i = pIn2->u.i;
69526   }
69527   break;
69528 }
69529 #endif /* SQLITE_OMIT_AUTOINCREMENT */
69530 
69531 /* Opcode: IfPos P1 P2 * * *
69532 **
69533 ** If the value of register P1 is 1 or greater, jump to P2.
69534 **
69535 ** It is illegal to use this instruction on a register that does
69536 ** not contain an integer.  An assertion fault will result if you try.
69537 */
69538 case OP_IfPos: {        /* jump, in1 */
69539   pIn1 = &aMem[pOp->p1];
69540   assert( pIn1->flags&MEM_Int );
69541   if( pIn1->u.i>0 ){
69542      pc = pOp->p2 - 1;
69543   }
69544   break;
69545 }
69546 
69547 /* Opcode: IfNeg P1 P2 * * *
69548 **
69549 ** If the value of register P1 is less than zero, jump to P2.
69550 **
69551 ** It is illegal to use this instruction on a register that does
69552 ** not contain an integer.  An assertion fault will result if you try.
69553 */
69554 case OP_IfNeg: {        /* jump, in1 */
69555   pIn1 = &aMem[pOp->p1];
69556   assert( pIn1->flags&MEM_Int );
69557   if( pIn1->u.i<0 ){
69558      pc = pOp->p2 - 1;
69559   }
69560   break;
69561 }
69562 
69563 /* Opcode: IfZero P1 P2 P3 * *
69564 **
69565 ** The register P1 must contain an integer.  Add literal P3 to the
69566 ** value in register P1.  If the result is exactly 0, jump to P2.
69567 **
69568 ** It is illegal to use this instruction on a register that does
69569 ** not contain an integer.  An assertion fault will result if you try.
69570 */
69571 case OP_IfZero: {        /* jump, in1 */
69572   pIn1 = &aMem[pOp->p1];
69573   assert( pIn1->flags&MEM_Int );
69574   pIn1->u.i += pOp->p3;
69575   if( pIn1->u.i==0 ){
69576      pc = pOp->p2 - 1;
69577   }
69578   break;
69579 }
69580 
69581 /* Opcode: AggStep * P2 P3 P4 P5
69582 **
69583 ** Execute the step function for an aggregate.  The
69584 ** function has P5 arguments.   P4 is a pointer to the FuncDef
69585 ** structure that specifies the function.  Use register
69586 ** P3 as the accumulator.
69587 **
69588 ** The P5 arguments are taken from register P2 and its
69589 ** successors.
69590 */
69591 case OP_AggStep: {
69592 #if 0  /* local variables moved into u.cg */
69593   int n;
69594   int i;
69595   Mem *pMem;
69596   Mem *pRec;
69597   sqlite3_context ctx;
69598   sqlite3_value **apVal;
69599 #endif /* local variables moved into u.cg */
69600 
69601   u.cg.n = pOp->p5;
69602   assert( u.cg.n>=0 );
69603   u.cg.pRec = &aMem[pOp->p2];
69604   u.cg.apVal = p->apArg;
69605   assert( u.cg.apVal || u.cg.n==0 );
69606   for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
69607     assert( memIsValid(u.cg.pRec) );
69608     u.cg.apVal[u.cg.i] = u.cg.pRec;
69609     memAboutToChange(p, u.cg.pRec);
69610     sqlite3VdbeMemStoreType(u.cg.pRec);
69611   }
69612   u.cg.ctx.pFunc = pOp->p4.pFunc;
69613   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69614   u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
69615   u.cg.pMem->n++;
69616   u.cg.ctx.s.flags = MEM_Null;
69617   u.cg.ctx.s.z = 0;
69618   u.cg.ctx.s.zMalloc = 0;
69619   u.cg.ctx.s.xDel = 0;
69620   u.cg.ctx.s.db = db;
69621   u.cg.ctx.isError = 0;
69622   u.cg.ctx.pColl = 0;
69623   u.cg.ctx.skipFlag = 0;
69624   if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
69625     assert( pOp>p->aOp );
69626     assert( pOp[-1].p4type==P4_COLLSEQ );
69627     assert( pOp[-1].opcode==OP_CollSeq );
69628     u.cg.ctx.pColl = pOp[-1].p4.pColl;
69629   }
69630   (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
69631   if( u.cg.ctx.isError ){
69632     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
69633     rc = u.cg.ctx.isError;
69634   }
69635   if( u.cg.ctx.skipFlag ){
69636     assert( pOp[-1].opcode==OP_CollSeq );
69637     u.cg.i = pOp[-1].p1;
69638     if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
69639   }
69640 
69641   sqlite3VdbeMemRelease(&u.cg.ctx.s);
69642 
69643   break;
69644 }
69645 
69646 /* Opcode: AggFinal P1 P2 * P4 *
69647 **
69648 ** Execute the finalizer function for an aggregate.  P1 is
69649 ** the memory location that is the accumulator for the aggregate.
69650 **
69651 ** P2 is the number of arguments that the step function takes and
69652 ** P4 is a pointer to the FuncDef for this function.  The P2
69653 ** argument is not used by this opcode.  It is only there to disambiguate
69654 ** functions that can take varying numbers of arguments.  The
69655 ** P4 argument is only needed for the degenerate case where
69656 ** the step function was not previously called.
69657 */
69658 case OP_AggFinal: {
69659 #if 0  /* local variables moved into u.ch */
69660   Mem *pMem;
69661 #endif /* local variables moved into u.ch */
69662   assert( pOp->p1>0 && pOp->p1<=p->nMem );
69663   u.ch.pMem = &aMem[pOp->p1];
69664   assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
69665   rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
69666   if( rc ){
69667     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
69668   }
69669   sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
69670   UPDATE_MAX_BLOBSIZE(u.ch.pMem);
69671   if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
69672     goto too_big;
69673   }
69674   break;
69675 }
69676 
69677 #ifndef SQLITE_OMIT_WAL
69678 /* Opcode: Checkpoint P1 P2 P3 * *
69679 **
69680 ** Checkpoint database P1. This is a no-op if P1 is not currently in
69681 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
69682 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
69683 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
69684 ** WAL after the checkpoint into mem[P3+1] and the number of pages
69685 ** in the WAL that have been checkpointed after the checkpoint
69686 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
69687 ** mem[P3+2] are initialized to -1.
69688 */
69689 case OP_Checkpoint: {
69690 #if 0  /* local variables moved into u.ci */
69691   int i;                          /* Loop counter */
69692   int aRes[3];                    /* Results */
69693   Mem *pMem;                      /* Write results here */
69694 #endif /* local variables moved into u.ci */
69695 
69696   u.ci.aRes[0] = 0;
69697   u.ci.aRes[1] = u.ci.aRes[2] = -1;
69698   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
69699        || pOp->p2==SQLITE_CHECKPOINT_FULL
69700        || pOp->p2==SQLITE_CHECKPOINT_RESTART
69701   );
69702   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
69703   if( rc==SQLITE_BUSY ){
69704     rc = SQLITE_OK;
69705     u.ci.aRes[0] = 1;
69706   }
69707   for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
69708     sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
69709   }
69710   break;
69711 };
69712 #endif
69713 
69714 #ifndef SQLITE_OMIT_PRAGMA
69715 /* Opcode: JournalMode P1 P2 P3 * P5
69716 **
69717 ** Change the journal mode of database P1 to P3. P3 must be one of the
69718 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
69719 ** modes (delete, truncate, persist, off and memory), this is a simple
69720 ** operation. No IO is required.
69721 **
69722 ** If changing into or out of WAL mode the procedure is more complicated.
69723 **
69724 ** Write a string containing the final journal-mode to register P2.
69725 */
69726 case OP_JournalMode: {    /* out2-prerelease */
69727 #if 0  /* local variables moved into u.cj */
69728   Btree *pBt;                     /* Btree to change journal mode of */
69729   Pager *pPager;                  /* Pager associated with pBt */
69730   int eNew;                       /* New journal mode */
69731   int eOld;                       /* The old journal mode */
69732 #ifndef SQLITE_OMIT_WAL
69733   const char *zFilename;          /* Name of database file for pPager */
69734 #endif
69735 #endif /* local variables moved into u.cj */
69736 
69737   u.cj.eNew = pOp->p3;
69738   assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
69739        || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
69740        || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
69741        || u.cj.eNew==PAGER_JOURNALMODE_OFF
69742        || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
69743        || u.cj.eNew==PAGER_JOURNALMODE_WAL
69744        || u.cj.eNew==PAGER_JOURNALMODE_QUERY
69745   );
69746   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69747 
69748   u.cj.pBt = db->aDb[pOp->p1].pBt;
69749   u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
69750   u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
69751   if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
69752   if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
69753 
69754 #ifndef SQLITE_OMIT_WAL
69755   u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
69756 
69757   /* Do not allow a transition to journal_mode=WAL for a database
69758   ** in temporary storage or if the VFS does not support shared memory
69759   */
69760   if( u.cj.eNew==PAGER_JOURNALMODE_WAL
69761    && (sqlite3Strlen30(u.cj.zFilename)==0           /* Temp file */
69762        || !sqlite3PagerWalSupported(u.cj.pPager))   /* No shared-memory support */
69763   ){
69764     u.cj.eNew = u.cj.eOld;
69765   }
69766 
69767   if( (u.cj.eNew!=u.cj.eOld)
69768    && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
69769   ){
69770     if( !db->autoCommit || db->activeVdbeCnt>1 ){
69771       rc = SQLITE_ERROR;
69772       sqlite3SetString(&p->zErrMsg, db,
69773           "cannot change %s wal mode from within a transaction",
69774           (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
69775       );
69776       break;
69777     }else{
69778 
69779       if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
69780         /* If leaving WAL mode, close the log file. If successful, the call
69781         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
69782         ** file. An EXCLUSIVE lock may still be held on the database file
69783         ** after a successful return.
69784         */
69785         rc = sqlite3PagerCloseWal(u.cj.pPager);
69786         if( rc==SQLITE_OK ){
69787           sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
69788         }
69789       }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
69790         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
69791         ** as an intermediate */
69792         sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
69793       }
69794 
69795       /* Open a transaction on the database file. Regardless of the journal
69796       ** mode, this transaction always uses a rollback journal.
69797       */
69798       assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
69799       if( rc==SQLITE_OK ){
69800         rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
69801       }
69802     }
69803   }
69804 #endif /* ifndef SQLITE_OMIT_WAL */
69805 
69806   if( rc ){
69807     u.cj.eNew = u.cj.eOld;
69808   }
69809   u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
69810 
69811   pOut = &aMem[pOp->p2];
69812   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
69813   pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
69814   pOut->n = sqlite3Strlen30(pOut->z);
69815   pOut->enc = SQLITE_UTF8;
69816   sqlite3VdbeChangeEncoding(pOut, encoding);
69817   break;
69818 };
69819 #endif /* SQLITE_OMIT_PRAGMA */
69820 
69821 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69822 /* Opcode: Vacuum * * * * *
69823 **
69824 ** Vacuum the entire database.  This opcode will cause other virtual
69825 ** machines to be created and run.  It may not be called from within
69826 ** a transaction.
69827 */
69828 case OP_Vacuum: {
69829   rc = sqlite3RunVacuum(&p->zErrMsg, db);
69830   break;
69831 }
69832 #endif
69833 
69834 #if !defined(SQLITE_OMIT_AUTOVACUUM)
69835 /* Opcode: IncrVacuum P1 P2 * * *
69836 **
69837 ** Perform a single step of the incremental vacuum procedure on
69838 ** the P1 database. If the vacuum has finished, jump to instruction
69839 ** P2. Otherwise, fall through to the next instruction.
69840 */
69841 case OP_IncrVacuum: {        /* jump */
69842 #if 0  /* local variables moved into u.ck */
69843   Btree *pBt;
69844 #endif /* local variables moved into u.ck */
69845 
69846   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69847   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69848   u.ck.pBt = db->aDb[pOp->p1].pBt;
69849   rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
69850   if( rc==SQLITE_DONE ){
69851     pc = pOp->p2 - 1;
69852     rc = SQLITE_OK;
69853   }
69854   break;
69855 }
69856 #endif
69857 
69858 /* Opcode: Expire P1 * * * *
69859 **
69860 ** Cause precompiled statements to become expired. An expired statement
69861 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
69862 ** (via sqlite3_step()).
69863 **
69864 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69865 ** then only the currently executing statement is affected.
69866 */
69867 case OP_Expire: {
69868   if( !pOp->p1 ){
69869     sqlite3ExpirePreparedStatements(db);
69870   }else{
69871     p->expired = 1;
69872   }
69873   break;
69874 }
69875 
69876 #ifndef SQLITE_OMIT_SHARED_CACHE
69877 /* Opcode: TableLock P1 P2 P3 P4 *
69878 **
69879 ** Obtain a lock on a particular table. This instruction is only used when
69880 ** the shared-cache feature is enabled.
69881 **
69882 ** P1 is the index of the database in sqlite3.aDb[] of the database
69883 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
69884 ** a write lock if P3==1.
69885 **
69886 ** P2 contains the root-page of the table to lock.
69887 **
69888 ** P4 contains a pointer to the name of the table being locked. This is only
69889 ** used to generate an error message if the lock cannot be obtained.
69890 */
69891 case OP_TableLock: {
69892   u8 isWriteLock = (u8)pOp->p3;
69893   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
69894     int p1 = pOp->p1;
69895     assert( p1>=0 && p1<db->nDb );
69896     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
69897     assert( isWriteLock==0 || isWriteLock==1 );
69898     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69899     if( (rc&0xFF)==SQLITE_LOCKED ){
69900       const char *z = pOp->p4.z;
69901       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
69902     }
69903   }
69904   break;
69905 }
69906 #endif /* SQLITE_OMIT_SHARED_CACHE */
69907 
69908 #ifndef SQLITE_OMIT_VIRTUALTABLE
69909 /* Opcode: VBegin * * * P4 *
69910 **
69911 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
69912 ** xBegin method for that table.
69913 **
69914 ** Also, whether or not P4 is set, check that this is not being called from
69915 ** within a callback to a virtual table xSync() method. If it is, the error
69916 ** code will be set to SQLITE_LOCKED.
69917 */
69918 case OP_VBegin: {
69919 #if 0  /* local variables moved into u.cl */
69920   VTable *pVTab;
69921 #endif /* local variables moved into u.cl */
69922   u.cl.pVTab = pOp->p4.pVtab;
69923   rc = sqlite3VtabBegin(db, u.cl.pVTab);
69924   if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
69925   break;
69926 }
69927 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69928 
69929 #ifndef SQLITE_OMIT_VIRTUALTABLE
69930 /* Opcode: VCreate P1 * * P4 *
69931 **
69932 ** P4 is the name of a virtual table in database P1. Call the xCreate method
69933 ** for that table.
69934 */
69935 case OP_VCreate: {
69936   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
69937   break;
69938 }
69939 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69940 
69941 #ifndef SQLITE_OMIT_VIRTUALTABLE
69942 /* Opcode: VDestroy P1 * * P4 *
69943 **
69944 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
69945 ** of that table.
69946 */
69947 case OP_VDestroy: {
69948   p->inVtabMethod = 2;
69949   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
69950   p->inVtabMethod = 0;
69951   break;
69952 }
69953 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69954 
69955 #ifndef SQLITE_OMIT_VIRTUALTABLE
69956 /* Opcode: VOpen P1 * * P4 *
69957 **
69958 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69959 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
69960 ** table and stores that cursor in P1.
69961 */
69962 case OP_VOpen: {
69963 #if 0  /* local variables moved into u.cm */
69964   VdbeCursor *pCur;
69965   sqlite3_vtab_cursor *pVtabCursor;
69966   sqlite3_vtab *pVtab;
69967   sqlite3_module *pModule;
69968 #endif /* local variables moved into u.cm */
69969 
69970   u.cm.pCur = 0;
69971   u.cm.pVtabCursor = 0;
69972   u.cm.pVtab = pOp->p4.pVtab->pVtab;
69973   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
69974   assert(u.cm.pVtab && u.cm.pModule);
69975   rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
69976   importVtabErrMsg(p, u.cm.pVtab);
69977   if( SQLITE_OK==rc ){
69978     /* Initialize sqlite3_vtab_cursor base class */
69979     u.cm.pVtabCursor->pVtab = u.cm.pVtab;
69980 
69981     /* Initialize vdbe cursor object */
69982     u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
69983     if( u.cm.pCur ){
69984       u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
69985       u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
69986     }else{
69987       db->mallocFailed = 1;
69988       u.cm.pModule->xClose(u.cm.pVtabCursor);
69989     }
69990   }
69991   break;
69992 }
69993 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69994 
69995 #ifndef SQLITE_OMIT_VIRTUALTABLE
69996 /* Opcode: VFilter P1 P2 P3 P4 *
69997 **
69998 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
69999 ** the filtered result set is empty.
70000 **
70001 ** P4 is either NULL or a string that was generated by the xBestIndex
70002 ** method of the module.  The interpretation of the P4 string is left
70003 ** to the module implementation.
70004 **
70005 ** This opcode invokes the xFilter method on the virtual table specified
70006 ** by P1.  The integer query plan parameter to xFilter is stored in register
70007 ** P3. Register P3+1 stores the argc parameter to be passed to the
70008 ** xFilter method. Registers P3+2..P3+1+argc are the argc
70009 ** additional parameters which are passed to
70010 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
70011 **
70012 ** A jump is made to P2 if the result set after filtering would be empty.
70013 */
70014 case OP_VFilter: {   /* jump */
70015 #if 0  /* local variables moved into u.cn */
70016   int nArg;
70017   int iQuery;
70018   const sqlite3_module *pModule;
70019   Mem *pQuery;
70020   Mem *pArgc;
70021   sqlite3_vtab_cursor *pVtabCursor;
70022   sqlite3_vtab *pVtab;
70023   VdbeCursor *pCur;
70024   int res;
70025   int i;
70026   Mem **apArg;
70027 #endif /* local variables moved into u.cn */
70028 
70029   u.cn.pQuery = &aMem[pOp->p3];
70030   u.cn.pArgc = &u.cn.pQuery[1];
70031   u.cn.pCur = p->apCsr[pOp->p1];
70032   assert( memIsValid(u.cn.pQuery) );
70033   REGISTER_TRACE(pOp->p3, u.cn.pQuery);
70034   assert( u.cn.pCur->pVtabCursor );
70035   u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
70036   u.cn.pVtab = u.cn.pVtabCursor->pVtab;
70037   u.cn.pModule = u.cn.pVtab->pModule;
70038 
70039   /* Grab the index number and argc parameters */
70040   assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
70041   u.cn.nArg = (int)u.cn.pArgc->u.i;
70042   u.cn.iQuery = (int)u.cn.pQuery->u.i;
70043 
70044   /* Invoke the xFilter method */
70045   {
70046     u.cn.res = 0;
70047     u.cn.apArg = p->apArg;
70048     for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
70049       u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
70050       sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
70051     }
70052 
70053     p->inVtabMethod = 1;
70054     rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
70055     p->inVtabMethod = 0;
70056     importVtabErrMsg(p, u.cn.pVtab);
70057     if( rc==SQLITE_OK ){
70058       u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
70059     }
70060 
70061     if( u.cn.res ){
70062       pc = pOp->p2 - 1;
70063     }
70064   }
70065   u.cn.pCur->nullRow = 0;
70066 
70067   break;
70068 }
70069 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70070 
70071 #ifndef SQLITE_OMIT_VIRTUALTABLE
70072 /* Opcode: VColumn P1 P2 P3 * *
70073 **
70074 ** Store the value of the P2-th column of
70075 ** the row of the virtual-table that the
70076 ** P1 cursor is pointing to into register P3.
70077 */
70078 case OP_VColumn: {
70079 #if 0  /* local variables moved into u.co */
70080   sqlite3_vtab *pVtab;
70081   const sqlite3_module *pModule;
70082   Mem *pDest;
70083   sqlite3_context sContext;
70084 #endif /* local variables moved into u.co */
70085 
70086   VdbeCursor *pCur = p->apCsr[pOp->p1];
70087   assert( pCur->pVtabCursor );
70088   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70089   u.co.pDest = &aMem[pOp->p3];
70090   memAboutToChange(p, u.co.pDest);
70091   if( pCur->nullRow ){
70092     sqlite3VdbeMemSetNull(u.co.pDest);
70093     break;
70094   }
70095   u.co.pVtab = pCur->pVtabCursor->pVtab;
70096   u.co.pModule = u.co.pVtab->pModule;
70097   assert( u.co.pModule->xColumn );
70098   memset(&u.co.sContext, 0, sizeof(u.co.sContext));
70099 
70100   /* The output cell may already have a buffer allocated. Move
70101   ** the current contents to u.co.sContext.s so in case the user-function
70102   ** can use the already allocated buffer instead of allocating a
70103   ** new one.
70104   */
70105   sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
70106   MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
70107 
70108   rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
70109   importVtabErrMsg(p, u.co.pVtab);
70110   if( u.co.sContext.isError ){
70111     rc = u.co.sContext.isError;
70112   }
70113 
70114   /* Copy the result of the function to the P3 register. We
70115   ** do this regardless of whether or not an error occurred to ensure any
70116   ** dynamic allocation in u.co.sContext.s (a Mem struct) is  released.
70117   */
70118   sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
70119   sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
70120   REGISTER_TRACE(pOp->p3, u.co.pDest);
70121   UPDATE_MAX_BLOBSIZE(u.co.pDest);
70122 
70123   if( sqlite3VdbeMemTooBig(u.co.pDest) ){
70124     goto too_big;
70125   }
70126   break;
70127 }
70128 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70129 
70130 #ifndef SQLITE_OMIT_VIRTUALTABLE
70131 /* Opcode: VNext P1 P2 * * *
70132 **
70133 ** Advance virtual table P1 to the next row in its result set and
70134 ** jump to instruction P2.  Or, if the virtual table has reached
70135 ** the end of its result set, then fall through to the next instruction.
70136 */
70137 case OP_VNext: {   /* jump */
70138 #if 0  /* local variables moved into u.cp */
70139   sqlite3_vtab *pVtab;
70140   const sqlite3_module *pModule;
70141   int res;
70142   VdbeCursor *pCur;
70143 #endif /* local variables moved into u.cp */
70144 
70145   u.cp.res = 0;
70146   u.cp.pCur = p->apCsr[pOp->p1];
70147   assert( u.cp.pCur->pVtabCursor );
70148   if( u.cp.pCur->nullRow ){
70149     break;
70150   }
70151   u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
70152   u.cp.pModule = u.cp.pVtab->pModule;
70153   assert( u.cp.pModule->xNext );
70154 
70155   /* Invoke the xNext() method of the module. There is no way for the
70156   ** underlying implementation to return an error if one occurs during
70157   ** xNext(). Instead, if an error occurs, true is returned (indicating that
70158   ** data is available) and the error code returned when xColumn or
70159   ** some other method is next invoked on the save virtual table cursor.
70160   */
70161   p->inVtabMethod = 1;
70162   rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
70163   p->inVtabMethod = 0;
70164   importVtabErrMsg(p, u.cp.pVtab);
70165   if( rc==SQLITE_OK ){
70166     u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
70167   }
70168 
70169   if( !u.cp.res ){
70170     /* If there is data, jump to P2 */
70171     pc = pOp->p2 - 1;
70172   }
70173   break;
70174 }
70175 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70176 
70177 #ifndef SQLITE_OMIT_VIRTUALTABLE
70178 /* Opcode: VRename P1 * * P4 *
70179 **
70180 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70181 ** This opcode invokes the corresponding xRename method. The value
70182 ** in register P1 is passed as the zName argument to the xRename method.
70183 */
70184 case OP_VRename: {
70185 #if 0  /* local variables moved into u.cq */
70186   sqlite3_vtab *pVtab;
70187   Mem *pName;
70188 #endif /* local variables moved into u.cq */
70189 
70190   u.cq.pVtab = pOp->p4.pVtab->pVtab;
70191   u.cq.pName = &aMem[pOp->p1];
70192   assert( u.cq.pVtab->pModule->xRename );
70193   assert( memIsValid(u.cq.pName) );
70194   REGISTER_TRACE(pOp->p1, u.cq.pName);
70195   assert( u.cq.pName->flags & MEM_Str );
70196   testcase( u.cq.pName->enc==SQLITE_UTF8 );
70197   testcase( u.cq.pName->enc==SQLITE_UTF16BE );
70198   testcase( u.cq.pName->enc==SQLITE_UTF16LE );
70199   rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
70200   if( rc==SQLITE_OK ){
70201     rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
70202     importVtabErrMsg(p, u.cq.pVtab);
70203     p->expired = 0;
70204   }
70205   break;
70206 }
70207 #endif
70208 
70209 #ifndef SQLITE_OMIT_VIRTUALTABLE
70210 /* Opcode: VUpdate P1 P2 P3 P4 *
70211 **
70212 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70213 ** This opcode invokes the corresponding xUpdate method. P2 values
70214 ** are contiguous memory cells starting at P3 to pass to the xUpdate
70215 ** invocation. The value in register (P3+P2-1) corresponds to the
70216 ** p2th element of the argv array passed to xUpdate.
70217 **
70218 ** The xUpdate method will do a DELETE or an INSERT or both.
70219 ** The argv[0] element (which corresponds to memory cell P3)
70220 ** is the rowid of a row to delete.  If argv[0] is NULL then no
70221 ** deletion occurs.  The argv[1] element is the rowid of the new
70222 ** row.  This can be NULL to have the virtual table select the new
70223 ** rowid for itself.  The subsequent elements in the array are
70224 ** the values of columns in the new row.
70225 **
70226 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
70227 ** a row to delete.
70228 **
70229 ** P1 is a boolean flag. If it is set to true and the xUpdate call
70230 ** is successful, then the value returned by sqlite3_last_insert_rowid()
70231 ** is set to the value of the rowid for the row just inserted.
70232 */
70233 case OP_VUpdate: {
70234 #if 0  /* local variables moved into u.cr */
70235   sqlite3_vtab *pVtab;
70236   sqlite3_module *pModule;
70237   int nArg;
70238   int i;
70239   sqlite_int64 rowid;
70240   Mem **apArg;
70241   Mem *pX;
70242 #endif /* local variables moved into u.cr */
70243 
70244   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70245        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70246   );
70247   u.cr.pVtab = pOp->p4.pVtab->pVtab;
70248   u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
70249   u.cr.nArg = pOp->p2;
70250   assert( pOp->p4type==P4_VTAB );
70251   if( ALWAYS(u.cr.pModule->xUpdate) ){
70252     u8 vtabOnConflict = db->vtabOnConflict;
70253     u.cr.apArg = p->apArg;
70254     u.cr.pX = &aMem[pOp->p3];
70255     for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
70256       assert( memIsValid(u.cr.pX) );
70257       memAboutToChange(p, u.cr.pX);
70258       sqlite3VdbeMemStoreType(u.cr.pX);
70259       u.cr.apArg[u.cr.i] = u.cr.pX;
70260       u.cr.pX++;
70261     }
70262     db->vtabOnConflict = pOp->p5;
70263     rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
70264     db->vtabOnConflict = vtabOnConflict;
70265     importVtabErrMsg(p, u.cr.pVtab);
70266     if( rc==SQLITE_OK && pOp->p1 ){
70267       assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
70268       db->lastRowid = lastRowid = u.cr.rowid;
70269     }
70270     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70271       if( pOp->p5==OE_Ignore ){
70272         rc = SQLITE_OK;
70273       }else{
70274         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70275       }
70276     }else{
70277       p->nChange++;
70278     }
70279   }
70280   break;
70281 }
70282 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70283 
70284 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70285 /* Opcode: Pagecount P1 P2 * * *
70286 **
70287 ** Write the current number of pages in database P1 to memory cell P2.
70288 */
70289 case OP_Pagecount: {            /* out2-prerelease */
70290   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
70291   break;
70292 }
70293 #endif
70294 
70295 
70296 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70297 /* Opcode: MaxPgcnt P1 P2 P3 * *
70298 **
70299 ** Try to set the maximum page count for database P1 to the value in P3.
70300 ** Do not let the maximum page count fall below the current page count and
70301 ** do not change the maximum page count value if P3==0.
70302 **
70303 ** Store the maximum page count after the change in register P2.
70304 */
70305 case OP_MaxPgcnt: {            /* out2-prerelease */
70306   unsigned int newMax;
70307   Btree *pBt;
70308 
70309   pBt = db->aDb[pOp->p1].pBt;
70310   newMax = 0;
70311   if( pOp->p3 ){
70312     newMax = sqlite3BtreeLastPage(pBt);
70313     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
70314   }
70315   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
70316   break;
70317 }
70318 #endif
70319 
70320 
70321 #ifndef SQLITE_OMIT_TRACE
70322 /* Opcode: Trace * * * P4 *
70323 **
70324 ** If tracing is enabled (by the sqlite3_trace()) interface, then
70325 ** the UTF-8 string contained in P4 is emitted on the trace callback.
70326 */
70327 case OP_Trace: {
70328 #if 0  /* local variables moved into u.cs */
70329   char *zTrace;
70330   char *z;
70331 #endif /* local variables moved into u.cs */
70332 
70333   if( db->xTrace
70334    && !p->doingRerun
70335    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70336   ){
70337     u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
70338     db->xTrace(db->pTraceArg, u.cs.z);
70339     sqlite3DbFree(db, u.cs.z);
70340   }
70341 #ifdef SQLITE_DEBUG
70342   if( (db->flags & SQLITE_SqlTrace)!=0
70343    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
70344   ){
70345     sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
70346   }
70347 #endif /* SQLITE_DEBUG */
70348   break;
70349 }
70350 #endif
70351 
70352 
70353 /* Opcode: Noop * * * * *
70354 **
70355 ** Do nothing.  This instruction is often useful as a jump
70356 ** destination.
70357 */
70358 /*
70359 ** The magic Explain opcode are only inserted when explain==2 (which
70360 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
70361 ** This opcode records information from the optimizer.  It is the
70362 ** the same as a no-op.  This opcodesnever appears in a real VM program.
70363 */
70364 default: {          /* This is really OP_Noop and OP_Explain */
70365   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
70366   break;
70367 }
70368 
70369 /*****************************************************************************
70370 ** The cases of the switch statement above this line should all be indented
70371 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
70372 ** readability.  From this point on down, the normal indentation rules are
70373 ** restored.
70374 *****************************************************************************/
70375     }
70376 
70377 #ifdef VDBE_PROFILE
70378     {
70379       u64 elapsed = sqlite3Hwtime() - start;
70380       pOp->cycles += elapsed;
70381       pOp->cnt++;
70382 #if 0
70383         fprintf(stdout, "%10llu ", elapsed);
70384         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
70385 #endif
70386     }
70387 #endif
70388 
70389     /* The following code adds nothing to the actual functionality
70390     ** of the program.  It is only here for testing and debugging.
70391     ** On the other hand, it does burn CPU cycles every time through
70392     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
70393     */
70394 #ifndef NDEBUG
70395     assert( pc>=-1 && pc<p->nOp );
70396 
70397 #ifdef SQLITE_DEBUG
70398     if( p->trace ){
70399       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
70400       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
70401         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
70402       }
70403       if( pOp->opflags & OPFLG_OUT3 ){
70404         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
70405       }
70406     }
70407 #endif  /* SQLITE_DEBUG */
70408 #endif  /* NDEBUG */
70409   }  /* The end of the for(;;) loop the loops through opcodes */
70410 
70411   /* If we reach this point, it means that execution is finished with
70412   ** an error of some kind.
70413   */
70414 vdbe_error_halt:
70415   assert( rc );
70416   p->rc = rc;
70417   testcase( sqlite3GlobalConfig.xLog!=0 );
70418   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
70419                    pc, p->zSql, p->zErrMsg);
70420   sqlite3VdbeHalt(p);
70421   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
70422   rc = SQLITE_ERROR;
70423   if( resetSchemaOnFault>0 ){
70424     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
70425   }
70426 
70427   /* This is the only way out of this procedure.  We have to
70428   ** release the mutexes on btrees that were acquired at the
70429   ** top. */
70430 vdbe_return:
70431   db->lastRowid = lastRowid;
70432   sqlite3VdbeLeave(p);
70433   return rc;
70434 
70435   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
70436   ** is encountered.
70437   */
70438 too_big:
70439   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
70440   rc = SQLITE_TOOBIG;
70441   goto vdbe_error_halt;
70442 
70443   /* Jump to here if a malloc() fails.
70444   */
70445 no_mem:
70446   db->mallocFailed = 1;
70447   sqlite3SetString(&p->zErrMsg, db, "out of memory");
70448   rc = SQLITE_NOMEM;
70449   goto vdbe_error_halt;
70450 
70451   /* Jump to here for any other kind of fatal error.  The "rc" variable
70452   ** should hold the error number.
70453   */
70454 abort_due_to_error:
70455   assert( p->zErrMsg==0 );
70456   if( db->mallocFailed ) rc = SQLITE_NOMEM;
70457   if( rc!=SQLITE_IOERR_NOMEM ){
70458     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
70459   }
70460   goto vdbe_error_halt;
70461 
70462   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
70463   ** flag.
70464   */
70465 abort_due_to_interrupt:
70466   assert( db->u1.isInterrupted );
70467   rc = SQLITE_INTERRUPT;
70468   p->rc = rc;
70469   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
70470   goto vdbe_error_halt;
70471 }
70472 
70473 /************** End of vdbe.c ************************************************/
70474 /************** Begin file vdbeblob.c ****************************************/
70475 /*
70476 ** 2007 May 1
70477 **
70478 ** The author disclaims copyright to this source code.  In place of
70479 ** a legal notice, here is a blessing:
70480 **
70481 **    May you do good and not evil.
70482 **    May you find forgiveness for yourself and forgive others.
70483 **    May you share freely, never taking more than you give.
70484 **
70485 *************************************************************************
70486 **
70487 ** This file contains code used to implement incremental BLOB I/O.
70488 */
70489 
70490 
70491 #ifndef SQLITE_OMIT_INCRBLOB
70492 
70493 /*
70494 ** Valid sqlite3_blob* handles point to Incrblob structures.
70495 */
70496 typedef struct Incrblob Incrblob;
70497 struct Incrblob {
70498   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
70499   int nByte;              /* Size of open blob, in bytes */
70500   int iOffset;            /* Byte offset of blob in cursor data */
70501   int iCol;               /* Table column this handle is open on */
70502   BtCursor *pCsr;         /* Cursor pointing at blob row */
70503   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
70504   sqlite3 *db;            /* The associated database */
70505 };
70506 
70507 
70508 /*
70509 ** This function is used by both blob_open() and blob_reopen(). It seeks
70510 ** the b-tree cursor associated with blob handle p to point to row iRow.
70511 ** If successful, SQLITE_OK is returned and subsequent calls to
70512 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
70513 **
70514 ** If an error occurs, or if the specified row does not exist or does not
70515 ** contain a value of type TEXT or BLOB in the column nominated when the
70516 ** blob handle was opened, then an error code is returned and *pzErr may
70517 ** be set to point to a buffer containing an error message. It is the
70518 ** responsibility of the caller to free the error message buffer using
70519 ** sqlite3DbFree().
70520 **
70521 ** If an error does occur, then the b-tree cursor is closed. All subsequent
70522 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
70523 ** immediately return SQLITE_ABORT.
70524 */
70525 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
70526   int rc;                         /* Error code */
70527   char *zErr = 0;                 /* Error message */
70528   Vdbe *v = (Vdbe *)p->pStmt;
70529 
70530   /* Set the value of the SQL statements only variable to integer iRow.
70531   ** This is done directly instead of using sqlite3_bind_int64() to avoid
70532   ** triggering asserts related to mutexes.
70533   */
70534   assert( v->aVar[0].flags&MEM_Int );
70535   v->aVar[0].u.i = iRow;
70536 
70537   rc = sqlite3_step(p->pStmt);
70538   if( rc==SQLITE_ROW ){
70539     u32 type = v->apCsr[0]->aType[p->iCol];
70540     if( type<12 ){
70541       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
70542           type==0?"null": type==7?"real": "integer"
70543       );
70544       rc = SQLITE_ERROR;
70545       sqlite3_finalize(p->pStmt);
70546       p->pStmt = 0;
70547     }else{
70548       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
70549       p->nByte = sqlite3VdbeSerialTypeLen(type);
70550       p->pCsr =  v->apCsr[0]->pCursor;
70551       sqlite3BtreeEnterCursor(p->pCsr);
70552       sqlite3BtreeCacheOverflow(p->pCsr);
70553       sqlite3BtreeLeaveCursor(p->pCsr);
70554     }
70555   }
70556 
70557   if( rc==SQLITE_ROW ){
70558     rc = SQLITE_OK;
70559   }else if( p->pStmt ){
70560     rc = sqlite3_finalize(p->pStmt);
70561     p->pStmt = 0;
70562     if( rc==SQLITE_OK ){
70563       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
70564       rc = SQLITE_ERROR;
70565     }else{
70566       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
70567     }
70568   }
70569 
70570   assert( rc!=SQLITE_OK || zErr==0 );
70571   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
70572 
70573   *pzErr = zErr;
70574   return rc;
70575 }
70576 
70577 /*
70578 ** Open a blob handle.
70579 */
70580 SQLITE_API int sqlite3_blob_open(
70581   sqlite3* db,            /* The database connection */
70582   const char *zDb,        /* The attached database containing the blob */
70583   const char *zTable,     /* The table containing the blob */
70584   const char *zColumn,    /* The column containing the blob */
70585   sqlite_int64 iRow,      /* The row containing the glob */
70586   int flags,              /* True -> read/write access, false -> read-only */
70587   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
70588 ){
70589   int nAttempt = 0;
70590   int iCol;               /* Index of zColumn in row-record */
70591 
70592   /* This VDBE program seeks a btree cursor to the identified
70593   ** db/table/row entry. The reason for using a vdbe program instead
70594   ** of writing code to use the b-tree layer directly is that the
70595   ** vdbe program will take advantage of the various transaction,
70596   ** locking and error handling infrastructure built into the vdbe.
70597   **
70598   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
70599   ** Code external to the Vdbe then "borrows" the b-tree cursor and
70600   ** uses it to implement the blob_read(), blob_write() and
70601   ** blob_bytes() functions.
70602   **
70603   ** The sqlite3_blob_close() function finalizes the vdbe program,
70604   ** which closes the b-tree cursor and (possibly) commits the
70605   ** transaction.
70606   */
70607   static const VdbeOpList openBlob[] = {
70608     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
70609     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
70610     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
70611 
70612     /* One of the following two instructions is replaced by an OP_Noop. */
70613     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
70614     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
70615 
70616     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
70617     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
70618     {OP_Column, 0, 0, 1},          /* 7  */
70619     {OP_ResultRow, 1, 0, 0},       /* 8  */
70620     {OP_Goto, 0, 5, 0},            /* 9  */
70621     {OP_Close, 0, 0, 0},           /* 10 */
70622     {OP_Halt, 0, 0, 0},            /* 11 */
70623   };
70624 
70625   int rc = SQLITE_OK;
70626   char *zErr = 0;
70627   Table *pTab;
70628   Parse *pParse = 0;
70629   Incrblob *pBlob = 0;
70630 
70631   flags = !!flags;                /* flags = (flags ? 1 : 0); */
70632   *ppBlob = 0;
70633 
70634   sqlite3_mutex_enter(db->mutex);
70635 
70636   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
70637   if( !pBlob ) goto blob_open_out;
70638   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
70639   if( !pParse ) goto blob_open_out;
70640 
70641   do {
70642     memset(pParse, 0, sizeof(Parse));
70643     pParse->db = db;
70644     sqlite3DbFree(db, zErr);
70645     zErr = 0;
70646 
70647     sqlite3BtreeEnterAll(db);
70648     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
70649     if( pTab && IsVirtual(pTab) ){
70650       pTab = 0;
70651       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
70652     }
70653 #ifndef SQLITE_OMIT_VIEW
70654     if( pTab && pTab->pSelect ){
70655       pTab = 0;
70656       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
70657     }
70658 #endif
70659     if( !pTab ){
70660       if( pParse->zErrMsg ){
70661         sqlite3DbFree(db, zErr);
70662         zErr = pParse->zErrMsg;
70663         pParse->zErrMsg = 0;
70664       }
70665       rc = SQLITE_ERROR;
70666       sqlite3BtreeLeaveAll(db);
70667       goto blob_open_out;
70668     }
70669 
70670     /* Now search pTab for the exact column. */
70671     for(iCol=0; iCol<pTab->nCol; iCol++) {
70672       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
70673         break;
70674       }
70675     }
70676     if( iCol==pTab->nCol ){
70677       sqlite3DbFree(db, zErr);
70678       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
70679       rc = SQLITE_ERROR;
70680       sqlite3BtreeLeaveAll(db);
70681       goto blob_open_out;
70682     }
70683 
70684     /* If the value is being opened for writing, check that the
70685     ** column is not indexed, and that it is not part of a foreign key.
70686     ** It is against the rules to open a column to which either of these
70687     ** descriptions applies for writing.  */
70688     if( flags ){
70689       const char *zFault = 0;
70690       Index *pIdx;
70691 #ifndef SQLITE_OMIT_FOREIGN_KEY
70692       if( db->flags&SQLITE_ForeignKeys ){
70693         /* Check that the column is not part of an FK child key definition. It
70694         ** is not necessary to check if it is part of a parent key, as parent
70695         ** key columns must be indexed. The check below will pick up this
70696         ** case.  */
70697         FKey *pFKey;
70698         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
70699           int j;
70700           for(j=0; j<pFKey->nCol; j++){
70701             if( pFKey->aCol[j].iFrom==iCol ){
70702               zFault = "foreign key";
70703             }
70704           }
70705         }
70706       }
70707 #endif
70708       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70709         int j;
70710         for(j=0; j<pIdx->nColumn; j++){
70711           if( pIdx->aiColumn[j]==iCol ){
70712             zFault = "indexed";
70713           }
70714         }
70715       }
70716       if( zFault ){
70717         sqlite3DbFree(db, zErr);
70718         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
70719         rc = SQLITE_ERROR;
70720         sqlite3BtreeLeaveAll(db);
70721         goto blob_open_out;
70722       }
70723     }
70724 
70725     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
70726     assert( pBlob->pStmt || db->mallocFailed );
70727     if( pBlob->pStmt ){
70728       Vdbe *v = (Vdbe *)pBlob->pStmt;
70729       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70730 
70731       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
70732 
70733 
70734       /* Configure the OP_Transaction */
70735       sqlite3VdbeChangeP1(v, 0, iDb);
70736       sqlite3VdbeChangeP2(v, 0, flags);
70737 
70738       /* Configure the OP_VerifyCookie */
70739       sqlite3VdbeChangeP1(v, 1, iDb);
70740       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
70741       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
70742 
70743       /* Make sure a mutex is held on the table to be accessed */
70744       sqlite3VdbeUsesBtree(v, iDb);
70745 
70746       /* Configure the OP_TableLock instruction */
70747 #ifdef SQLITE_OMIT_SHARED_CACHE
70748       sqlite3VdbeChangeToNoop(v, 2);
70749 #else
70750       sqlite3VdbeChangeP1(v, 2, iDb);
70751       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
70752       sqlite3VdbeChangeP3(v, 2, flags);
70753       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
70754 #endif
70755 
70756       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
70757       ** parameter of the other to pTab->tnum.  */
70758       sqlite3VdbeChangeToNoop(v, 4 - flags);
70759       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
70760       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
70761 
70762       /* Configure the number of columns. Configure the cursor to
70763       ** think that the table has one more column than it really
70764       ** does. An OP_Column to retrieve this imaginary column will
70765       ** always return an SQL NULL. This is useful because it means
70766       ** we can invoke OP_Column to fill in the vdbe cursors type
70767       ** and offset cache without causing any IO.
70768       */
70769       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
70770       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
70771       if( !db->mallocFailed ){
70772         pParse->nVar = 1;
70773         pParse->nMem = 1;
70774         pParse->nTab = 1;
70775         sqlite3VdbeMakeReady(v, pParse);
70776       }
70777     }
70778 
70779     pBlob->flags = flags;
70780     pBlob->iCol = iCol;
70781     pBlob->db = db;
70782     sqlite3BtreeLeaveAll(db);
70783     if( db->mallocFailed ){
70784       goto blob_open_out;
70785     }
70786     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
70787     rc = blobSeekToRow(pBlob, iRow, &zErr);
70788   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
70789 
70790 blob_open_out:
70791   if( rc==SQLITE_OK && db->mallocFailed==0 ){
70792     *ppBlob = (sqlite3_blob *)pBlob;
70793   }else{
70794     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
70795     sqlite3DbFree(db, pBlob);
70796   }
70797   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70798   sqlite3DbFree(db, zErr);
70799   sqlite3StackFree(db, pParse);
70800   rc = sqlite3ApiExit(db, rc);
70801   sqlite3_mutex_leave(db->mutex);
70802   return rc;
70803 }
70804 
70805 /*
70806 ** Close a blob handle that was previously created using
70807 ** sqlite3_blob_open().
70808 */
70809 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
70810   Incrblob *p = (Incrblob *)pBlob;
70811   int rc;
70812   sqlite3 *db;
70813 
70814   if( p ){
70815     db = p->db;
70816     sqlite3_mutex_enter(db->mutex);
70817     rc = sqlite3_finalize(p->pStmt);
70818     sqlite3DbFree(db, p);
70819     sqlite3_mutex_leave(db->mutex);
70820   }else{
70821     rc = SQLITE_OK;
70822   }
70823   return rc;
70824 }
70825 
70826 /*
70827 ** Perform a read or write operation on a blob
70828 */
70829 static int blobReadWrite(
70830   sqlite3_blob *pBlob,
70831   void *z,
70832   int n,
70833   int iOffset,
70834   int (*xCall)(BtCursor*, u32, u32, void*)
70835 ){
70836   int rc;
70837   Incrblob *p = (Incrblob *)pBlob;
70838   Vdbe *v;
70839   sqlite3 *db;
70840 
70841   if( p==0 ) return SQLITE_MISUSE_BKPT;
70842   db = p->db;
70843   sqlite3_mutex_enter(db->mutex);
70844   v = (Vdbe*)p->pStmt;
70845 
70846   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
70847     /* Request is out of range. Return a transient error. */
70848     rc = SQLITE_ERROR;
70849     sqlite3Error(db, SQLITE_ERROR, 0);
70850   }else if( v==0 ){
70851     /* If there is no statement handle, then the blob-handle has
70852     ** already been invalidated. Return SQLITE_ABORT in this case.
70853     */
70854     rc = SQLITE_ABORT;
70855   }else{
70856     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
70857     ** returned, clean-up the statement handle.
70858     */
70859     assert( db == v->db );
70860     sqlite3BtreeEnterCursor(p->pCsr);
70861     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
70862     sqlite3BtreeLeaveCursor(p->pCsr);
70863     if( rc==SQLITE_ABORT ){
70864       sqlite3VdbeFinalize(v);
70865       p->pStmt = 0;
70866     }else{
70867       db->errCode = rc;
70868       v->rc = rc;
70869     }
70870   }
70871   rc = sqlite3ApiExit(db, rc);
70872   sqlite3_mutex_leave(db->mutex);
70873   return rc;
70874 }
70875 
70876 /*
70877 ** Read data from a blob handle.
70878 */
70879 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
70880   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
70881 }
70882 
70883 /*
70884 ** Write data to a blob handle.
70885 */
70886 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
70887   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
70888 }
70889 
70890 /*
70891 ** Query a blob handle for the size of the data.
70892 **
70893 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
70894 ** so no mutex is required for access.
70895 */
70896 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
70897   Incrblob *p = (Incrblob *)pBlob;
70898   return (p && p->pStmt) ? p->nByte : 0;
70899 }
70900 
70901 /*
70902 ** Move an existing blob handle to point to a different row of the same
70903 ** database table.
70904 **
70905 ** If an error occurs, or if the specified row does not exist or does not
70906 ** contain a blob or text value, then an error code is returned and the
70907 ** database handle error code and message set. If this happens, then all
70908 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
70909 ** immediately return SQLITE_ABORT.
70910 */
70911 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
70912   int rc;
70913   Incrblob *p = (Incrblob *)pBlob;
70914   sqlite3 *db;
70915 
70916   if( p==0 ) return SQLITE_MISUSE_BKPT;
70917   db = p->db;
70918   sqlite3_mutex_enter(db->mutex);
70919 
70920   if( p->pStmt==0 ){
70921     /* If there is no statement handle, then the blob-handle has
70922     ** already been invalidated. Return SQLITE_ABORT in this case.
70923     */
70924     rc = SQLITE_ABORT;
70925   }else{
70926     char *zErr;
70927     rc = blobSeekToRow(p, iRow, &zErr);
70928     if( rc!=SQLITE_OK ){
70929       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70930       sqlite3DbFree(db, zErr);
70931     }
70932     assert( rc!=SQLITE_SCHEMA );
70933   }
70934 
70935   rc = sqlite3ApiExit(db, rc);
70936   assert( rc==SQLITE_OK || p->pStmt==0 );
70937   sqlite3_mutex_leave(db->mutex);
70938   return rc;
70939 }
70940 
70941 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
70942 
70943 /************** End of vdbeblob.c ********************************************/
70944 /************** Begin file vdbesort.c ****************************************/
70945 /*
70946 ** 2011 July 9
70947 **
70948 ** The author disclaims copyright to this source code.  In place of
70949 ** a legal notice, here is a blessing:
70950 **
70951 **    May you do good and not evil.
70952 **    May you find forgiveness for yourself and forgive others.
70953 **    May you share freely, never taking more than you give.
70954 **
70955 *************************************************************************
70956 ** This file contains code for the VdbeSorter object, used in concert with
70957 ** a VdbeCursor to sort large numbers of keys (as may be required, for
70958 ** example, by CREATE INDEX statements on tables too large to fit in main
70959 ** memory).
70960 */
70961 
70962 
70963 
70964 typedef struct VdbeSorterIter VdbeSorterIter;
70965 typedef struct SorterRecord SorterRecord;
70966 typedef struct FileWriter FileWriter;
70967 
70968 /*
70969 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
70970 **
70971 ** As keys are added to the sorter, they are written to disk in a series
70972 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
70973 ** the same as the cache-size allowed for temporary databases. In order
70974 ** to allow the caller to extract keys from the sorter in sorted order,
70975 ** all PMAs currently stored on disk must be merged together. This comment
70976 ** describes the data structure used to do so. The structure supports
70977 ** merging any number of arrays in a single pass with no redundant comparison
70978 ** operations.
70979 **
70980 ** The aIter[] array contains an iterator for each of the PMAs being merged.
70981 ** An aIter[] iterator either points to a valid key or else is at EOF. For
70982 ** the purposes of the paragraphs below, we assume that the array is actually
70983 ** N elements in size, where N is the smallest power of 2 greater to or equal
70984 ** to the number of iterators being merged. The extra aIter[] elements are
70985 ** treated as if they are empty (always at EOF).
70986 **
70987 ** The aTree[] array is also N elements in size. The value of N is stored in
70988 ** the VdbeSorter.nTree variable.
70989 **
70990 ** The final (N/2) elements of aTree[] contain the results of comparing
70991 ** pairs of iterator keys together. Element i contains the result of
70992 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
70993 ** aTree element is set to the index of it.
70994 **
70995 ** For the purposes of this comparison, EOF is considered greater than any
70996 ** other key value. If the keys are equal (only possible with two EOF
70997 ** values), it doesn't matter which index is stored.
70998 **
70999 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
71000 ** above contains the index of the smallest of each block of 4 iterators.
71001 ** And so on. So that aTree[1] contains the index of the iterator that
71002 ** currently points to the smallest key value. aTree[0] is unused.
71003 **
71004 ** Example:
71005 **
71006 **     aIter[0] -> Banana
71007 **     aIter[1] -> Feijoa
71008 **     aIter[2] -> Elderberry
71009 **     aIter[3] -> Currant
71010 **     aIter[4] -> Grapefruit
71011 **     aIter[5] -> Apple
71012 **     aIter[6] -> Durian
71013 **     aIter[7] -> EOF
71014 **
71015 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
71016 **
71017 ** The current element is "Apple" (the value of the key indicated by
71018 ** iterator 5). When the Next() operation is invoked, iterator 5 will
71019 ** be advanced to the next key in its segment. Say the next key is
71020 ** "Eggplant":
71021 **
71022 **     aIter[5] -> Eggplant
71023 **
71024 ** The contents of aTree[] are updated first by comparing the new iterator
71025 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
71026 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
71027 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
71028 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
71029 ** so the value written into element 1 of the array is 0. As follows:
71030 **
71031 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
71032 **
71033 ** In other words, each time we advance to the next sorter element, log2(N)
71034 ** key comparison operations are required, where N is the number of segments
71035 ** being merged (rounded up to the next power of 2).
71036 */
71037 struct VdbeSorter {
71038   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
71039   i64 iReadOff;                   /* Current read offset within file pTemp1 */
71040   int nInMemory;                  /* Current size of pRecord list as PMA */
71041   int nTree;                      /* Used size of aTree/aIter (power of 2) */
71042   int nPMA;                       /* Number of PMAs stored in pTemp1 */
71043   int mnPmaSize;                  /* Minimum PMA size, in bytes */
71044   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
71045   VdbeSorterIter *aIter;          /* Array of iterators to merge */
71046   int *aTree;                     /* Current state of incremental merge */
71047   sqlite3_file *pTemp1;           /* PMA file 1 */
71048   SorterRecord *pRecord;          /* Head of in-memory record list */
71049   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
71050 };
71051 
71052 /*
71053 ** The following type is an iterator for a PMA. It caches the current key in
71054 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
71055 */
71056 struct VdbeSorterIter {
71057   i64 iReadOff;                   /* Current read offset */
71058   i64 iEof;                       /* 1 byte past EOF for this iterator */
71059   int nAlloc;                     /* Bytes of space at aAlloc */
71060   int nKey;                       /* Number of bytes in key */
71061   sqlite3_file *pFile;            /* File iterator is reading from */
71062   u8 *aAlloc;                     /* Allocated space */
71063   u8 *aKey;                       /* Pointer to current key */
71064   u8 *aBuffer;                    /* Current read buffer */
71065   int nBuffer;                    /* Size of read buffer in bytes */
71066 };
71067 
71068 /*
71069 ** An instance of this structure is used to organize the stream of records
71070 ** being written to files by the merge-sort code into aligned, page-sized
71071 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
71072 ** faster on many operating systems.
71073 */
71074 struct FileWriter {
71075   int eFWErr;                     /* Non-zero if in an error state */
71076   u8 *aBuffer;                    /* Pointer to write buffer */
71077   int nBuffer;                    /* Size of write buffer in bytes */
71078   int iBufStart;                  /* First byte of buffer to write */
71079   int iBufEnd;                    /* Last byte of buffer to write */
71080   i64 iWriteOff;                  /* Offset of start of buffer in file */
71081   sqlite3_file *pFile;            /* File to write to */
71082 };
71083 
71084 /*
71085 ** A structure to store a single record. All in-memory records are connected
71086 ** together into a linked list headed at VdbeSorter.pRecord using the
71087 ** SorterRecord.pNext pointer.
71088 */
71089 struct SorterRecord {
71090   void *pVal;
71091   int nVal;
71092   SorterRecord *pNext;
71093 };
71094 
71095 /* Minimum allowable value for the VdbeSorter.nWorking variable */
71096 #define SORTER_MIN_WORKING 10
71097 
71098 /* Maximum number of segments to merge in a single pass. */
71099 #define SORTER_MAX_MERGE_COUNT 16
71100 
71101 /*
71102 ** Free all memory belonging to the VdbeSorterIter object passed as the second
71103 ** argument. All structure fields are set to zero before returning.
71104 */
71105 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
71106   sqlite3DbFree(db, pIter->aAlloc);
71107   sqlite3DbFree(db, pIter->aBuffer);
71108   memset(pIter, 0, sizeof(VdbeSorterIter));
71109 }
71110 
71111 /*
71112 ** Read nByte bytes of data from the stream of data iterated by object p.
71113 ** If successful, set *ppOut to point to a buffer containing the data
71114 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
71115 ** error code.
71116 **
71117 ** The buffer indicated by *ppOut may only be considered valid until the
71118 ** next call to this function.
71119 */
71120 static int vdbeSorterIterRead(
71121   sqlite3 *db,                    /* Database handle (for malloc) */
71122   VdbeSorterIter *p,              /* Iterator */
71123   int nByte,                      /* Bytes of data to read */
71124   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
71125 ){
71126   int iBuf;                       /* Offset within buffer to read from */
71127   int nAvail;                     /* Bytes of data available in buffer */
71128   assert( p->aBuffer );
71129 
71130   /* If there is no more data to be read from the buffer, read the next
71131   ** p->nBuffer bytes of data from the file into it. Or, if there are less
71132   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
71133   iBuf = p->iReadOff % p->nBuffer;
71134   if( iBuf==0 ){
71135     int nRead;                    /* Bytes to read from disk */
71136     int rc;                       /* sqlite3OsRead() return code */
71137 
71138     /* Determine how many bytes of data to read. */
71139     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
71140       nRead = p->nBuffer;
71141     }else{
71142       nRead = (int)(p->iEof - p->iReadOff);
71143     }
71144     assert( nRead>0 );
71145 
71146     /* Read data from the file. Return early if an error occurs. */
71147     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
71148     assert( rc!=SQLITE_IOERR_SHORT_READ );
71149     if( rc!=SQLITE_OK ) return rc;
71150   }
71151   nAvail = p->nBuffer - iBuf;
71152 
71153   if( nByte<=nAvail ){
71154     /* The requested data is available in the in-memory buffer. In this
71155     ** case there is no need to make a copy of the data, just return a
71156     ** pointer into the buffer to the caller.  */
71157     *ppOut = &p->aBuffer[iBuf];
71158     p->iReadOff += nByte;
71159   }else{
71160     /* The requested data is not all available in the in-memory buffer.
71161     ** In this case, allocate space at p->aAlloc[] to copy the requested
71162     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
71163     int nRem;                     /* Bytes remaining to copy */
71164 
71165     /* Extend the p->aAlloc[] allocation if required. */
71166     if( p->nAlloc<nByte ){
71167       int nNew = p->nAlloc*2;
71168       while( nByte>nNew ) nNew = nNew*2;
71169       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
71170       if( !p->aAlloc ) return SQLITE_NOMEM;
71171       p->nAlloc = nNew;
71172     }
71173 
71174     /* Copy as much data as is available in the buffer into the start of
71175     ** p->aAlloc[].  */
71176     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
71177     p->iReadOff += nAvail;
71178     nRem = nByte - nAvail;
71179 
71180     /* The following loop copies up to p->nBuffer bytes per iteration into
71181     ** the p->aAlloc[] buffer.  */
71182     while( nRem>0 ){
71183       int rc;                     /* vdbeSorterIterRead() return code */
71184       int nCopy;                  /* Number of bytes to copy */
71185       u8 *aNext;                  /* Pointer to buffer to copy data from */
71186 
71187       nCopy = nRem;
71188       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
71189       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
71190       if( rc!=SQLITE_OK ) return rc;
71191       assert( aNext!=p->aAlloc );
71192       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
71193       nRem -= nCopy;
71194     }
71195 
71196     *ppOut = p->aAlloc;
71197   }
71198 
71199   return SQLITE_OK;
71200 }
71201 
71202 /*
71203 ** Read a varint from the stream of data accessed by p. Set *pnOut to
71204 ** the value read.
71205 */
71206 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
71207   int iBuf;
71208 
71209   iBuf = p->iReadOff % p->nBuffer;
71210   if( iBuf && (p->nBuffer-iBuf)>=9 ){
71211     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
71212   }else{
71213     u8 aVarint[16], *a;
71214     int i = 0, rc;
71215     do{
71216       rc = vdbeSorterIterRead(db, p, 1, &a);
71217       if( rc ) return rc;
71218       aVarint[(i++)&0xf] = a[0];
71219     }while( (a[0]&0x80)!=0 );
71220     sqlite3GetVarint(aVarint, pnOut);
71221   }
71222 
71223   return SQLITE_OK;
71224 }
71225 
71226 
71227 /*
71228 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
71229 ** no error occurs, or an SQLite error code if one does.
71230 */
71231 static int vdbeSorterIterNext(
71232   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
71233   VdbeSorterIter *pIter           /* Iterator to advance */
71234 ){
71235   int rc;                         /* Return Code */
71236   u64 nRec = 0;                   /* Size of record in bytes */
71237 
71238   if( pIter->iReadOff>=pIter->iEof ){
71239     /* This is an EOF condition */
71240     vdbeSorterIterZero(db, pIter);
71241     return SQLITE_OK;
71242   }
71243 
71244   rc = vdbeSorterIterVarint(db, pIter, &nRec);
71245   if( rc==SQLITE_OK ){
71246     pIter->nKey = (int)nRec;
71247     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
71248   }
71249 
71250   return rc;
71251 }
71252 
71253 /*
71254 ** Initialize iterator pIter to scan through the PMA stored in file pFile
71255 ** starting at offset iStart and ending at offset iEof-1. This function
71256 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
71257 ** PMA is empty).
71258 */
71259 static int vdbeSorterIterInit(
71260   sqlite3 *db,                    /* Database handle */
71261   const VdbeSorter *pSorter,      /* Sorter object */
71262   i64 iStart,                     /* Start offset in pFile */
71263   VdbeSorterIter *pIter,          /* Iterator to populate */
71264   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71265 ){
71266   int rc = SQLITE_OK;
71267   int nBuf;
71268 
71269   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71270 
71271   assert( pSorter->iWriteOff>iStart );
71272   assert( pIter->aAlloc==0 );
71273   assert( pIter->aBuffer==0 );
71274   pIter->pFile = pSorter->pTemp1;
71275   pIter->iReadOff = iStart;
71276   pIter->nAlloc = 128;
71277   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
71278   pIter->nBuffer = nBuf;
71279   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
71280 
71281   if( !pIter->aBuffer ){
71282     rc = SQLITE_NOMEM;
71283   }else{
71284     int iBuf;
71285 
71286     iBuf = iStart % nBuf;
71287     if( iBuf ){
71288       int nRead = nBuf - iBuf;
71289       if( (iStart + nRead) > pSorter->iWriteOff ){
71290         nRead = (int)(pSorter->iWriteOff - iStart);
71291       }
71292       rc = sqlite3OsRead(
71293           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
71294       );
71295       assert( rc!=SQLITE_IOERR_SHORT_READ );
71296     }
71297 
71298     if( rc==SQLITE_OK ){
71299       u64 nByte;                       /* Size of PMA in bytes */
71300       pIter->iEof = pSorter->iWriteOff;
71301       rc = vdbeSorterIterVarint(db, pIter, &nByte);
71302       pIter->iEof = pIter->iReadOff + nByte;
71303       *pnByte += nByte;
71304     }
71305   }
71306 
71307   if( rc==SQLITE_OK ){
71308     rc = vdbeSorterIterNext(db, pIter);
71309   }
71310   return rc;
71311 }
71312 
71313 
71314 /*
71315 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
71316 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71317 ** used by the comparison. If an error occurs, return an SQLite error code.
71318 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
71319 ** value, depending on whether key1 is smaller, equal to or larger than key2.
71320 **
71321 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71322 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71323 ** is true and key1 contains even a single NULL value, it is considered to
71324 ** be less than key2. Even if key2 also contains NULL values.
71325 **
71326 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71327 ** has been allocated and contains an unpacked record that is used as key2.
71328 */
71329 static void vdbeSorterCompare(
71330   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
71331   int bOmitRowid,                 /* Ignore rowid field at end of keys */
71332   const void *pKey1, int nKey1,   /* Left side of comparison */
71333   const void *pKey2, int nKey2,   /* Right side of comparison */
71334   int *pRes                       /* OUT: Result of comparison */
71335 ){
71336   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71337   VdbeSorter *pSorter = pCsr->pSorter;
71338   UnpackedRecord *r2 = pSorter->pUnpacked;
71339   int i;
71340 
71341   if( pKey2 ){
71342     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71343   }
71344 
71345   if( bOmitRowid ){
71346     r2->nField = pKeyInfo->nField;
71347     assert( r2->nField>0 );
71348     for(i=0; i<r2->nField; i++){
71349       if( r2->aMem[i].flags & MEM_Null ){
71350         *pRes = -1;
71351         return;
71352       }
71353     }
71354     r2->flags |= UNPACKED_PREFIX_MATCH;
71355   }
71356 
71357   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
71358 }
71359 
71360 /*
71361 ** This function is called to compare two iterator keys when merging
71362 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
71363 ** value to recalculate.
71364 */
71365 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
71366   VdbeSorter *pSorter = pCsr->pSorter;
71367   int i1;
71368   int i2;
71369   int iRes;
71370   VdbeSorterIter *p1;
71371   VdbeSorterIter *p2;
71372 
71373   assert( iOut<pSorter->nTree && iOut>0 );
71374 
71375   if( iOut>=(pSorter->nTree/2) ){
71376     i1 = (iOut - pSorter->nTree/2) * 2;
71377     i2 = i1 + 1;
71378   }else{
71379     i1 = pSorter->aTree[iOut*2];
71380     i2 = pSorter->aTree[iOut*2+1];
71381   }
71382 
71383   p1 = &pSorter->aIter[i1];
71384   p2 = &pSorter->aIter[i2];
71385 
71386   if( p1->pFile==0 ){
71387     iRes = i2;
71388   }else if( p2->pFile==0 ){
71389     iRes = i1;
71390   }else{
71391     int res;
71392     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
71393     vdbeSorterCompare(
71394         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
71395     );
71396     if( res<=0 ){
71397       iRes = i1;
71398     }else{
71399       iRes = i2;
71400     }
71401   }
71402 
71403   pSorter->aTree[iOut] = iRes;
71404   return SQLITE_OK;
71405 }
71406 
71407 /*
71408 ** Initialize the temporary index cursor just opened as a sorter cursor.
71409 */
71410 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
71411   int pgsz;                       /* Page size of main database */
71412   int mxCache;                    /* Cache size */
71413   VdbeSorter *pSorter;            /* The new sorter */
71414   char *d;                        /* Dummy */
71415 
71416   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
71417   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
71418   if( pSorter==0 ){
71419     return SQLITE_NOMEM;
71420   }
71421 
71422   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
71423   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
71424   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
71425 
71426   if( !sqlite3TempInMemory(db) ){
71427     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71428     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
71429     mxCache = db->aDb[0].pSchema->cache_size;
71430     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
71431     pSorter->mxPmaSize = mxCache * pgsz;
71432   }
71433 
71434   return SQLITE_OK;
71435 }
71436 
71437 /*
71438 ** Free the list of sorted records starting at pRecord.
71439 */
71440 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
71441   SorterRecord *p;
71442   SorterRecord *pNext;
71443   for(p=pRecord; p; p=pNext){
71444     pNext = p->pNext;
71445     sqlite3DbFree(db, p);
71446   }
71447 }
71448 
71449 /*
71450 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
71451 */
71452 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
71453   VdbeSorter *pSorter = pCsr->pSorter;
71454   if( pSorter ){
71455     if( pSorter->aIter ){
71456       int i;
71457       for(i=0; i<pSorter->nTree; i++){
71458         vdbeSorterIterZero(db, &pSorter->aIter[i]);
71459       }
71460       sqlite3DbFree(db, pSorter->aIter);
71461     }
71462     if( pSorter->pTemp1 ){
71463       sqlite3OsCloseFree(pSorter->pTemp1);
71464     }
71465     vdbeSorterRecordFree(db, pSorter->pRecord);
71466     sqlite3DbFree(db, pSorter->pUnpacked);
71467     sqlite3DbFree(db, pSorter);
71468     pCsr->pSorter = 0;
71469   }
71470 }
71471 
71472 /*
71473 ** Allocate space for a file-handle and open a temporary file. If successful,
71474 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
71475 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
71476 */
71477 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
71478   int dummy;
71479   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
71480       SQLITE_OPEN_TEMP_JOURNAL |
71481       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
71482       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
71483   );
71484 }
71485 
71486 /*
71487 ** Merge the two sorted lists p1 and p2 into a single list.
71488 ** Set *ppOut to the head of the new list.
71489 */
71490 static void vdbeSorterMerge(
71491   const VdbeCursor *pCsr,         /* For pKeyInfo */
71492   SorterRecord *p1,               /* First list to merge */
71493   SorterRecord *p2,               /* Second list to merge */
71494   SorterRecord **ppOut            /* OUT: Head of merged list */
71495 ){
71496   SorterRecord *pFinal = 0;
71497   SorterRecord **pp = &pFinal;
71498   void *pVal2 = p2 ? p2->pVal : 0;
71499 
71500   while( p1 && p2 ){
71501     int res;
71502     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
71503     if( res<=0 ){
71504       *pp = p1;
71505       pp = &p1->pNext;
71506       p1 = p1->pNext;
71507       pVal2 = 0;
71508     }else{
71509       *pp = p2;
71510        pp = &p2->pNext;
71511       p2 = p2->pNext;
71512       if( p2==0 ) break;
71513       pVal2 = p2->pVal;
71514     }
71515   }
71516   *pp = p1 ? p1 : p2;
71517   *ppOut = pFinal;
71518 }
71519 
71520 /*
71521 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
71522 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
71523 ** occurs.
71524 */
71525 static int vdbeSorterSort(const VdbeCursor *pCsr){
71526   int i;
71527   SorterRecord **aSlot;
71528   SorterRecord *p;
71529   VdbeSorter *pSorter = pCsr->pSorter;
71530 
71531   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
71532   if( !aSlot ){
71533     return SQLITE_NOMEM;
71534   }
71535 
71536   p = pSorter->pRecord;
71537   while( p ){
71538     SorterRecord *pNext = p->pNext;
71539     p->pNext = 0;
71540     for(i=0; aSlot[i]; i++){
71541       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
71542       aSlot[i] = 0;
71543     }
71544     aSlot[i] = p;
71545     p = pNext;
71546   }
71547 
71548   p = 0;
71549   for(i=0; i<64; i++){
71550     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
71551   }
71552   pSorter->pRecord = p;
71553 
71554   sqlite3_free(aSlot);
71555   return SQLITE_OK;
71556 }
71557 
71558 /*
71559 ** Initialize a file-writer object.
71560 */
71561 static void fileWriterInit(
71562   sqlite3 *db,                    /* Database (for malloc) */
71563   sqlite3_file *pFile,            /* File to write to */
71564   FileWriter *p,                  /* Object to populate */
71565   i64 iStart                      /* Offset of pFile to begin writing at */
71566 ){
71567   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
71568 
71569   memset(p, 0, sizeof(FileWriter));
71570   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
71571   if( !p->aBuffer ){
71572     p->eFWErr = SQLITE_NOMEM;
71573   }else{
71574     p->iBufEnd = p->iBufStart = (iStart % nBuf);
71575     p->iWriteOff = iStart - p->iBufStart;
71576     p->nBuffer = nBuf;
71577     p->pFile = pFile;
71578   }
71579 }
71580 
71581 /*
71582 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
71583 ** if successful, or an SQLite error code if an error occurs.
71584 */
71585 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
71586   int nRem = nData;
71587   while( nRem>0 && p->eFWErr==0 ){
71588     int nCopy = nRem;
71589     if( nCopy>(p->nBuffer - p->iBufEnd) ){
71590       nCopy = p->nBuffer - p->iBufEnd;
71591     }
71592 
71593     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
71594     p->iBufEnd += nCopy;
71595     if( p->iBufEnd==p->nBuffer ){
71596       p->eFWErr = sqlite3OsWrite(p->pFile,
71597           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
71598           p->iWriteOff + p->iBufStart
71599       );
71600       p->iBufStart = p->iBufEnd = 0;
71601       p->iWriteOff += p->nBuffer;
71602     }
71603     assert( p->iBufEnd<p->nBuffer );
71604 
71605     nRem -= nCopy;
71606   }
71607 }
71608 
71609 /*
71610 ** Flush any buffered data to disk and clean up the file-writer object.
71611 ** The results of using the file-writer after this call are undefined.
71612 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
71613 ** required. Otherwise, return an SQLite error code.
71614 **
71615 ** Before returning, set *piEof to the offset immediately following the
71616 ** last byte written to the file.
71617 */
71618 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
71619   int rc;
71620   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
71621     p->eFWErr = sqlite3OsWrite(p->pFile,
71622         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
71623         p->iWriteOff + p->iBufStart
71624     );
71625   }
71626   *piEof = (p->iWriteOff + p->iBufEnd);
71627   sqlite3DbFree(db, p->aBuffer);
71628   rc = p->eFWErr;
71629   memset(p, 0, sizeof(FileWriter));
71630   return rc;
71631 }
71632 
71633 /*
71634 ** Write value iVal encoded as a varint to the file-write object. Return
71635 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
71636 */
71637 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
71638   int nByte;
71639   u8 aByte[10];
71640   nByte = sqlite3PutVarint(aByte, iVal);
71641   fileWriterWrite(p, aByte, nByte);
71642 }
71643 
71644 /*
71645 ** Write the current contents of the in-memory linked-list to a PMA. Return
71646 ** SQLITE_OK if successful, or an SQLite error code otherwise.
71647 **
71648 ** The format of a PMA is:
71649 **
71650 **     * A varint. This varint contains the total number of bytes of content
71651 **       in the PMA (not including the varint itself).
71652 **
71653 **     * One or more records packed end-to-end in order of ascending keys.
71654 **       Each record consists of a varint followed by a blob of data (the
71655 **       key). The varint is the number of bytes in the blob of data.
71656 */
71657 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
71658   int rc = SQLITE_OK;             /* Return code */
71659   VdbeSorter *pSorter = pCsr->pSorter;
71660   FileWriter writer;
71661 
71662   memset(&writer, 0, sizeof(FileWriter));
71663 
71664   if( pSorter->nInMemory==0 ){
71665     assert( pSorter->pRecord==0 );
71666     return rc;
71667   }
71668 
71669   rc = vdbeSorterSort(pCsr);
71670 
71671   /* If the first temporary PMA file has not been opened, open it now. */
71672   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
71673     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
71674     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
71675     assert( pSorter->iWriteOff==0 );
71676     assert( pSorter->nPMA==0 );
71677   }
71678 
71679   if( rc==SQLITE_OK ){
71680     SorterRecord *p;
71681     SorterRecord *pNext = 0;
71682 
71683     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
71684     pSorter->nPMA++;
71685     fileWriterWriteVarint(&writer, pSorter->nInMemory);
71686     for(p=pSorter->pRecord; p; p=pNext){
71687       pNext = p->pNext;
71688       fileWriterWriteVarint(&writer, p->nVal);
71689       fileWriterWrite(&writer, p->pVal, p->nVal);
71690       sqlite3DbFree(db, p);
71691     }
71692     pSorter->pRecord = p;
71693     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
71694   }
71695 
71696   return rc;
71697 }
71698 
71699 /*
71700 ** Add a record to the sorter.
71701 */
71702 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
71703   sqlite3 *db,                    /* Database handle */
71704   const VdbeCursor *pCsr,               /* Sorter cursor */
71705   Mem *pVal                       /* Memory cell containing record */
71706 ){
71707   VdbeSorter *pSorter = pCsr->pSorter;
71708   int rc = SQLITE_OK;             /* Return Code */
71709   SorterRecord *pNew;             /* New list element */
71710 
71711   assert( pSorter );
71712   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
71713 
71714   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
71715   if( pNew==0 ){
71716     rc = SQLITE_NOMEM;
71717   }else{
71718     pNew->pVal = (void *)&pNew[1];
71719     memcpy(pNew->pVal, pVal->z, pVal->n);
71720     pNew->nVal = pVal->n;
71721     pNew->pNext = pSorter->pRecord;
71722     pSorter->pRecord = pNew;
71723   }
71724 
71725   /* See if the contents of the sorter should now be written out. They
71726   ** are written out when either of the following are true:
71727   **
71728   **   * The total memory allocated for the in-memory list is greater
71729   **     than (page-size * cache-size), or
71730   **
71731   **   * The total memory allocated for the in-memory list is greater
71732   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
71733   */
71734   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
71735         (pSorter->nInMemory>pSorter->mxPmaSize)
71736      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
71737   )){
71738 #ifdef SQLITE_DEBUG
71739     i64 nExpect = pSorter->iWriteOff
71740                 + sqlite3VarintLen(pSorter->nInMemory)
71741                 + pSorter->nInMemory;
71742 #endif
71743     rc = vdbeSorterListToPMA(db, pCsr);
71744     pSorter->nInMemory = 0;
71745     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
71746   }
71747 
71748   return rc;
71749 }
71750 
71751 /*
71752 ** Helper function for sqlite3VdbeSorterRewind().
71753 */
71754 static int vdbeSorterInitMerge(
71755   sqlite3 *db,                    /* Database handle */
71756   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
71757   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
71758 ){
71759   VdbeSorter *pSorter = pCsr->pSorter;
71760   int rc = SQLITE_OK;             /* Return code */
71761   int i;                          /* Used to iterator through aIter[] */
71762   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
71763 
71764   /* Initialize the iterators. */
71765   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
71766     VdbeSorterIter *pIter = &pSorter->aIter[i];
71767     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
71768     pSorter->iReadOff = pIter->iEof;
71769     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
71770     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
71771   }
71772 
71773   /* Initialize the aTree[] array. */
71774   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
71775     rc = vdbeSorterDoCompare(pCsr, i);
71776   }
71777 
71778   *pnByte = nByte;
71779   return rc;
71780 }
71781 
71782 /*
71783 ** Once the sorter has been populated, this function is called to prepare
71784 ** for iterating through its contents in sorted order.
71785 */
71786 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71787   VdbeSorter *pSorter = pCsr->pSorter;
71788   int rc;                         /* Return code */
71789   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
71790   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
71791   int nIter;                      /* Number of iterators used */
71792   int nByte;                      /* Bytes of space required for aIter/aTree */
71793   int N = 2;                      /* Power of 2 >= nIter */
71794 
71795   assert( pSorter );
71796 
71797   /* If no data has been written to disk, then do not do so now. Instead,
71798   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
71799   ** from the in-memory list.  */
71800   if( pSorter->nPMA==0 ){
71801     *pbEof = !pSorter->pRecord;
71802     assert( pSorter->aTree==0 );
71803     return vdbeSorterSort(pCsr);
71804   }
71805 
71806   /* Write the current in-memory list to a PMA. */
71807   rc = vdbeSorterListToPMA(db, pCsr);
71808   if( rc!=SQLITE_OK ) return rc;
71809 
71810   /* Allocate space for aIter[] and aTree[]. */
71811   nIter = pSorter->nPMA;
71812   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
71813   assert( nIter>0 );
71814   while( N<nIter ) N += N;
71815   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
71816   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
71817   if( !pSorter->aIter ) return SQLITE_NOMEM;
71818   pSorter->aTree = (int *)&pSorter->aIter[N];
71819   pSorter->nTree = N;
71820 
71821   do {
71822     int iNew;                     /* Index of new, merged, PMA */
71823 
71824     for(iNew=0;
71825         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
71826         iNew++
71827     ){
71828       int rc2;                    /* Return code from fileWriterFinish() */
71829       FileWriter writer;          /* Object used to write to disk */
71830       i64 nWrite;                 /* Number of bytes in new PMA */
71831 
71832       memset(&writer, 0, sizeof(FileWriter));
71833 
71834       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
71835       ** initialize an iterator for each of them and break out of the loop.
71836       ** These iterators will be incrementally merged as the VDBE layer calls
71837       ** sqlite3VdbeSorterNext().
71838       **
71839       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
71840       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
71841       ** are merged into a single PMA that is written to file pTemp2.
71842       */
71843       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
71844       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
71845       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71846         break;
71847       }
71848 
71849       /* Open the second temp file, if it is not already open. */
71850       if( pTemp2==0 ){
71851         assert( iWrite2==0 );
71852         rc = vdbeSorterOpenTempFile(db, &pTemp2);
71853       }
71854 
71855       if( rc==SQLITE_OK ){
71856         int bEof = 0;
71857         fileWriterInit(db, pTemp2, &writer, iWrite2);
71858         fileWriterWriteVarint(&writer, nWrite);
71859         while( rc==SQLITE_OK && bEof==0 ){
71860           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71861           assert( pIter->pFile );
71862 
71863           fileWriterWriteVarint(&writer, pIter->nKey);
71864           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
71865           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
71866         }
71867         rc2 = fileWriterFinish(db, &writer, &iWrite2);
71868         if( rc==SQLITE_OK ) rc = rc2;
71869       }
71870     }
71871 
71872     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71873       break;
71874     }else{
71875       sqlite3_file *pTmp = pSorter->pTemp1;
71876       pSorter->nPMA = iNew;
71877       pSorter->pTemp1 = pTemp2;
71878       pTemp2 = pTmp;
71879       pSorter->iWriteOff = iWrite2;
71880       pSorter->iReadOff = 0;
71881       iWrite2 = 0;
71882     }
71883   }while( rc==SQLITE_OK );
71884 
71885   if( pTemp2 ){
71886     sqlite3OsCloseFree(pTemp2);
71887   }
71888   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71889   return rc;
71890 }
71891 
71892 /*
71893 ** Advance to the next element in the sorter.
71894 */
71895 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
71896   VdbeSorter *pSorter = pCsr->pSorter;
71897   int rc;                         /* Return code */
71898 
71899   if( pSorter->aTree ){
71900     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
71901     int i;                        /* Index of aTree[] to recalculate */
71902 
71903     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
71904     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
71905       rc = vdbeSorterDoCompare(pCsr, i);
71906     }
71907 
71908     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71909   }else{
71910     SorterRecord *pFree = pSorter->pRecord;
71911     pSorter->pRecord = pFree->pNext;
71912     pFree->pNext = 0;
71913     vdbeSorterRecordFree(db, pFree);
71914     *pbEof = !pSorter->pRecord;
71915     rc = SQLITE_OK;
71916   }
71917   return rc;
71918 }
71919 
71920 /*
71921 ** Return a pointer to a buffer owned by the sorter that contains the
71922 ** current key.
71923 */
71924 static void *vdbeSorterRowkey(
71925   const VdbeSorter *pSorter,      /* Sorter object */
71926   int *pnKey                      /* OUT: Size of current key in bytes */
71927 ){
71928   void *pKey;
71929   if( pSorter->aTree ){
71930     VdbeSorterIter *pIter;
71931     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71932     *pnKey = pIter->nKey;
71933     pKey = pIter->aKey;
71934   }else{
71935     *pnKey = pSorter->pRecord->nVal;
71936     pKey = pSorter->pRecord->pVal;
71937   }
71938   return pKey;
71939 }
71940 
71941 /*
71942 ** Copy the current sorter key into the memory cell pOut.
71943 */
71944 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
71945   VdbeSorter *pSorter = pCsr->pSorter;
71946   void *pKey; int nKey;           /* Sorter key to copy into pOut */
71947 
71948   pKey = vdbeSorterRowkey(pSorter, &nKey);
71949   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
71950     return SQLITE_NOMEM;
71951   }
71952   pOut->n = nKey;
71953   MemSetTypeFlag(pOut, MEM_Blob);
71954   memcpy(pOut->z, pKey, nKey);
71955 
71956   return SQLITE_OK;
71957 }
71958 
71959 /*
71960 ** Compare the key in memory cell pVal with the key that the sorter cursor
71961 ** passed as the first argument currently points to. For the purposes of
71962 ** the comparison, ignore the rowid field at the end of each record.
71963 **
71964 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
71965 ** Otherwise, set *pRes to a negative, zero or positive value if the
71966 ** key in pVal is smaller than, equal to or larger than the current sorter
71967 ** key.
71968 */
71969 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
71970   const VdbeCursor *pCsr,         /* Sorter cursor */
71971   Mem *pVal,                      /* Value to compare to current sorter key */
71972   int *pRes                       /* OUT: Result of comparison */
71973 ){
71974   VdbeSorter *pSorter = pCsr->pSorter;
71975   void *pKey; int nKey;           /* Sorter key to compare pVal with */
71976 
71977   pKey = vdbeSorterRowkey(pSorter, &nKey);
71978   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
71979   return SQLITE_OK;
71980 }
71981 
71982 /************** End of vdbesort.c ********************************************/
71983 /************** Begin file journal.c *****************************************/
71984 /*
71985 ** 2007 August 22
71986 **
71987 ** The author disclaims copyright to this source code.  In place of
71988 ** a legal notice, here is a blessing:
71989 **
71990 **    May you do good and not evil.
71991 **    May you find forgiveness for yourself and forgive others.
71992 **    May you share freely, never taking more than you give.
71993 **
71994 *************************************************************************
71995 **
71996 ** This file implements a special kind of sqlite3_file object used
71997 ** by SQLite to create journal files if the atomic-write optimization
71998 ** is enabled.
71999 **
72000 ** The distinctive characteristic of this sqlite3_file is that the
72001 ** actual on disk file is created lazily. When the file is created,
72002 ** the caller specifies a buffer size for an in-memory buffer to
72003 ** be used to service read() and write() requests. The actual file
72004 ** on disk is not created or populated until either:
72005 **
72006 **   1) The in-memory representation grows too large for the allocated
72007 **      buffer, or
72008 **   2) The sqlite3JournalCreate() function is called.
72009 */
72010 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
72011 
72012 
72013 /*
72014 ** A JournalFile object is a subclass of sqlite3_file used by
72015 ** as an open file handle for journal files.
72016 */
72017 struct JournalFile {
72018   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
72019   int nBuf;                       /* Size of zBuf[] in bytes */
72020   char *zBuf;                     /* Space to buffer journal writes */
72021   int iSize;                      /* Amount of zBuf[] currently used */
72022   int flags;                      /* xOpen flags */
72023   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
72024   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
72025   const char *zJournal;           /* Name of the journal file */
72026 };
72027 typedef struct JournalFile JournalFile;
72028 
72029 /*
72030 ** If it does not already exists, create and populate the on-disk file
72031 ** for JournalFile p.
72032 */
72033 static int createFile(JournalFile *p){
72034   int rc = SQLITE_OK;
72035   if( !p->pReal ){
72036     sqlite3_file *pReal = (sqlite3_file *)&p[1];
72037     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
72038     if( rc==SQLITE_OK ){
72039       p->pReal = pReal;
72040       if( p->iSize>0 ){
72041         assert(p->iSize<=p->nBuf);
72042         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
72043       }
72044       if( rc!=SQLITE_OK ){
72045         /* If an error occurred while writing to the file, close it before
72046         ** returning. This way, SQLite uses the in-memory journal data to
72047         ** roll back changes made to the internal page-cache before this
72048         ** function was called.  */
72049         sqlite3OsClose(pReal);
72050         p->pReal = 0;
72051       }
72052     }
72053   }
72054   return rc;
72055 }
72056 
72057 /*
72058 ** Close the file.
72059 */
72060 static int jrnlClose(sqlite3_file *pJfd){
72061   JournalFile *p = (JournalFile *)pJfd;
72062   if( p->pReal ){
72063     sqlite3OsClose(p->pReal);
72064   }
72065   sqlite3_free(p->zBuf);
72066   return SQLITE_OK;
72067 }
72068 
72069 /*
72070 ** Read data from the file.
72071 */
72072 static int jrnlRead(
72073   sqlite3_file *pJfd,    /* The journal file from which to read */
72074   void *zBuf,            /* Put the results here */
72075   int iAmt,              /* Number of bytes to read */
72076   sqlite_int64 iOfst     /* Begin reading at this offset */
72077 ){
72078   int rc = SQLITE_OK;
72079   JournalFile *p = (JournalFile *)pJfd;
72080   if( p->pReal ){
72081     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
72082   }else if( (iAmt+iOfst)>p->iSize ){
72083     rc = SQLITE_IOERR_SHORT_READ;
72084   }else{
72085     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
72086   }
72087   return rc;
72088 }
72089 
72090 /*
72091 ** Write data to the file.
72092 */
72093 static int jrnlWrite(
72094   sqlite3_file *pJfd,    /* The journal file into which to write */
72095   const void *zBuf,      /* Take data to be written from here */
72096   int iAmt,              /* Number of bytes to write */
72097   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72098 ){
72099   int rc = SQLITE_OK;
72100   JournalFile *p = (JournalFile *)pJfd;
72101   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
72102     rc = createFile(p);
72103   }
72104   if( rc==SQLITE_OK ){
72105     if( p->pReal ){
72106       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
72107     }else{
72108       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
72109       if( p->iSize<(iOfst+iAmt) ){
72110         p->iSize = (iOfst+iAmt);
72111       }
72112     }
72113   }
72114   return rc;
72115 }
72116 
72117 /*
72118 ** Truncate the file.
72119 */
72120 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72121   int rc = SQLITE_OK;
72122   JournalFile *p = (JournalFile *)pJfd;
72123   if( p->pReal ){
72124     rc = sqlite3OsTruncate(p->pReal, size);
72125   }else if( size<p->iSize ){
72126     p->iSize = size;
72127   }
72128   return rc;
72129 }
72130 
72131 /*
72132 ** Sync the file.
72133 */
72134 static int jrnlSync(sqlite3_file *pJfd, int flags){
72135   int rc;
72136   JournalFile *p = (JournalFile *)pJfd;
72137   if( p->pReal ){
72138     rc = sqlite3OsSync(p->pReal, flags);
72139   }else{
72140     rc = SQLITE_OK;
72141   }
72142   return rc;
72143 }
72144 
72145 /*
72146 ** Query the size of the file in bytes.
72147 */
72148 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72149   int rc = SQLITE_OK;
72150   JournalFile *p = (JournalFile *)pJfd;
72151   if( p->pReal ){
72152     rc = sqlite3OsFileSize(p->pReal, pSize);
72153   }else{
72154     *pSize = (sqlite_int64) p->iSize;
72155   }
72156   return rc;
72157 }
72158 
72159 /*
72160 ** Table of methods for JournalFile sqlite3_file object.
72161 */
72162 static struct sqlite3_io_methods JournalFileMethods = {
72163   1,             /* iVersion */
72164   jrnlClose,     /* xClose */
72165   jrnlRead,      /* xRead */
72166   jrnlWrite,     /* xWrite */
72167   jrnlTruncate,  /* xTruncate */
72168   jrnlSync,      /* xSync */
72169   jrnlFileSize,  /* xFileSize */
72170   0,             /* xLock */
72171   0,             /* xUnlock */
72172   0,             /* xCheckReservedLock */
72173   0,             /* xFileControl */
72174   0,             /* xSectorSize */
72175   0,             /* xDeviceCharacteristics */
72176   0,             /* xShmMap */
72177   0,             /* xShmLock */
72178   0,             /* xShmBarrier */
72179   0              /* xShmUnmap */
72180 };
72181 
72182 /*
72183 ** Open a journal file.
72184 */
72185 SQLITE_PRIVATE int sqlite3JournalOpen(
72186   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72187   const char *zName,         /* Name of the journal file */
72188   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
72189   int flags,                 /* Opening flags */
72190   int nBuf                   /* Bytes buffered before opening the file */
72191 ){
72192   JournalFile *p = (JournalFile *)pJfd;
72193   memset(p, 0, sqlite3JournalSize(pVfs));
72194   if( nBuf>0 ){
72195     p->zBuf = sqlite3MallocZero(nBuf);
72196     if( !p->zBuf ){
72197       return SQLITE_NOMEM;
72198     }
72199   }else{
72200     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
72201   }
72202   p->pMethod = &JournalFileMethods;
72203   p->nBuf = nBuf;
72204   p->flags = flags;
72205   p->zJournal = zName;
72206   p->pVfs = pVfs;
72207   return SQLITE_OK;
72208 }
72209 
72210 /*
72211 ** If the argument p points to a JournalFile structure, and the underlying
72212 ** file has not yet been created, create it now.
72213 */
72214 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
72215   if( p->pMethods!=&JournalFileMethods ){
72216     return SQLITE_OK;
72217   }
72218   return createFile((JournalFile *)p);
72219 }
72220 
72221 /*
72222 ** The file-handle passed as the only argument is guaranteed to be an open
72223 ** file. It may or may not be of class JournalFile. If the file is a
72224 ** JournalFile, and the underlying file on disk has not yet been opened,
72225 ** return 0. Otherwise, return 1.
72226 */
72227 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
72228   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
72229 }
72230 
72231 /*
72232 ** Return the number of bytes required to store a JournalFile that uses vfs
72233 ** pVfs to create the underlying on-disk files.
72234 */
72235 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
72236   return (pVfs->szOsFile+sizeof(JournalFile));
72237 }
72238 #endif
72239 
72240 /************** End of journal.c *********************************************/
72241 /************** Begin file memjournal.c **************************************/
72242 /*
72243 ** 2008 October 7
72244 **
72245 ** The author disclaims copyright to this source code.  In place of
72246 ** a legal notice, here is a blessing:
72247 **
72248 **    May you do good and not evil.
72249 **    May you find forgiveness for yourself and forgive others.
72250 **    May you share freely, never taking more than you give.
72251 **
72252 *************************************************************************
72253 **
72254 ** This file contains code use to implement an in-memory rollback journal.
72255 ** The in-memory rollback journal is used to journal transactions for
72256 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72257 */
72258 
72259 /* Forward references to internal structures */
72260 typedef struct MemJournal MemJournal;
72261 typedef struct FilePoint FilePoint;
72262 typedef struct FileChunk FileChunk;
72263 
72264 /* Space to hold the rollback journal is allocated in increments of
72265 ** this many bytes.
72266 **
72267 ** The size chosen is a little less than a power of two.  That way,
72268 ** the FileChunk object will have a size that almost exactly fills
72269 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72270 ** memory allocators.
72271 */
72272 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72273 
72274 /* Macro to find the minimum of two numeric values.
72275 */
72276 #ifndef MIN
72277 # define MIN(x,y) ((x)<(y)?(x):(y))
72278 #endif
72279 
72280 /*
72281 ** The rollback journal is composed of a linked list of these structures.
72282 */
72283 struct FileChunk {
72284   FileChunk *pNext;               /* Next chunk in the journal */
72285   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72286 };
72287 
72288 /*
72289 ** An instance of this object serves as a cursor into the rollback journal.
72290 ** The cursor can be either for reading or writing.
72291 */
72292 struct FilePoint {
72293   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
72294   FileChunk *pChunk;              /* Specific chunk into which cursor points */
72295 };
72296 
72297 /*
72298 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
72299 ** is an instance of this class.
72300 */
72301 struct MemJournal {
72302   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72303   FileChunk *pFirst;              /* Head of in-memory chunk-list */
72304   FilePoint endpoint;             /* Pointer to the end of the file */
72305   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72306 };
72307 
72308 /*
72309 ** Read data from the in-memory journal file.  This is the implementation
72310 ** of the sqlite3_vfs.xRead method.
72311 */
72312 static int memjrnlRead(
72313   sqlite3_file *pJfd,    /* The journal file from which to read */
72314   void *zBuf,            /* Put the results here */
72315   int iAmt,              /* Number of bytes to read */
72316   sqlite_int64 iOfst     /* Begin reading at this offset */
72317 ){
72318   MemJournal *p = (MemJournal *)pJfd;
72319   u8 *zOut = zBuf;
72320   int nRead = iAmt;
72321   int iChunkOffset;
72322   FileChunk *pChunk;
72323 
72324   /* SQLite never tries to read past the end of a rollback journal file */
72325   assert( iOfst+iAmt<=p->endpoint.iOffset );
72326 
72327   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72328     sqlite3_int64 iOff = 0;
72329     for(pChunk=p->pFirst;
72330         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72331         pChunk=pChunk->pNext
72332     ){
72333       iOff += JOURNAL_CHUNKSIZE;
72334     }
72335   }else{
72336     pChunk = p->readpoint.pChunk;
72337   }
72338 
72339   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72340   do {
72341     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72342     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72343     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72344     zOut += nCopy;
72345     nRead -= iSpace;
72346     iChunkOffset = 0;
72347   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72348   p->readpoint.iOffset = iOfst+iAmt;
72349   p->readpoint.pChunk = pChunk;
72350 
72351   return SQLITE_OK;
72352 }
72353 
72354 /*
72355 ** Write data to the file.
72356 */
72357 static int memjrnlWrite(
72358   sqlite3_file *pJfd,    /* The journal file into which to write */
72359   const void *zBuf,      /* Take data to be written from here */
72360   int iAmt,              /* Number of bytes to write */
72361   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72362 ){
72363   MemJournal *p = (MemJournal *)pJfd;
72364   int nWrite = iAmt;
72365   u8 *zWrite = (u8 *)zBuf;
72366 
72367   /* An in-memory journal file should only ever be appended to. Random
72368   ** access writes are not required by sqlite.
72369   */
72370   assert( iOfst==p->endpoint.iOffset );
72371   UNUSED_PARAMETER(iOfst);
72372 
72373   while( nWrite>0 ){
72374     FileChunk *pChunk = p->endpoint.pChunk;
72375     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72376     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72377 
72378     if( iChunkOffset==0 ){
72379       /* New chunk is required to extend the file. */
72380       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
72381       if( !pNew ){
72382         return SQLITE_IOERR_NOMEM;
72383       }
72384       pNew->pNext = 0;
72385       if( pChunk ){
72386         assert( p->pFirst );
72387         pChunk->pNext = pNew;
72388       }else{
72389         assert( !p->pFirst );
72390         p->pFirst = pNew;
72391       }
72392       p->endpoint.pChunk = pNew;
72393     }
72394 
72395     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72396     zWrite += iSpace;
72397     nWrite -= iSpace;
72398     p->endpoint.iOffset += iSpace;
72399   }
72400 
72401   return SQLITE_OK;
72402 }
72403 
72404 /*
72405 ** Truncate the file.
72406 */
72407 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72408   MemJournal *p = (MemJournal *)pJfd;
72409   FileChunk *pChunk;
72410   assert(size==0);
72411   UNUSED_PARAMETER(size);
72412   pChunk = p->pFirst;
72413   while( pChunk ){
72414     FileChunk *pTmp = pChunk;
72415     pChunk = pChunk->pNext;
72416     sqlite3_free(pTmp);
72417   }
72418   sqlite3MemJournalOpen(pJfd);
72419   return SQLITE_OK;
72420 }
72421 
72422 /*
72423 ** Close the file.
72424 */
72425 static int memjrnlClose(sqlite3_file *pJfd){
72426   memjrnlTruncate(pJfd, 0);
72427   return SQLITE_OK;
72428 }
72429 
72430 
72431 /*
72432 ** Sync the file.
72433 **
72434 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72435 ** is never called in a working implementation.  This implementation
72436 ** exists purely as a contingency, in case some malfunction in some other
72437 ** part of SQLite causes Sync to be called by mistake.
72438 */
72439 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
72440   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72441   return SQLITE_OK;
72442 }
72443 
72444 /*
72445 ** Query the size of the file in bytes.
72446 */
72447 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72448   MemJournal *p = (MemJournal *)pJfd;
72449   *pSize = (sqlite_int64) p->endpoint.iOffset;
72450   return SQLITE_OK;
72451 }
72452 
72453 /*
72454 ** Table of methods for MemJournal sqlite3_file object.
72455 */
72456 static const struct sqlite3_io_methods MemJournalMethods = {
72457   1,                /* iVersion */
72458   memjrnlClose,     /* xClose */
72459   memjrnlRead,      /* xRead */
72460   memjrnlWrite,     /* xWrite */
72461   memjrnlTruncate,  /* xTruncate */
72462   memjrnlSync,      /* xSync */
72463   memjrnlFileSize,  /* xFileSize */
72464   0,                /* xLock */
72465   0,                /* xUnlock */
72466   0,                /* xCheckReservedLock */
72467   0,                /* xFileControl */
72468   0,                /* xSectorSize */
72469   0,                /* xDeviceCharacteristics */
72470   0,                /* xShmMap */
72471   0,                /* xShmLock */
72472   0,                /* xShmBarrier */
72473   0                 /* xShmUnlock */
72474 };
72475 
72476 /*
72477 ** Open a journal file.
72478 */
72479 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
72480   MemJournal *p = (MemJournal *)pJfd;
72481   assert( EIGHT_BYTE_ALIGNMENT(p) );
72482   memset(p, 0, sqlite3MemJournalSize());
72483   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
72484 }
72485 
72486 /*
72487 ** Return true if the file-handle passed as an argument is
72488 ** an in-memory journal
72489 */
72490 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
72491   return pJfd->pMethods==&MemJournalMethods;
72492 }
72493 
72494 /*
72495 ** Return the number of bytes required to store a MemJournal file descriptor.
72496 */
72497 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
72498   return sizeof(MemJournal);
72499 }
72500 
72501 /************** End of memjournal.c ******************************************/
72502 /************** Begin file walker.c ******************************************/
72503 /*
72504 ** 2008 August 16
72505 **
72506 ** The author disclaims copyright to this source code.  In place of
72507 ** a legal notice, here is a blessing:
72508 **
72509 **    May you do good and not evil.
72510 **    May you find forgiveness for yourself and forgive others.
72511 **    May you share freely, never taking more than you give.
72512 **
72513 *************************************************************************
72514 ** This file contains routines used for walking the parser tree for
72515 ** an SQL statement.
72516 */
72517 /* #include <stdlib.h> */
72518 /* #include <string.h> */
72519 
72520 
72521 /*
72522 ** Walk an expression tree.  Invoke the callback once for each node
72523 ** of the expression, while decending.  (In other words, the callback
72524 ** is invoked before visiting children.)
72525 **
72526 ** The return value from the callback should be one of the WRC_*
72527 ** constants to specify how to proceed with the walk.
72528 **
72529 **    WRC_Continue      Continue descending down the tree.
72530 **
72531 **    WRC_Prune         Do not descend into child nodes.  But allow
72532 **                      the walk to continue with sibling nodes.
72533 **
72534 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
72535 **                      return the top-level walk call.
72536 **
72537 ** The return value from this routine is WRC_Abort to abandon the tree walk
72538 ** and WRC_Continue to continue.
72539 */
72540 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
72541   int rc;
72542   if( pExpr==0 ) return WRC_Continue;
72543   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
72544   testcase( ExprHasProperty(pExpr, EP_Reduced) );
72545   rc = pWalker->xExprCallback(pWalker, pExpr);
72546   if( rc==WRC_Continue
72547               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
72548     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
72549     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
72550     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72551       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
72552     }else{
72553       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
72554     }
72555   }
72556   return rc & WRC_Abort;
72557 }
72558 
72559 /*
72560 ** Call sqlite3WalkExpr() for every expression in list p or until
72561 ** an abort request is seen.
72562 */
72563 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
72564   int i;
72565   struct ExprList_item *pItem;
72566   if( p ){
72567     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
72568       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
72569     }
72570   }
72571   return WRC_Continue;
72572 }
72573 
72574 /*
72575 ** Walk all expressions associated with SELECT statement p.  Do
72576 ** not invoke the SELECT callback on p, but do (of course) invoke
72577 ** any expr callbacks and SELECT callbacks that come from subqueries.
72578 ** Return WRC_Abort or WRC_Continue.
72579 */
72580 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
72581   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
72582   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
72583   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
72584   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
72585   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
72586   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
72587   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
72588   return WRC_Continue;
72589 }
72590 
72591 /*
72592 ** Walk the parse trees associated with all subqueries in the
72593 ** FROM clause of SELECT statement p.  Do not invoke the select
72594 ** callback on p, but do invoke it on each FROM clause subquery
72595 ** and on any subqueries further down in the tree.  Return
72596 ** WRC_Abort or WRC_Continue;
72597 */
72598 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
72599   SrcList *pSrc;
72600   int i;
72601   struct SrcList_item *pItem;
72602 
72603   pSrc = p->pSrc;
72604   if( ALWAYS(pSrc) ){
72605     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
72606       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
72607         return WRC_Abort;
72608       }
72609     }
72610   }
72611   return WRC_Continue;
72612 }
72613 
72614 /*
72615 ** Call sqlite3WalkExpr() for every expression in Select statement p.
72616 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
72617 ** on the compound select chain, p->pPrior.
72618 **
72619 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
72620 ** there is an abort request.
72621 **
72622 ** If the Walker does not have an xSelectCallback() then this routine
72623 ** is a no-op returning WRC_Continue.
72624 */
72625 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
72626   int rc;
72627   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
72628   rc = WRC_Continue;
72629   pWalker->walkerDepth++;
72630   while( p ){
72631     rc = pWalker->xSelectCallback(pWalker, p);
72632     if( rc ) break;
72633     if( sqlite3WalkSelectExpr(pWalker, p)
72634      || sqlite3WalkSelectFrom(pWalker, p)
72635     ){
72636       pWalker->walkerDepth--;
72637       return WRC_Abort;
72638     }
72639     p = p->pPrior;
72640   }
72641   pWalker->walkerDepth--;
72642   return rc & WRC_Abort;
72643 }
72644 
72645 /************** End of walker.c **********************************************/
72646 /************** Begin file resolve.c *****************************************/
72647 /*
72648 ** 2008 August 18
72649 **
72650 ** The author disclaims copyright to this source code.  In place of
72651 ** a legal notice, here is a blessing:
72652 **
72653 **    May you do good and not evil.
72654 **    May you find forgiveness for yourself and forgive others.
72655 **    May you share freely, never taking more than you give.
72656 **
72657 *************************************************************************
72658 **
72659 ** This file contains routines used for walking the parser tree and
72660 ** resolve all identifiers by associating them with a particular
72661 ** table and column.
72662 */
72663 /* #include <stdlib.h> */
72664 /* #include <string.h> */
72665 
72666 /*
72667 ** Walk the expression tree pExpr and increase the aggregate function
72668 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
72669 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
72670 ** outer query into an inner subquery.
72671 **
72672 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
72673 ** is a helper function - a callback for the tree walker.
72674 */
72675 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
72676   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
72677   return WRC_Continue;
72678 }
72679 static void incrAggFunctionDepth(Expr *pExpr, int N){
72680   if( N>0 ){
72681     Walker w;
72682     memset(&w, 0, sizeof(w));
72683     w.xExprCallback = incrAggDepth;
72684     w.u.i = N;
72685     sqlite3WalkExpr(&w, pExpr);
72686   }
72687 }
72688 
72689 /*
72690 ** Turn the pExpr expression into an alias for the iCol-th column of the
72691 ** result set in pEList.
72692 **
72693 ** If the result set column is a simple column reference, then this routine
72694 ** makes an exact copy.  But for any other kind of expression, this
72695 ** routine make a copy of the result set column as the argument to the
72696 ** TK_AS operator.  The TK_AS operator causes the expression to be
72697 ** evaluated just once and then reused for each alias.
72698 **
72699 ** The reason for suppressing the TK_AS term when the expression is a simple
72700 ** column reference is so that the column reference will be recognized as
72701 ** usable by indices within the WHERE clause processing logic.
72702 **
72703 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
72704 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
72705 **
72706 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
72707 **
72708 ** Is equivalent to:
72709 **
72710 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
72711 **
72712 ** The result of random()%5 in the GROUP BY clause is probably different
72713 ** from the result in the result-set.  We might fix this someday.  Or
72714 ** then again, we might not...
72715 **
72716 ** If the reference is followed by a COLLATE operator, then make sure
72717 ** the COLLATE operator is preserved.  For example:
72718 **
72719 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
72720 **
72721 ** Should be transformed into:
72722 **
72723 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
72724 **
72725 ** The nSubquery parameter specifies how many levels of subquery the
72726 ** alias is removed from the original expression.  The usually value is
72727 ** zero but it might be more if the alias is contained within a subquery
72728 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
72729 ** structures must be increased by the nSubquery amount.
72730 */
72731 static void resolveAlias(
72732   Parse *pParse,         /* Parsing context */
72733   ExprList *pEList,      /* A result set */
72734   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
72735   Expr *pExpr,           /* Transform this into an alias to the result set */
72736   const char *zType,     /* "GROUP" or "ORDER" or "" */
72737   int nSubquery          /* Number of subqueries that the label is moving */
72738 ){
72739   Expr *pOrig;           /* The iCol-th column of the result set */
72740   Expr *pDup;            /* Copy of pOrig */
72741   sqlite3 *db;           /* The database connection */
72742 
72743   assert( iCol>=0 && iCol<pEList->nExpr );
72744   pOrig = pEList->a[iCol].pExpr;
72745   assert( pOrig!=0 );
72746   assert( pOrig->flags & EP_Resolved );
72747   db = pParse->db;
72748   pDup = sqlite3ExprDup(db, pOrig, 0);
72749   if( pDup==0 ) return;
72750   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
72751     incrAggFunctionDepth(pDup, nSubquery);
72752     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
72753     if( pDup==0 ) return;
72754     if( pEList->a[iCol].iAlias==0 ){
72755       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
72756     }
72757     pDup->iTable = pEList->a[iCol].iAlias;
72758   }
72759   if( pExpr->op==TK_COLLATE ){
72760     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
72761   }
72762 
72763   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
72764   ** prevents ExprDelete() from deleting the Expr structure itself,
72765   ** allowing it to be repopulated by the memcpy() on the following line.
72766   ** The pExpr->u.zToken might point into memory that will be freed by the
72767   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
72768   ** make a copy of the token before doing the sqlite3DbFree().
72769   */
72770   ExprSetProperty(pExpr, EP_Static);
72771   sqlite3ExprDelete(db, pExpr);
72772   memcpy(pExpr, pDup, sizeof(*pExpr));
72773   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
72774     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
72775     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
72776     pExpr->flags2 |= EP2_MallocedToken;
72777   }
72778   sqlite3DbFree(db, pDup);
72779 }
72780 
72781 
72782 /*
72783 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
72784 **
72785 ** Return FALSE if the USING clause is NULL or if it does not contain
72786 ** zCol.
72787 */
72788 static int nameInUsingClause(IdList *pUsing, const char *zCol){
72789   if( pUsing ){
72790     int k;
72791     for(k=0; k<pUsing->nId; k++){
72792       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
72793     }
72794   }
72795   return 0;
72796 }
72797 
72798 /*
72799 ** Subqueries stores the original database, table and column names for their
72800 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
72801 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
72802 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
72803 ** match anything.
72804 */
72805 SQLITE_PRIVATE int sqlite3MatchSpanName(
72806   const char *zSpan,
72807   const char *zCol,
72808   const char *zTab,
72809   const char *zDb
72810 ){
72811   int n;
72812   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
72813   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
72814     return 0;
72815   }
72816   zSpan += n+1;
72817   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
72818   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
72819     return 0;
72820   }
72821   zSpan += n+1;
72822   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
72823     return 0;
72824   }
72825   return 1;
72826 }
72827 
72828 /*
72829 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
72830 ** that name in the set of source tables in pSrcList and make the pExpr
72831 ** expression node refer back to that source column.  The following changes
72832 ** are made to pExpr:
72833 **
72834 **    pExpr->iDb           Set the index in db->aDb[] of the database X
72835 **                         (even if X is implied).
72836 **    pExpr->iTable        Set to the cursor number for the table obtained
72837 **                         from pSrcList.
72838 **    pExpr->pTab          Points to the Table structure of X.Y (even if
72839 **                         X and/or Y are implied.)
72840 **    pExpr->iColumn       Set to the column number within the table.
72841 **    pExpr->op            Set to TK_COLUMN.
72842 **    pExpr->pLeft         Any expression this points to is deleted
72843 **    pExpr->pRight        Any expression this points to is deleted.
72844 **
72845 ** The zDb variable is the name of the database (the "X").  This value may be
72846 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
72847 ** can be used.  The zTable variable is the name of the table (the "Y").  This
72848 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
72849 ** means that the form of the name is Z and that columns from any table
72850 ** can be used.
72851 **
72852 ** If the name cannot be resolved unambiguously, leave an error message
72853 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
72854 */
72855 static int lookupName(
72856   Parse *pParse,       /* The parsing context */
72857   const char *zDb,     /* Name of the database containing table, or NULL */
72858   const char *zTab,    /* Name of table containing column, or NULL */
72859   const char *zCol,    /* Name of the column. */
72860   NameContext *pNC,    /* The name context used to resolve the name */
72861   Expr *pExpr          /* Make this EXPR node point to the selected column */
72862 ){
72863   int i, j;                         /* Loop counters */
72864   int cnt = 0;                      /* Number of matching column names */
72865   int cntTab = 0;                   /* Number of matching table names */
72866   int nSubquery = 0;                /* How many levels of subquery */
72867   sqlite3 *db = pParse->db;         /* The database connection */
72868   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
72869   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
72870   NameContext *pTopNC = pNC;        /* First namecontext in the list */
72871   Schema *pSchema = 0;              /* Schema of the expression */
72872   int isTrigger = 0;
72873 
72874   assert( pNC );     /* the name context cannot be NULL. */
72875   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
72876   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72877 
72878   /* Initialize the node to no-match */
72879   pExpr->iTable = -1;
72880   pExpr->pTab = 0;
72881   ExprSetIrreducible(pExpr);
72882 
72883   /* Translate the schema name in zDb into a pointer to the corresponding
72884   ** schema.  If not found, pSchema will remain NULL and nothing will match
72885   ** resulting in an appropriate error message toward the end of this routine
72886   */
72887   if( zDb ){
72888     for(i=0; i<db->nDb; i++){
72889       assert( db->aDb[i].zName );
72890       if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
72891         pSchema = db->aDb[i].pSchema;
72892         break;
72893       }
72894     }
72895   }
72896 
72897   /* Start at the inner-most context and move outward until a match is found */
72898   while( pNC && cnt==0 ){
72899     ExprList *pEList;
72900     SrcList *pSrcList = pNC->pSrcList;
72901 
72902     if( pSrcList ){
72903       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
72904         Table *pTab;
72905         Column *pCol;
72906 
72907         pTab = pItem->pTab;
72908         assert( pTab!=0 && pTab->zName!=0 );
72909         assert( pTab->nCol>0 );
72910         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
72911           int hit = 0;
72912           pEList = pItem->pSelect->pEList;
72913           for(j=0; j<pEList->nExpr; j++){
72914             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
72915               cnt++;
72916               cntTab = 2;
72917               pMatch = pItem;
72918               pExpr->iColumn = j;
72919               hit = 1;
72920             }
72921           }
72922           if( hit || zTab==0 ) continue;
72923         }
72924         if( zDb && pTab->pSchema!=pSchema ){
72925           continue;
72926         }
72927         if( zTab ){
72928           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
72929           assert( zTabName!=0 );
72930           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
72931             continue;
72932           }
72933         }
72934         if( 0==(cntTab++) ){
72935           pMatch = pItem;
72936         }
72937         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
72938           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72939             /* If there has been exactly one prior match and this match
72940             ** is for the right-hand table of a NATURAL JOIN or is in a
72941             ** USING clause, then skip this match.
72942             */
72943             if( cnt==1 ){
72944               if( pItem->jointype & JT_NATURAL ) continue;
72945               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
72946             }
72947             cnt++;
72948             pMatch = pItem;
72949             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
72950             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
72951             break;
72952           }
72953         }
72954       }
72955       if( pMatch ){
72956         pExpr->iTable = pMatch->iCursor;
72957         pExpr->pTab = pMatch->pTab;
72958         pSchema = pExpr->pTab->pSchema;
72959       }
72960     } /* if( pSrcList ) */
72961 
72962 #ifndef SQLITE_OMIT_TRIGGER
72963     /* If we have not already resolved the name, then maybe
72964     ** it is a new.* or old.* trigger argument reference
72965     */
72966     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
72967       int op = pParse->eTriggerOp;
72968       Table *pTab = 0;
72969       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
72970       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
72971         pExpr->iTable = 1;
72972         pTab = pParse->pTriggerTab;
72973       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
72974         pExpr->iTable = 0;
72975         pTab = pParse->pTriggerTab;
72976       }
72977 
72978       if( pTab ){
72979         int iCol;
72980         pSchema = pTab->pSchema;
72981         cntTab++;
72982         for(iCol=0; iCol<pTab->nCol; iCol++){
72983           Column *pCol = &pTab->aCol[iCol];
72984           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72985             if( iCol==pTab->iPKey ){
72986               iCol = -1;
72987             }
72988             break;
72989           }
72990         }
72991         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
72992           iCol = -1;        /* IMP: R-44911-55124 */
72993         }
72994         if( iCol<pTab->nCol ){
72995           cnt++;
72996           if( iCol<0 ){
72997             pExpr->affinity = SQLITE_AFF_INTEGER;
72998           }else if( pExpr->iTable==0 ){
72999             testcase( iCol==31 );
73000             testcase( iCol==32 );
73001             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73002           }else{
73003             testcase( iCol==31 );
73004             testcase( iCol==32 );
73005             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73006           }
73007           pExpr->iColumn = (i16)iCol;
73008           pExpr->pTab = pTab;
73009           isTrigger = 1;
73010         }
73011       }
73012     }
73013 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
73014 
73015     /*
73016     ** Perhaps the name is a reference to the ROWID
73017     */
73018     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
73019       cnt = 1;
73020       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
73021       pExpr->affinity = SQLITE_AFF_INTEGER;
73022     }
73023 
73024     /*
73025     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
73026     ** might refer to an result-set alias.  This happens, for example, when
73027     ** we are resolving names in the WHERE clause of the following command:
73028     **
73029     **     SELECT a+b AS x FROM table WHERE x<10;
73030     **
73031     ** In cases like this, replace pExpr with a copy of the expression that
73032     ** forms the result set entry ("a+b" in the example) and return immediately.
73033     ** Note that the expression in the result set should have already been
73034     ** resolved by the time the WHERE clause is resolved.
73035     */
73036     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
73037       for(j=0; j<pEList->nExpr; j++){
73038         char *zAs = pEList->a[j].zName;
73039         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73040           Expr *pOrig;
73041           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
73042           assert( pExpr->x.pList==0 );
73043           assert( pExpr->x.pSelect==0 );
73044           pOrig = pEList->a[j].pExpr;
73045           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
73046             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
73047             return WRC_Abort;
73048           }
73049           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
73050           cnt = 1;
73051           pMatch = 0;
73052           assert( zTab==0 && zDb==0 );
73053           goto lookupname_end;
73054         }
73055       }
73056     }
73057 
73058     /* Advance to the next name context.  The loop will exit when either
73059     ** we have a match (cnt>0) or when we run out of name contexts.
73060     */
73061     if( cnt==0 ){
73062       pNC = pNC->pNext;
73063       nSubquery++;
73064     }
73065   }
73066 
73067   /*
73068   ** If X and Y are NULL (in other words if only the column name Z is
73069   ** supplied) and the value of Z is enclosed in double-quotes, then
73070   ** Z is a string literal if it doesn't match any column names.  In that
73071   ** case, we need to return right away and not make any changes to
73072   ** pExpr.
73073   **
73074   ** Because no reference was made to outer contexts, the pNC->nRef
73075   ** fields are not changed in any context.
73076   */
73077   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
73078     pExpr->op = TK_STRING;
73079     pExpr->pTab = 0;
73080     return WRC_Prune;
73081   }
73082 
73083   /*
73084   ** cnt==0 means there was not match.  cnt>1 means there were two or
73085   ** more matches.  Either way, we have an error.
73086   */
73087   if( cnt!=1 ){
73088     const char *zErr;
73089     zErr = cnt==0 ? "no such column" : "ambiguous column name";
73090     if( zDb ){
73091       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
73092     }else if( zTab ){
73093       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
73094     }else{
73095       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
73096     }
73097     pParse->checkSchema = 1;
73098     pTopNC->nErr++;
73099   }
73100 
73101   /* If a column from a table in pSrcList is referenced, then record
73102   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
73103   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
73104   ** column number is greater than the number of bits in the bitmask
73105   ** then set the high-order bit of the bitmask.
73106   */
73107   if( pExpr->iColumn>=0 && pMatch!=0 ){
73108     int n = pExpr->iColumn;
73109     testcase( n==BMS-1 );
73110     if( n>=BMS ){
73111       n = BMS-1;
73112     }
73113     assert( pMatch->iCursor==pExpr->iTable );
73114     pMatch->colUsed |= ((Bitmask)1)<<n;
73115   }
73116 
73117   /* Clean up and return
73118   */
73119   sqlite3ExprDelete(db, pExpr->pLeft);
73120   pExpr->pLeft = 0;
73121   sqlite3ExprDelete(db, pExpr->pRight);
73122   pExpr->pRight = 0;
73123   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
73124 lookupname_end:
73125   if( cnt==1 ){
73126     assert( pNC!=0 );
73127     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
73128     /* Increment the nRef value on all name contexts from TopNC up to
73129     ** the point where the name matched. */
73130     for(;;){
73131       assert( pTopNC!=0 );
73132       pTopNC->nRef++;
73133       if( pTopNC==pNC ) break;
73134       pTopNC = pTopNC->pNext;
73135     }
73136     return WRC_Prune;
73137   } else {
73138     return WRC_Abort;
73139   }
73140 }
73141 
73142 /*
73143 ** Allocate and return a pointer to an expression to load the column iCol
73144 ** from datasource iSrc in SrcList pSrc.
73145 */
73146 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
73147   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
73148   if( p ){
73149     struct SrcList_item *pItem = &pSrc->a[iSrc];
73150     p->pTab = pItem->pTab;
73151     p->iTable = pItem->iCursor;
73152     if( p->pTab->iPKey==iCol ){
73153       p->iColumn = -1;
73154     }else{
73155       p->iColumn = (ynVar)iCol;
73156       testcase( iCol==BMS );
73157       testcase( iCol==BMS-1 );
73158       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
73159     }
73160     ExprSetProperty(p, EP_Resolved);
73161   }
73162   return p;
73163 }
73164 
73165 /*
73166 ** This routine is callback for sqlite3WalkExpr().
73167 **
73168 ** Resolve symbolic names into TK_COLUMN operators for the current
73169 ** node in the expression tree.  Return 0 to continue the search down
73170 ** the tree or 2 to abort the tree walk.
73171 **
73172 ** This routine also does error checking and name resolution for
73173 ** function names.  The operator for aggregate functions is changed
73174 ** to TK_AGG_FUNCTION.
73175 */
73176 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
73177   NameContext *pNC;
73178   Parse *pParse;
73179 
73180   pNC = pWalker->u.pNC;
73181   assert( pNC!=0 );
73182   pParse = pNC->pParse;
73183   assert( pParse==pWalker->pParse );
73184 
73185   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
73186   ExprSetProperty(pExpr, EP_Resolved);
73187 #ifndef NDEBUG
73188   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
73189     SrcList *pSrcList = pNC->pSrcList;
73190     int i;
73191     for(i=0; i<pNC->pSrcList->nSrc; i++){
73192       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
73193     }
73194   }
73195 #endif
73196   switch( pExpr->op ){
73197 
73198 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
73199     /* The special operator TK_ROW means use the rowid for the first
73200     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
73201     ** clause processing on UPDATE and DELETE statements.
73202     */
73203     case TK_ROW: {
73204       SrcList *pSrcList = pNC->pSrcList;
73205       struct SrcList_item *pItem;
73206       assert( pSrcList && pSrcList->nSrc==1 );
73207       pItem = pSrcList->a;
73208       pExpr->op = TK_COLUMN;
73209       pExpr->pTab = pItem->pTab;
73210       pExpr->iTable = pItem->iCursor;
73211       pExpr->iColumn = -1;
73212       pExpr->affinity = SQLITE_AFF_INTEGER;
73213       break;
73214     }
73215 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
73216 
73217     /* A lone identifier is the name of a column.
73218     */
73219     case TK_ID: {
73220       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73221     }
73222 
73223     /* A table name and column name:     ID.ID
73224     ** Or a database, table and column:  ID.ID.ID
73225     */
73226     case TK_DOT: {
73227       const char *zColumn;
73228       const char *zTable;
73229       const char *zDb;
73230       Expr *pRight;
73231 
73232       /* if( pSrcList==0 ) break; */
73233       pRight = pExpr->pRight;
73234       if( pRight->op==TK_ID ){
73235         zDb = 0;
73236         zTable = pExpr->pLeft->u.zToken;
73237         zColumn = pRight->u.zToken;
73238       }else{
73239         assert( pRight->op==TK_DOT );
73240         zDb = pExpr->pLeft->u.zToken;
73241         zTable = pRight->pLeft->u.zToken;
73242         zColumn = pRight->pRight->u.zToken;
73243       }
73244       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73245     }
73246 
73247     /* Resolve function names
73248     */
73249     case TK_CONST_FUNC:
73250     case TK_FUNCTION: {
73251       ExprList *pList = pExpr->x.pList;    /* The argument list */
73252       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73253       int no_such_func = 0;       /* True if no such function exists */
73254       int wrong_num_args = 0;     /* True if wrong number of arguments */
73255       int is_agg = 0;             /* True if is an aggregate function */
73256       int auth;                   /* Authorization to use the function */
73257       int nId;                    /* Number of characters in function name */
73258       const char *zId;            /* The function name. */
73259       FuncDef *pDef;              /* Information about the function */
73260       u8 enc = ENC(pParse->db);   /* The database encoding */
73261 
73262       testcase( pExpr->op==TK_CONST_FUNC );
73263       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73264       zId = pExpr->u.zToken;
73265       nId = sqlite3Strlen30(zId);
73266       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
73267       if( pDef==0 ){
73268         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
73269         if( pDef==0 ){
73270           no_such_func = 1;
73271         }else{
73272           wrong_num_args = 1;
73273         }
73274       }else{
73275         is_agg = pDef->xFunc==0;
73276       }
73277 #ifndef SQLITE_OMIT_AUTHORIZATION
73278       if( pDef ){
73279         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
73280         if( auth!=SQLITE_OK ){
73281           if( auth==SQLITE_DENY ){
73282             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
73283                                     pDef->zName);
73284             pNC->nErr++;
73285           }
73286           pExpr->op = TK_NULL;
73287           return WRC_Prune;
73288         }
73289       }
73290 #endif
73291       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
73292         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73293         pNC->nErr++;
73294         is_agg = 0;
73295       }else if( no_such_func && pParse->db->init.busy==0 ){
73296         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73297         pNC->nErr++;
73298       }else if( wrong_num_args ){
73299         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73300              nId, zId);
73301         pNC->nErr++;
73302       }
73303       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
73304       sqlite3WalkExprList(pWalker, pList);
73305       if( is_agg ){
73306         NameContext *pNC2 = pNC;
73307         pExpr->op = TK_AGG_FUNCTION;
73308         pExpr->op2 = 0;
73309         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
73310           pExpr->op2++;
73311           pNC2 = pNC2->pNext;
73312         }
73313         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
73314         pNC->ncFlags |= NC_AllowAgg;
73315       }
73316       /* FIX ME:  Compute pExpr->affinity based on the expected return
73317       ** type of the function
73318       */
73319       return WRC_Prune;
73320     }
73321 #ifndef SQLITE_OMIT_SUBQUERY
73322     case TK_SELECT:
73323     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73324 #endif
73325     case TK_IN: {
73326       testcase( pExpr->op==TK_IN );
73327       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73328         int nRef = pNC->nRef;
73329 #ifndef SQLITE_OMIT_CHECK
73330         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
73331           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73332         }
73333 #endif
73334         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
73335         assert( pNC->nRef>=nRef );
73336         if( nRef!=pNC->nRef ){
73337           ExprSetProperty(pExpr, EP_VarSelect);
73338         }
73339       }
73340       break;
73341     }
73342 #ifndef SQLITE_OMIT_CHECK
73343     case TK_VARIABLE: {
73344       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
73345         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73346       }
73347       break;
73348     }
73349 #endif
73350   }
73351   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73352 }
73353 
73354 /*
73355 ** pEList is a list of expressions which are really the result set of the
73356 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73357 ** This routine checks to see if pE is a simple identifier which corresponds
73358 ** to the AS-name of one of the terms of the expression list.  If it is,
73359 ** this routine return an integer between 1 and N where N is the number of
73360 ** elements in pEList, corresponding to the matching entry.  If there is
73361 ** no match, or if pE is not a simple identifier, then this routine
73362 ** return 0.
73363 **
73364 ** pEList has been resolved.  pE has not.
73365 */
73366 static int resolveAsName(
73367   Parse *pParse,     /* Parsing context for error messages */
73368   ExprList *pEList,  /* List of expressions to scan */
73369   Expr *pE           /* Expression we are trying to match */
73370 ){
73371   int i;             /* Loop counter */
73372 
73373   UNUSED_PARAMETER(pParse);
73374 
73375   if( pE->op==TK_ID ){
73376     char *zCol = pE->u.zToken;
73377     for(i=0; i<pEList->nExpr; i++){
73378       char *zAs = pEList->a[i].zName;
73379       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73380         return i+1;
73381       }
73382     }
73383   }
73384   return 0;
73385 }
73386 
73387 /*
73388 ** pE is a pointer to an expression which is a single term in the
73389 ** ORDER BY of a compound SELECT.  The expression has not been
73390 ** name resolved.
73391 **
73392 ** At the point this routine is called, we already know that the
73393 ** ORDER BY term is not an integer index into the result set.  That
73394 ** case is handled by the calling routine.
73395 **
73396 ** Attempt to match pE against result set columns in the left-most
73397 ** SELECT statement.  Return the index i of the matching column,
73398 ** as an indication to the caller that it should sort by the i-th column.
73399 ** The left-most column is 1.  In other words, the value returned is the
73400 ** same integer value that would be used in the SQL statement to indicate
73401 ** the column.
73402 **
73403 ** If there is no match, return 0.  Return -1 if an error occurs.
73404 */
73405 static int resolveOrderByTermToExprList(
73406   Parse *pParse,     /* Parsing context for error messages */
73407   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73408   Expr *pE           /* The specific ORDER BY term */
73409 ){
73410   int i;             /* Loop counter */
73411   ExprList *pEList;  /* The columns of the result set */
73412   NameContext nc;    /* Name context for resolving pE */
73413   sqlite3 *db;       /* Database connection */
73414   int rc;            /* Return code from subprocedures */
73415   u8 savedSuppErr;   /* Saved value of db->suppressErr */
73416 
73417   assert( sqlite3ExprIsInteger(pE, &i)==0 );
73418   pEList = pSelect->pEList;
73419 
73420   /* Resolve all names in the ORDER BY term expression
73421   */
73422   memset(&nc, 0, sizeof(nc));
73423   nc.pParse = pParse;
73424   nc.pSrcList = pSelect->pSrc;
73425   nc.pEList = pEList;
73426   nc.ncFlags = NC_AllowAgg;
73427   nc.nErr = 0;
73428   db = pParse->db;
73429   savedSuppErr = db->suppressErr;
73430   db->suppressErr = 1;
73431   rc = sqlite3ResolveExprNames(&nc, pE);
73432   db->suppressErr = savedSuppErr;
73433   if( rc ) return 0;
73434 
73435   /* Try to match the ORDER BY expression against an expression
73436   ** in the result set.  Return an 1-based index of the matching
73437   ** result-set entry.
73438   */
73439   for(i=0; i<pEList->nExpr; i++){
73440     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73441       return i+1;
73442     }
73443   }
73444 
73445   /* If no match, return 0. */
73446   return 0;
73447 }
73448 
73449 /*
73450 ** Generate an ORDER BY or GROUP BY term out-of-range error.
73451 */
73452 static void resolveOutOfRangeError(
73453   Parse *pParse,         /* The error context into which to write the error */
73454   const char *zType,     /* "ORDER" or "GROUP" */
73455   int i,                 /* The index (1-based) of the term out of range */
73456   int mx                 /* Largest permissible value of i */
73457 ){
73458   sqlite3ErrorMsg(pParse,
73459     "%r %s BY term out of range - should be "
73460     "between 1 and %d", i, zType, mx);
73461 }
73462 
73463 /*
73464 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73465 ** each term of the ORDER BY clause is a constant integer between 1
73466 ** and N where N is the number of columns in the compound SELECT.
73467 **
73468 ** ORDER BY terms that are already an integer between 1 and N are
73469 ** unmodified.  ORDER BY terms that are integers outside the range of
73470 ** 1 through N generate an error.  ORDER BY terms that are expressions
73471 ** are matched against result set expressions of compound SELECT
73472 ** beginning with the left-most SELECT and working toward the right.
73473 ** At the first match, the ORDER BY expression is transformed into
73474 ** the integer column number.
73475 **
73476 ** Return the number of errors seen.
73477 */
73478 static int resolveCompoundOrderBy(
73479   Parse *pParse,        /* Parsing context.  Leave error messages here */
73480   Select *pSelect       /* The SELECT statement containing the ORDER BY */
73481 ){
73482   int i;
73483   ExprList *pOrderBy;
73484   ExprList *pEList;
73485   sqlite3 *db;
73486   int moreToDo = 1;
73487 
73488   pOrderBy = pSelect->pOrderBy;
73489   if( pOrderBy==0 ) return 0;
73490   db = pParse->db;
73491 #if SQLITE_MAX_COLUMN
73492   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73493     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73494     return 1;
73495   }
73496 #endif
73497   for(i=0; i<pOrderBy->nExpr; i++){
73498     pOrderBy->a[i].done = 0;
73499   }
73500   pSelect->pNext = 0;
73501   while( pSelect->pPrior ){
73502     pSelect->pPrior->pNext = pSelect;
73503     pSelect = pSelect->pPrior;
73504   }
73505   while( pSelect && moreToDo ){
73506     struct ExprList_item *pItem;
73507     moreToDo = 0;
73508     pEList = pSelect->pEList;
73509     assert( pEList!=0 );
73510     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73511       int iCol = -1;
73512       Expr *pE, *pDup;
73513       if( pItem->done ) continue;
73514       pE = sqlite3ExprSkipCollate(pItem->pExpr);
73515       if( sqlite3ExprIsInteger(pE, &iCol) ){
73516         if( iCol<=0 || iCol>pEList->nExpr ){
73517           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73518           return 1;
73519         }
73520       }else{
73521         iCol = resolveAsName(pParse, pEList, pE);
73522         if( iCol==0 ){
73523           pDup = sqlite3ExprDup(db, pE, 0);
73524           if( !db->mallocFailed ){
73525             assert(pDup);
73526             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73527           }
73528           sqlite3ExprDelete(db, pDup);
73529         }
73530       }
73531       if( iCol>0 ){
73532         /* Convert the ORDER BY term into an integer column number iCol,
73533         ** taking care to preserve the COLLATE clause if it exists */
73534         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
73535         if( pNew==0 ) return 1;
73536         pNew->flags |= EP_IntValue;
73537         pNew->u.iValue = iCol;
73538         if( pItem->pExpr==pE ){
73539           pItem->pExpr = pNew;
73540         }else{
73541           assert( pItem->pExpr->op==TK_COLLATE );
73542           assert( pItem->pExpr->pLeft==pE );
73543           pItem->pExpr->pLeft = pNew;
73544         }
73545         sqlite3ExprDelete(db, pE);
73546         pItem->iOrderByCol = (u16)iCol;
73547         pItem->done = 1;
73548       }else{
73549         moreToDo = 1;
73550       }
73551     }
73552     pSelect = pSelect->pNext;
73553   }
73554   for(i=0; i<pOrderBy->nExpr; i++){
73555     if( pOrderBy->a[i].done==0 ){
73556       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73557             "column in the result set", i+1);
73558       return 1;
73559     }
73560   }
73561   return 0;
73562 }
73563 
73564 /*
73565 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
73566 ** the SELECT statement pSelect.  If any term is reference to a
73567 ** result set expression (as determined by the ExprList.a.iCol field)
73568 ** then convert that term into a copy of the corresponding result set
73569 ** column.
73570 **
73571 ** If any errors are detected, add an error message to pParse and
73572 ** return non-zero.  Return zero if no errors are seen.
73573 */
73574 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
73575   Parse *pParse,        /* Parsing context.  Leave error messages here */
73576   Select *pSelect,      /* The SELECT statement containing the clause */
73577   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
73578   const char *zType     /* "ORDER" or "GROUP" */
73579 ){
73580   int i;
73581   sqlite3 *db = pParse->db;
73582   ExprList *pEList;
73583   struct ExprList_item *pItem;
73584 
73585   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
73586 #if SQLITE_MAX_COLUMN
73587   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73588     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
73589     return 1;
73590   }
73591 #endif
73592   pEList = pSelect->pEList;
73593   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
73594   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73595     if( pItem->iOrderByCol ){
73596       if( pItem->iOrderByCol>pEList->nExpr ){
73597         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
73598         return 1;
73599       }
73600       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
73601     }
73602   }
73603   return 0;
73604 }
73605 
73606 /*
73607 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
73608 ** The Name context of the SELECT statement is pNC.  zType is either
73609 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
73610 **
73611 ** This routine resolves each term of the clause into an expression.
73612 ** If the order-by term is an integer I between 1 and N (where N is the
73613 ** number of columns in the result set of the SELECT) then the expression
73614 ** in the resolution is a copy of the I-th result-set expression.  If
73615 ** the order-by term is an identify that corresponds to the AS-name of
73616 ** a result-set expression, then the term resolves to a copy of the
73617 ** result-set expression.  Otherwise, the expression is resolved in
73618 ** the usual way - using sqlite3ResolveExprNames().
73619 **
73620 ** This routine returns the number of errors.  If errors occur, then
73621 ** an appropriate error message might be left in pParse.  (OOM errors
73622 ** excepted.)
73623 */
73624 static int resolveOrderGroupBy(
73625   NameContext *pNC,     /* The name context of the SELECT statement */
73626   Select *pSelect,      /* The SELECT statement holding pOrderBy */
73627   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
73628   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
73629 ){
73630   int i, j;                      /* Loop counters */
73631   int iCol;                      /* Column number */
73632   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
73633   Parse *pParse;                 /* Parsing context */
73634   int nResult;                   /* Number of terms in the result set */
73635 
73636   if( pOrderBy==0 ) return 0;
73637   nResult = pSelect->pEList->nExpr;
73638   pParse = pNC->pParse;
73639   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73640     Expr *pE = pItem->pExpr;
73641     iCol = resolveAsName(pParse, pSelect->pEList, pE);
73642     if( iCol>0 ){
73643       /* If an AS-name match is found, mark this ORDER BY column as being
73644       ** a copy of the iCol-th result-set column.  The subsequent call to
73645       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
73646       ** copy of the iCol-th result-set expression. */
73647       pItem->iOrderByCol = (u16)iCol;
73648       continue;
73649     }
73650     if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
73651       /* The ORDER BY term is an integer constant.  Again, set the column
73652       ** number so that sqlite3ResolveOrderGroupBy() will convert the
73653       ** order-by term to a copy of the result-set expression */
73654       if( iCol<1 || iCol>0xffff ){
73655         resolveOutOfRangeError(pParse, zType, i+1, nResult);
73656         return 1;
73657       }
73658       pItem->iOrderByCol = (u16)iCol;
73659       continue;
73660     }
73661 
73662     /* Otherwise, treat the ORDER BY term as an ordinary expression */
73663     pItem->iOrderByCol = 0;
73664     if( sqlite3ResolveExprNames(pNC, pE) ){
73665       return 1;
73666     }
73667     for(j=0; j<pSelect->pEList->nExpr; j++){
73668       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
73669         pItem->iOrderByCol = j+1;
73670       }
73671     }
73672   }
73673   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
73674 }
73675 
73676 /*
73677 ** Resolve names in the SELECT statement p and all of its descendents.
73678 */
73679 static int resolveSelectStep(Walker *pWalker, Select *p){
73680   NameContext *pOuterNC;  /* Context that contains this SELECT */
73681   NameContext sNC;        /* Name context of this SELECT */
73682   int isCompound;         /* True if p is a compound select */
73683   int nCompound;          /* Number of compound terms processed so far */
73684   Parse *pParse;          /* Parsing context */
73685   ExprList *pEList;       /* Result set expression list */
73686   int i;                  /* Loop counter */
73687   ExprList *pGroupBy;     /* The GROUP BY clause */
73688   Select *pLeftmost;      /* Left-most of SELECT of a compound */
73689   sqlite3 *db;            /* Database connection */
73690 
73691 
73692   assert( p!=0 );
73693   if( p->selFlags & SF_Resolved ){
73694     return WRC_Prune;
73695   }
73696   pOuterNC = pWalker->u.pNC;
73697   pParse = pWalker->pParse;
73698   db = pParse->db;
73699 
73700   /* Normally sqlite3SelectExpand() will be called first and will have
73701   ** already expanded this SELECT.  However, if this is a subquery within
73702   ** an expression, sqlite3ResolveExprNames() will be called without a
73703   ** prior call to sqlite3SelectExpand().  When that happens, let
73704   ** sqlite3SelectPrep() do all of the processing for this SELECT.
73705   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
73706   ** this routine in the correct order.
73707   */
73708   if( (p->selFlags & SF_Expanded)==0 ){
73709     sqlite3SelectPrep(pParse, p, pOuterNC);
73710     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
73711   }
73712 
73713   isCompound = p->pPrior!=0;
73714   nCompound = 0;
73715   pLeftmost = p;
73716   while( p ){
73717     assert( (p->selFlags & SF_Expanded)!=0 );
73718     assert( (p->selFlags & SF_Resolved)==0 );
73719     p->selFlags |= SF_Resolved;
73720 
73721     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
73722     ** are not allowed to refer to any names, so pass an empty NameContext.
73723     */
73724     memset(&sNC, 0, sizeof(sNC));
73725     sNC.pParse = pParse;
73726     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
73727         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
73728       return WRC_Abort;
73729     }
73730 
73731     /* Recursively resolve names in all subqueries
73732     */
73733     for(i=0; i<p->pSrc->nSrc; i++){
73734       struct SrcList_item *pItem = &p->pSrc->a[i];
73735       if( pItem->pSelect ){
73736         NameContext *pNC;         /* Used to iterate name contexts */
73737         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
73738         const char *zSavedContext = pParse->zAuthContext;
73739 
73740         /* Count the total number of references to pOuterNC and all of its
73741         ** parent contexts. After resolving references to expressions in
73742         ** pItem->pSelect, check if this value has changed. If so, then
73743         ** SELECT statement pItem->pSelect must be correlated. Set the
73744         ** pItem->isCorrelated flag if this is the case. */
73745         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
73746 
73747         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
73748         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
73749         pParse->zAuthContext = zSavedContext;
73750         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
73751 
73752         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
73753         assert( pItem->isCorrelated==0 && nRef<=0 );
73754         pItem->isCorrelated = (nRef!=0);
73755       }
73756     }
73757 
73758     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
73759     ** resolve the result-set expression list.
73760     */
73761     sNC.ncFlags = NC_AllowAgg;
73762     sNC.pSrcList = p->pSrc;
73763     sNC.pNext = pOuterNC;
73764 
73765     /* Resolve names in the result set. */
73766     pEList = p->pEList;
73767     assert( pEList!=0 );
73768     for(i=0; i<pEList->nExpr; i++){
73769       Expr *pX = pEList->a[i].pExpr;
73770       if( sqlite3ResolveExprNames(&sNC, pX) ){
73771         return WRC_Abort;
73772       }
73773     }
73774 
73775     /* If there are no aggregate functions in the result-set, and no GROUP BY
73776     ** expression, do not allow aggregates in any of the other expressions.
73777     */
73778     assert( (p->selFlags & SF_Aggregate)==0 );
73779     pGroupBy = p->pGroupBy;
73780     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
73781       p->selFlags |= SF_Aggregate;
73782     }else{
73783       sNC.ncFlags &= ~NC_AllowAgg;
73784     }
73785 
73786     /* If a HAVING clause is present, then there must be a GROUP BY clause.
73787     */
73788     if( p->pHaving && !pGroupBy ){
73789       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
73790       return WRC_Abort;
73791     }
73792 
73793     /* Add the expression list to the name-context before parsing the
73794     ** other expressions in the SELECT statement. This is so that
73795     ** expressions in the WHERE clause (etc.) can refer to expressions by
73796     ** aliases in the result set.
73797     **
73798     ** Minor point: If this is the case, then the expression will be
73799     ** re-evaluated for each reference to it.
73800     */
73801     sNC.pEList = p->pEList;
73802     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
73803        sqlite3ResolveExprNames(&sNC, p->pHaving)
73804     ){
73805       return WRC_Abort;
73806     }
73807 
73808     /* The ORDER BY and GROUP BY clauses may not refer to terms in
73809     ** outer queries
73810     */
73811     sNC.pNext = 0;
73812     sNC.ncFlags |= NC_AllowAgg;
73813 
73814     /* Process the ORDER BY clause for singleton SELECT statements.
73815     ** The ORDER BY clause for compounds SELECT statements is handled
73816     ** below, after all of the result-sets for all of the elements of
73817     ** the compound have been resolved.
73818     */
73819     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
73820       return WRC_Abort;
73821     }
73822     if( db->mallocFailed ){
73823       return WRC_Abort;
73824     }
73825 
73826     /* Resolve the GROUP BY clause.  At the same time, make sure
73827     ** the GROUP BY clause does not contain aggregate functions.
73828     */
73829     if( pGroupBy ){
73830       struct ExprList_item *pItem;
73831 
73832       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
73833         return WRC_Abort;
73834       }
73835       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
73836         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
73837           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
73838               "the GROUP BY clause");
73839           return WRC_Abort;
73840         }
73841       }
73842     }
73843 
73844     /* Advance to the next term of the compound
73845     */
73846     p = p->pPrior;
73847     nCompound++;
73848   }
73849 
73850   /* Resolve the ORDER BY on a compound SELECT after all terms of
73851   ** the compound have been resolved.
73852   */
73853   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
73854     return WRC_Abort;
73855   }
73856 
73857   return WRC_Prune;
73858 }
73859 
73860 /*
73861 ** This routine walks an expression tree and resolves references to
73862 ** table columns and result-set columns.  At the same time, do error
73863 ** checking on function usage and set a flag if any aggregate functions
73864 ** are seen.
73865 **
73866 ** To resolve table columns references we look for nodes (or subtrees) of the
73867 ** form X.Y.Z or Y.Z or just Z where
73868 **
73869 **      X:   The name of a database.  Ex:  "main" or "temp" or
73870 **           the symbolic name assigned to an ATTACH-ed database.
73871 **
73872 **      Y:   The name of a table in a FROM clause.  Or in a trigger
73873 **           one of the special names "old" or "new".
73874 **
73875 **      Z:   The name of a column in table Y.
73876 **
73877 ** The node at the root of the subtree is modified as follows:
73878 **
73879 **    Expr.op        Changed to TK_COLUMN
73880 **    Expr.pTab      Points to the Table object for X.Y
73881 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
73882 **    Expr.iTable    The VDBE cursor number for X.Y
73883 **
73884 **
73885 ** To resolve result-set references, look for expression nodes of the
73886 ** form Z (with no X and Y prefix) where the Z matches the right-hand
73887 ** size of an AS clause in the result-set of a SELECT.  The Z expression
73888 ** is replaced by a copy of the left-hand side of the result-set expression.
73889 ** Table-name and function resolution occurs on the substituted expression
73890 ** tree.  For example, in:
73891 **
73892 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
73893 **
73894 ** The "x" term of the order by is replaced by "a+b" to render:
73895 **
73896 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
73897 **
73898 ** Function calls are checked to make sure that the function is
73899 ** defined and that the correct number of arguments are specified.
73900 ** If the function is an aggregate function, then the NC_HasAgg flag is
73901 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
73902 ** If an expression contains aggregate functions then the EP_Agg
73903 ** property on the expression is set.
73904 **
73905 ** An error message is left in pParse if anything is amiss.  The number
73906 ** if errors is returned.
73907 */
73908 SQLITE_PRIVATE int sqlite3ResolveExprNames(
73909   NameContext *pNC,       /* Namespace to resolve expressions in. */
73910   Expr *pExpr             /* The expression to be analyzed. */
73911 ){
73912   u8 savedHasAgg;
73913   Walker w;
73914 
73915   if( pExpr==0 ) return 0;
73916 #if SQLITE_MAX_EXPR_DEPTH>0
73917   {
73918     Parse *pParse = pNC->pParse;
73919     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
73920       return 1;
73921     }
73922     pParse->nHeight += pExpr->nHeight;
73923   }
73924 #endif
73925   savedHasAgg = pNC->ncFlags & NC_HasAgg;
73926   pNC->ncFlags &= ~NC_HasAgg;
73927   w.xExprCallback = resolveExprStep;
73928   w.xSelectCallback = resolveSelectStep;
73929   w.pParse = pNC->pParse;
73930   w.u.pNC = pNC;
73931   sqlite3WalkExpr(&w, pExpr);
73932 #if SQLITE_MAX_EXPR_DEPTH>0
73933   pNC->pParse->nHeight -= pExpr->nHeight;
73934 #endif
73935   if( pNC->nErr>0 || w.pParse->nErr>0 ){
73936     ExprSetProperty(pExpr, EP_Error);
73937   }
73938   if( pNC->ncFlags & NC_HasAgg ){
73939     ExprSetProperty(pExpr, EP_Agg);
73940   }else if( savedHasAgg ){
73941     pNC->ncFlags |= NC_HasAgg;
73942   }
73943   return ExprHasProperty(pExpr, EP_Error);
73944 }
73945 
73946 
73947 /*
73948 ** Resolve all names in all expressions of a SELECT and in all
73949 ** decendents of the SELECT, including compounds off of p->pPrior,
73950 ** subqueries in expressions, and subqueries used as FROM clause
73951 ** terms.
73952 **
73953 ** See sqlite3ResolveExprNames() for a description of the kinds of
73954 ** transformations that occur.
73955 **
73956 ** All SELECT statements should have been expanded using
73957 ** sqlite3SelectExpand() prior to invoking this routine.
73958 */
73959 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
73960   Parse *pParse,         /* The parser context */
73961   Select *p,             /* The SELECT statement being coded. */
73962   NameContext *pOuterNC  /* Name context for parent SELECT statement */
73963 ){
73964   Walker w;
73965 
73966   assert( p!=0 );
73967   w.xExprCallback = resolveExprStep;
73968   w.xSelectCallback = resolveSelectStep;
73969   w.pParse = pParse;
73970   w.u.pNC = pOuterNC;
73971   sqlite3WalkSelect(&w, p);
73972 }
73973 
73974 /************** End of resolve.c *********************************************/
73975 /************** Begin file expr.c ********************************************/
73976 /*
73977 ** 2001 September 15
73978 **
73979 ** The author disclaims copyright to this source code.  In place of
73980 ** a legal notice, here is a blessing:
73981 **
73982 **    May you do good and not evil.
73983 **    May you find forgiveness for yourself and forgive others.
73984 **    May you share freely, never taking more than you give.
73985 **
73986 *************************************************************************
73987 ** This file contains routines used for analyzing expressions and
73988 ** for generating VDBE code that evaluates expressions in SQLite.
73989 */
73990 
73991 /*
73992 ** Return the 'affinity' of the expression pExpr if any.
73993 **
73994 ** If pExpr is a column, a reference to a column via an 'AS' alias,
73995 ** or a sub-select with a column as the return value, then the
73996 ** affinity of that column is returned. Otherwise, 0x00 is returned,
73997 ** indicating no affinity for the expression.
73998 **
73999 ** i.e. the WHERE clause expresssions in the following statements all
74000 ** have an affinity:
74001 **
74002 ** CREATE TABLE t1(a);
74003 ** SELECT * FROM t1 WHERE a;
74004 ** SELECT a AS b FROM t1 WHERE b;
74005 ** SELECT * FROM t1 WHERE (select a from t1);
74006 */
74007 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
74008   int op;
74009   pExpr = sqlite3ExprSkipCollate(pExpr);
74010   op = pExpr->op;
74011   if( op==TK_SELECT ){
74012     assert( pExpr->flags&EP_xIsSelect );
74013     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
74014   }
74015 #ifndef SQLITE_OMIT_CAST
74016   if( op==TK_CAST ){
74017     assert( !ExprHasProperty(pExpr, EP_IntValue) );
74018     return sqlite3AffinityType(pExpr->u.zToken);
74019   }
74020 #endif
74021   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
74022    && pExpr->pTab!=0
74023   ){
74024     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
74025     ** a TK_COLUMN but was previously evaluated and cached in a register */
74026     int j = pExpr->iColumn;
74027     if( j<0 ) return SQLITE_AFF_INTEGER;
74028     assert( pExpr->pTab && j<pExpr->pTab->nCol );
74029     return pExpr->pTab->aCol[j].affinity;
74030   }
74031   return pExpr->affinity;
74032 }
74033 
74034 /*
74035 ** Set the collating sequence for expression pExpr to be the collating
74036 ** sequence named by pToken.   Return a pointer to a new Expr node that
74037 ** implements the COLLATE operator.
74038 **
74039 ** If a memory allocation error occurs, that fact is recorded in pParse->db
74040 ** and the pExpr parameter is returned unchanged.
74041 */
74042 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
74043   if( pCollName->n>0 ){
74044     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
74045     if( pNew ){
74046       pNew->pLeft = pExpr;
74047       pNew->flags |= EP_Collate;
74048       pExpr = pNew;
74049     }
74050   }
74051   return pExpr;
74052 }
74053 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
74054   Token s;
74055   assert( zC!=0 );
74056   s.z = zC;
74057   s.n = sqlite3Strlen30(s.z);
74058   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
74059 }
74060 
74061 /*
74062 ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
74063 ** an expression.
74064 */
74065 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
74066   while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
74067     pExpr = pExpr->pLeft;
74068   }
74069   return pExpr;
74070 }
74071 
74072 /*
74073 ** Return the collation sequence for the expression pExpr. If
74074 ** there is no defined collating sequence, return NULL.
74075 **
74076 ** The collating sequence might be determined by a COLLATE operator
74077 ** or by the presence of a column with a defined collating sequence.
74078 ** COLLATE operators take first precedence.  Left operands take
74079 ** precedence over right operands.
74080 */
74081 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
74082   sqlite3 *db = pParse->db;
74083   CollSeq *pColl = 0;
74084   Expr *p = pExpr;
74085   while( p ){
74086     int op = p->op;
74087     if( op==TK_CAST || op==TK_UPLUS ){
74088       p = p->pLeft;
74089       continue;
74090     }
74091     assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
74092     if( op==TK_COLLATE ){
74093       if( db->init.busy ){
74094         /* Do not report errors when parsing while the schema */
74095         pColl = sqlite3FindCollSeq(db, ENC(db), p->u.zToken, 0);
74096       }else{
74097         pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
74098       }
74099       break;
74100     }
74101     if( p->pTab!=0
74102      && (op==TK_AGG_COLUMN || op==TK_COLUMN
74103           || op==TK_REGISTER || op==TK_TRIGGER)
74104     ){
74105       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
74106       ** a TK_COLUMN but was previously evaluated and cached in a register */
74107       int j = p->iColumn;
74108       if( j>=0 ){
74109         const char *zColl = p->pTab->aCol[j].zColl;
74110         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
74111       }
74112       break;
74113     }
74114     if( p->flags & EP_Collate ){
74115       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
74116         p = p->pLeft;
74117       }else{
74118         p = p->pRight;
74119       }
74120     }else{
74121       break;
74122     }
74123   }
74124   if( sqlite3CheckCollSeq(pParse, pColl) ){
74125     pColl = 0;
74126   }
74127   return pColl;
74128 }
74129 
74130 /*
74131 ** pExpr is an operand of a comparison operator.  aff2 is the
74132 ** type affinity of the other operand.  This routine returns the
74133 ** type affinity that should be used for the comparison operator.
74134 */
74135 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
74136   char aff1 = sqlite3ExprAffinity(pExpr);
74137   if( aff1 && aff2 ){
74138     /* Both sides of the comparison are columns. If one has numeric
74139     ** affinity, use that. Otherwise use no affinity.
74140     */
74141     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
74142       return SQLITE_AFF_NUMERIC;
74143     }else{
74144       return SQLITE_AFF_NONE;
74145     }
74146   }else if( !aff1 && !aff2 ){
74147     /* Neither side of the comparison is a column.  Compare the
74148     ** results directly.
74149     */
74150     return SQLITE_AFF_NONE;
74151   }else{
74152     /* One side is a column, the other is not. Use the columns affinity. */
74153     assert( aff1==0 || aff2==0 );
74154     return (aff1 + aff2);
74155   }
74156 }
74157 
74158 /*
74159 ** pExpr is a comparison operator.  Return the type affinity that should
74160 ** be applied to both operands prior to doing the comparison.
74161 */
74162 static char comparisonAffinity(Expr *pExpr){
74163   char aff;
74164   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
74165           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
74166           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
74167   assert( pExpr->pLeft );
74168   aff = sqlite3ExprAffinity(pExpr->pLeft);
74169   if( pExpr->pRight ){
74170     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
74171   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74172     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
74173   }else if( !aff ){
74174     aff = SQLITE_AFF_NONE;
74175   }
74176   return aff;
74177 }
74178 
74179 /*
74180 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
74181 ** idx_affinity is the affinity of an indexed column. Return true
74182 ** if the index with affinity idx_affinity may be used to implement
74183 ** the comparison in pExpr.
74184 */
74185 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
74186   char aff = comparisonAffinity(pExpr);
74187   switch( aff ){
74188     case SQLITE_AFF_NONE:
74189       return 1;
74190     case SQLITE_AFF_TEXT:
74191       return idx_affinity==SQLITE_AFF_TEXT;
74192     default:
74193       return sqlite3IsNumericAffinity(idx_affinity);
74194   }
74195 }
74196 
74197 /*
74198 ** Return the P5 value that should be used for a binary comparison
74199 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
74200 */
74201 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
74202   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
74203   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74204   return aff;
74205 }
74206 
74207 /*
74208 ** Return a pointer to the collation sequence that should be used by
74209 ** a binary comparison operator comparing pLeft and pRight.
74210 **
74211 ** If the left hand expression has a collating sequence type, then it is
74212 ** used. Otherwise the collation sequence for the right hand expression
74213 ** is used, or the default (BINARY) if neither expression has a collating
74214 ** type.
74215 **
74216 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
74217 ** it is not considered.
74218 */
74219 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
74220   Parse *pParse,
74221   Expr *pLeft,
74222   Expr *pRight
74223 ){
74224   CollSeq *pColl;
74225   assert( pLeft );
74226   if( pLeft->flags & EP_Collate ){
74227     pColl = sqlite3ExprCollSeq(pParse, pLeft);
74228   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
74229     pColl = sqlite3ExprCollSeq(pParse, pRight);
74230   }else{
74231     pColl = sqlite3ExprCollSeq(pParse, pLeft);
74232     if( !pColl ){
74233       pColl = sqlite3ExprCollSeq(pParse, pRight);
74234     }
74235   }
74236   return pColl;
74237 }
74238 
74239 /*
74240 ** Generate code for a comparison operator.
74241 */
74242 static int codeCompare(
74243   Parse *pParse,    /* The parsing (and code generating) context */
74244   Expr *pLeft,      /* The left operand */
74245   Expr *pRight,     /* The right operand */
74246   int opcode,       /* The comparison opcode */
74247   int in1, int in2, /* Register holding operands */
74248   int dest,         /* Jump here if true.  */
74249   int jumpIfNull    /* If true, jump if either operand is NULL */
74250 ){
74251   int p5;
74252   int addr;
74253   CollSeq *p4;
74254 
74255   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
74256   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74257   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74258                            (void*)p4, P4_COLLSEQ);
74259   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74260   return addr;
74261 }
74262 
74263 #if SQLITE_MAX_EXPR_DEPTH>0
74264 /*
74265 ** Check that argument nHeight is less than or equal to the maximum
74266 ** expression depth allowed. If it is not, leave an error message in
74267 ** pParse.
74268 */
74269 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
74270   int rc = SQLITE_OK;
74271   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
74272   if( nHeight>mxHeight ){
74273     sqlite3ErrorMsg(pParse,
74274        "Expression tree is too large (maximum depth %d)", mxHeight
74275     );
74276     rc = SQLITE_ERROR;
74277   }
74278   return rc;
74279 }
74280 
74281 /* The following three functions, heightOfExpr(), heightOfExprList()
74282 ** and heightOfSelect(), are used to determine the maximum height
74283 ** of any expression tree referenced by the structure passed as the
74284 ** first argument.
74285 **
74286 ** If this maximum height is greater than the current value pointed
74287 ** to by pnHeight, the second parameter, then set *pnHeight to that
74288 ** value.
74289 */
74290 static void heightOfExpr(Expr *p, int *pnHeight){
74291   if( p ){
74292     if( p->nHeight>*pnHeight ){
74293       *pnHeight = p->nHeight;
74294     }
74295   }
74296 }
74297 static void heightOfExprList(ExprList *p, int *pnHeight){
74298   if( p ){
74299     int i;
74300     for(i=0; i<p->nExpr; i++){
74301       heightOfExpr(p->a[i].pExpr, pnHeight);
74302     }
74303   }
74304 }
74305 static void heightOfSelect(Select *p, int *pnHeight){
74306   if( p ){
74307     heightOfExpr(p->pWhere, pnHeight);
74308     heightOfExpr(p->pHaving, pnHeight);
74309     heightOfExpr(p->pLimit, pnHeight);
74310     heightOfExpr(p->pOffset, pnHeight);
74311     heightOfExprList(p->pEList, pnHeight);
74312     heightOfExprList(p->pGroupBy, pnHeight);
74313     heightOfExprList(p->pOrderBy, pnHeight);
74314     heightOfSelect(p->pPrior, pnHeight);
74315   }
74316 }
74317 
74318 /*
74319 ** Set the Expr.nHeight variable in the structure passed as an
74320 ** argument. An expression with no children, Expr.pList or
74321 ** Expr.pSelect member has a height of 1. Any other expression
74322 ** has a height equal to the maximum height of any other
74323 ** referenced Expr plus one.
74324 */
74325 static void exprSetHeight(Expr *p){
74326   int nHeight = 0;
74327   heightOfExpr(p->pLeft, &nHeight);
74328   heightOfExpr(p->pRight, &nHeight);
74329   if( ExprHasProperty(p, EP_xIsSelect) ){
74330     heightOfSelect(p->x.pSelect, &nHeight);
74331   }else{
74332     heightOfExprList(p->x.pList, &nHeight);
74333   }
74334   p->nHeight = nHeight + 1;
74335 }
74336 
74337 /*
74338 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
74339 ** the height is greater than the maximum allowed expression depth,
74340 ** leave an error in pParse.
74341 */
74342 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
74343   exprSetHeight(p);
74344   sqlite3ExprCheckHeight(pParse, p->nHeight);
74345 }
74346 
74347 /*
74348 ** Return the maximum height of any expression tree referenced
74349 ** by the select statement passed as an argument.
74350 */
74351 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
74352   int nHeight = 0;
74353   heightOfSelect(p, &nHeight);
74354   return nHeight;
74355 }
74356 #else
74357   #define exprSetHeight(y)
74358 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
74359 
74360 /*
74361 ** This routine is the core allocator for Expr nodes.
74362 **
74363 ** Construct a new expression node and return a pointer to it.  Memory
74364 ** for this node and for the pToken argument is a single allocation
74365 ** obtained from sqlite3DbMalloc().  The calling function
74366 ** is responsible for making sure the node eventually gets freed.
74367 **
74368 ** If dequote is true, then the token (if it exists) is dequoted.
74369 ** If dequote is false, no dequoting is performance.  The deQuote
74370 ** parameter is ignored if pToken is NULL or if the token does not
74371 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74372 ** then the EP_DblQuoted flag is set on the expression node.
74373 **
74374 ** Special case:  If op==TK_INTEGER and pToken points to a string that
74375 ** can be translated into a 32-bit integer, then the token is not
74376 ** stored in u.zToken.  Instead, the integer values is written
74377 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
74378 ** is allocated to hold the integer text and the dequote flag is ignored.
74379 */
74380 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
74381   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74382   int op,                 /* Expression opcode */
74383   const Token *pToken,    /* Token argument.  Might be NULL */
74384   int dequote             /* True to dequote */
74385 ){
74386   Expr *pNew;
74387   int nExtra = 0;
74388   int iValue = 0;
74389 
74390   if( pToken ){
74391     if( op!=TK_INTEGER || pToken->z==0
74392           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
74393       nExtra = pToken->n+1;
74394       assert( iValue>=0 );
74395     }
74396   }
74397   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
74398   if( pNew ){
74399     pNew->op = (u8)op;
74400     pNew->iAgg = -1;
74401     if( pToken ){
74402       if( nExtra==0 ){
74403         pNew->flags |= EP_IntValue;
74404         pNew->u.iValue = iValue;
74405       }else{
74406         int c;
74407         pNew->u.zToken = (char*)&pNew[1];
74408         assert( pToken->z!=0 || pToken->n==0 );
74409         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74410         pNew->u.zToken[pToken->n] = 0;
74411         if( dequote && nExtra>=3
74412              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74413           sqlite3Dequote(pNew->u.zToken);
74414           if( c=='"' ) pNew->flags |= EP_DblQuoted;
74415         }
74416       }
74417     }
74418 #if SQLITE_MAX_EXPR_DEPTH>0
74419     pNew->nHeight = 1;
74420 #endif
74421   }
74422   return pNew;
74423 }
74424 
74425 /*
74426 ** Allocate a new expression node from a zero-terminated token that has
74427 ** already been dequoted.
74428 */
74429 SQLITE_PRIVATE Expr *sqlite3Expr(
74430   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74431   int op,                 /* Expression opcode */
74432   const char *zToken      /* Token argument.  Might be NULL */
74433 ){
74434   Token x;
74435   x.z = zToken;
74436   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
74437   return sqlite3ExprAlloc(db, op, &x, 0);
74438 }
74439 
74440 /*
74441 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
74442 **
74443 ** If pRoot==NULL that means that a memory allocation error has occurred.
74444 ** In that case, delete the subtrees pLeft and pRight.
74445 */
74446 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
74447   sqlite3 *db,
74448   Expr *pRoot,
74449   Expr *pLeft,
74450   Expr *pRight
74451 ){
74452   if( pRoot==0 ){
74453     assert( db->mallocFailed );
74454     sqlite3ExprDelete(db, pLeft);
74455     sqlite3ExprDelete(db, pRight);
74456   }else{
74457     if( pRight ){
74458       pRoot->pRight = pRight;
74459       pRoot->flags |= EP_Collate & pRight->flags;
74460     }
74461     if( pLeft ){
74462       pRoot->pLeft = pLeft;
74463       pRoot->flags |= EP_Collate & pLeft->flags;
74464     }
74465     exprSetHeight(pRoot);
74466   }
74467 }
74468 
74469 /*
74470 ** Allocate a Expr node which joins as many as two subtrees.
74471 **
74472 ** One or both of the subtrees can be NULL.  Return a pointer to the new
74473 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74474 ** free the subtrees and return NULL.
74475 */
74476 SQLITE_PRIVATE Expr *sqlite3PExpr(
74477   Parse *pParse,          /* Parsing context */
74478   int op,                 /* Expression opcode */
74479   Expr *pLeft,            /* Left operand */
74480   Expr *pRight,           /* Right operand */
74481   const Token *pToken     /* Argument token */
74482 ){
74483   Expr *p;
74484   if( op==TK_AND && pLeft && pRight ){
74485     /* Take advantage of short-circuit false optimization for AND */
74486     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
74487   }else{
74488     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
74489     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74490   }
74491   if( p ) {
74492     sqlite3ExprCheckHeight(pParse, p->nHeight);
74493   }
74494   return p;
74495 }
74496 
74497 /*
74498 ** Return 1 if an expression must be FALSE in all cases and 0 if the
74499 ** expression might be true.  This is an optimization.  If is OK to
74500 ** return 0 here even if the expression really is always false (a
74501 ** false negative).  But it is a bug to return 1 if the expression
74502 ** might be true in some rare circumstances (a false positive.)
74503 **
74504 ** Note that if the expression is part of conditional for a
74505 ** LEFT JOIN, then we cannot determine at compile-time whether or not
74506 ** is it true or false, so always return 0.
74507 */
74508 static int exprAlwaysFalse(Expr *p){
74509   int v = 0;
74510   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
74511   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
74512   return v==0;
74513 }
74514 
74515 /*
74516 ** Join two expressions using an AND operator.  If either expression is
74517 ** NULL, then just return the other expression.
74518 **
74519 ** If one side or the other of the AND is known to be false, then instead
74520 ** of returning an AND expression, just return a constant expression with
74521 ** a value of false.
74522 */
74523 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
74524   if( pLeft==0 ){
74525     return pRight;
74526   }else if( pRight==0 ){
74527     return pLeft;
74528   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
74529     sqlite3ExprDelete(db, pLeft);
74530     sqlite3ExprDelete(db, pRight);
74531     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
74532   }else{
74533     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
74534     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74535     return pNew;
74536   }
74537 }
74538 
74539 /*
74540 ** Construct a new expression node for a function with multiple
74541 ** arguments.
74542 */
74543 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74544   Expr *pNew;
74545   sqlite3 *db = pParse->db;
74546   assert( pToken );
74547   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74548   if( pNew==0 ){
74549     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74550     return 0;
74551   }
74552   pNew->x.pList = pList;
74553   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74554   sqlite3ExprSetHeight(pParse, pNew);
74555   return pNew;
74556 }
74557 
74558 /*
74559 ** Assign a variable number to an expression that encodes a wildcard
74560 ** in the original SQL statement.
74561 **
74562 ** Wildcards consisting of a single "?" are assigned the next sequential
74563 ** variable number.
74564 **
74565 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74566 ** sure "nnn" is not too be to avoid a denial of service attack when
74567 ** the SQL statement comes from an external source.
74568 **
74569 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74570 ** as the previous instance of the same wildcard.  Or if this is the first
74571 ** instance of the wildcard, the next sequenial variable number is
74572 ** assigned.
74573 */
74574 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74575   sqlite3 *db = pParse->db;
74576   const char *z;
74577 
74578   if( pExpr==0 ) return;
74579   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74580   z = pExpr->u.zToken;
74581   assert( z!=0 );
74582   assert( z[0]!=0 );
74583   if( z[1]==0 ){
74584     /* Wildcard of the form "?".  Assign the next variable number */
74585     assert( z[0]=='?' );
74586     pExpr->iColumn = (ynVar)(++pParse->nVar);
74587   }else{
74588     ynVar x = 0;
74589     u32 n = sqlite3Strlen30(z);
74590     if( z[0]=='?' ){
74591       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74592       ** use it as the variable number */
74593       i64 i;
74594       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
74595       pExpr->iColumn = x = (ynVar)i;
74596       testcase( i==0 );
74597       testcase( i==1 );
74598       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
74599       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
74600       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74601         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74602             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
74603         x = 0;
74604       }
74605       if( i>pParse->nVar ){
74606         pParse->nVar = (int)i;
74607       }
74608     }else{
74609       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74610       ** number as the prior appearance of the same name, or if the name
74611       ** has never appeared before, reuse the same variable number
74612       */
74613       ynVar i;
74614       for(i=0; i<pParse->nzVar; i++){
74615         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
74616           pExpr->iColumn = x = (ynVar)i+1;
74617           break;
74618         }
74619       }
74620       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74621     }
74622     if( x>0 ){
74623       if( x>pParse->nzVar ){
74624         char **a;
74625         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
74626         if( a==0 ) return;  /* Error reported through db->mallocFailed */
74627         pParse->azVar = a;
74628         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
74629         pParse->nzVar = x;
74630       }
74631       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
74632         sqlite3DbFree(db, pParse->azVar[x-1]);
74633         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
74634       }
74635     }
74636   }
74637   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74638     sqlite3ErrorMsg(pParse, "too many SQL variables");
74639   }
74640 }
74641 
74642 /*
74643 ** Recursively delete an expression tree.
74644 */
74645 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
74646   if( p==0 ) return;
74647   /* Sanity check: Assert that the IntValue is non-negative if it exists */
74648   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
74649   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74650     sqlite3ExprDelete(db, p->pLeft);
74651     sqlite3ExprDelete(db, p->pRight);
74652     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
74653       sqlite3DbFree(db, p->u.zToken);
74654     }
74655     if( ExprHasProperty(p, EP_xIsSelect) ){
74656       sqlite3SelectDelete(db, p->x.pSelect);
74657     }else{
74658       sqlite3ExprListDelete(db, p->x.pList);
74659     }
74660   }
74661   if( !ExprHasProperty(p, EP_Static) ){
74662     sqlite3DbFree(db, p);
74663   }
74664 }
74665 
74666 /*
74667 ** Return the number of bytes allocated for the expression structure
74668 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
74669 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
74670 */
74671 static int exprStructSize(Expr *p){
74672   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
74673   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
74674   return EXPR_FULLSIZE;
74675 }
74676 
74677 /*
74678 ** The dupedExpr*Size() routines each return the number of bytes required
74679 ** to store a copy of an expression or expression tree.  They differ in
74680 ** how much of the tree is measured.
74681 **
74682 **     dupedExprStructSize()     Size of only the Expr structure
74683 **     dupedExprNodeSize()       Size of Expr + space for token
74684 **     dupedExprSize()           Expr + token + subtree components
74685 **
74686 ***************************************************************************
74687 **
74688 ** The dupedExprStructSize() function returns two values OR-ed together:
74689 ** (1) the space required for a copy of the Expr structure only and
74690 ** (2) the EP_xxx flags that indicate what the structure size should be.
74691 ** The return values is always one of:
74692 **
74693 **      EXPR_FULLSIZE
74694 **      EXPR_REDUCEDSIZE   | EP_Reduced
74695 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
74696 **
74697 ** The size of the structure can be found by masking the return value
74698 ** of this routine with 0xfff.  The flags can be found by masking the
74699 ** return value with EP_Reduced|EP_TokenOnly.
74700 **
74701 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
74702 ** (unreduced) Expr objects as they or originally constructed by the parser.
74703 ** During expression analysis, extra information is computed and moved into
74704 ** later parts of teh Expr object and that extra information might get chopped
74705 ** off if the expression is reduced.  Note also that it does not work to
74706 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
74707 ** to reduce a pristine expression tree from the parser.  The implementation
74708 ** of dupedExprStructSize() contain multiple assert() statements that attempt
74709 ** to enforce this constraint.
74710 */
74711 static int dupedExprStructSize(Expr *p, int flags){
74712   int nSize;
74713   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
74714   if( 0==(flags&EXPRDUP_REDUCE) ){
74715     nSize = EXPR_FULLSIZE;
74716   }else{
74717     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
74718     assert( !ExprHasProperty(p, EP_FromJoin) );
74719     assert( (p->flags2 & EP2_MallocedToken)==0 );
74720     assert( (p->flags2 & EP2_Irreducible)==0 );
74721     if( p->pLeft || p->pRight || p->x.pList ){
74722       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
74723     }else{
74724       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
74725     }
74726   }
74727   return nSize;
74728 }
74729 
74730 /*
74731 ** This function returns the space in bytes required to store the copy
74732 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
74733 ** string is defined.)
74734 */
74735 static int dupedExprNodeSize(Expr *p, int flags){
74736   int nByte = dupedExprStructSize(p, flags) & 0xfff;
74737   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74738     nByte += sqlite3Strlen30(p->u.zToken)+1;
74739   }
74740   return ROUND8(nByte);
74741 }
74742 
74743 /*
74744 ** Return the number of bytes required to create a duplicate of the
74745 ** expression passed as the first argument. The second argument is a
74746 ** mask containing EXPRDUP_XXX flags.
74747 **
74748 ** The value returned includes space to create a copy of the Expr struct
74749 ** itself and the buffer referred to by Expr.u.zToken, if any.
74750 **
74751 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
74752 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
74753 ** and Expr.pRight variables (but not for any structures pointed to or
74754 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
74755 */
74756 static int dupedExprSize(Expr *p, int flags){
74757   int nByte = 0;
74758   if( p ){
74759     nByte = dupedExprNodeSize(p, flags);
74760     if( flags&EXPRDUP_REDUCE ){
74761       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
74762     }
74763   }
74764   return nByte;
74765 }
74766 
74767 /*
74768 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
74769 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
74770 ** to store the copy of expression p, the copies of p->u.zToken
74771 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
74772 ** if any. Before returning, *pzBuffer is set to the first byte passed the
74773 ** portion of the buffer copied into by this function.
74774 */
74775 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
74776   Expr *pNew = 0;                      /* Value to return */
74777   if( p ){
74778     const int isReduced = (flags&EXPRDUP_REDUCE);
74779     u8 *zAlloc;
74780     u32 staticFlag = 0;
74781 
74782     assert( pzBuffer==0 || isReduced );
74783 
74784     /* Figure out where to write the new Expr structure. */
74785     if( pzBuffer ){
74786       zAlloc = *pzBuffer;
74787       staticFlag = EP_Static;
74788     }else{
74789       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
74790     }
74791     pNew = (Expr *)zAlloc;
74792 
74793     if( pNew ){
74794       /* Set nNewSize to the size allocated for the structure pointed to
74795       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
74796       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
74797       ** by the copy of the p->u.zToken string (if any).
74798       */
74799       const unsigned nStructSize = dupedExprStructSize(p, flags);
74800       const int nNewSize = nStructSize & 0xfff;
74801       int nToken;
74802       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
74803         nToken = sqlite3Strlen30(p->u.zToken) + 1;
74804       }else{
74805         nToken = 0;
74806       }
74807       if( isReduced ){
74808         assert( ExprHasProperty(p, EP_Reduced)==0 );
74809         memcpy(zAlloc, p, nNewSize);
74810       }else{
74811         int nSize = exprStructSize(p);
74812         memcpy(zAlloc, p, nSize);
74813         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
74814       }
74815 
74816       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
74817       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
74818       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
74819       pNew->flags |= staticFlag;
74820 
74821       /* Copy the p->u.zToken string, if any. */
74822       if( nToken ){
74823         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
74824         memcpy(zToken, p->u.zToken, nToken);
74825       }
74826 
74827       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
74828         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
74829         if( ExprHasProperty(p, EP_xIsSelect) ){
74830           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
74831         }else{
74832           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
74833         }
74834       }
74835 
74836       /* Fill in pNew->pLeft and pNew->pRight. */
74837       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
74838         zAlloc += dupedExprNodeSize(p, flags);
74839         if( ExprHasProperty(pNew, EP_Reduced) ){
74840           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
74841           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
74842         }
74843         if( pzBuffer ){
74844           *pzBuffer = zAlloc;
74845         }
74846       }else{
74847         pNew->flags2 = 0;
74848         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
74849           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
74850           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
74851         }
74852       }
74853 
74854     }
74855   }
74856   return pNew;
74857 }
74858 
74859 /*
74860 ** The following group of routines make deep copies of expressions,
74861 ** expression lists, ID lists, and select statements.  The copies can
74862 ** be deleted (by being passed to their respective ...Delete() routines)
74863 ** without effecting the originals.
74864 **
74865 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
74866 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
74867 ** by subsequent calls to sqlite*ListAppend() routines.
74868 **
74869 ** Any tables that the SrcList might point to are not duplicated.
74870 **
74871 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
74872 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
74873 ** truncated version of the usual Expr structure that will be stored as
74874 ** part of the in-memory representation of the database schema.
74875 */
74876 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
74877   return exprDup(db, p, flags, 0);
74878 }
74879 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
74880   ExprList *pNew;
74881   struct ExprList_item *pItem, *pOldItem;
74882   int i;
74883   if( p==0 ) return 0;
74884   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74885   if( pNew==0 ) return 0;
74886   pNew->iECursor = 0;
74887   pNew->nExpr = i = p->nExpr;
74888   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
74889   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
74890   if( pItem==0 ){
74891     sqlite3DbFree(db, pNew);
74892     return 0;
74893   }
74894   pOldItem = p->a;
74895   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
74896     Expr *pOldExpr = pOldItem->pExpr;
74897     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
74898     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74899     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
74900     pItem->sortOrder = pOldItem->sortOrder;
74901     pItem->done = 0;
74902     pItem->iOrderByCol = pOldItem->iOrderByCol;
74903     pItem->iAlias = pOldItem->iAlias;
74904   }
74905   return pNew;
74906 }
74907 
74908 /*
74909 ** If cursors, triggers, views and subqueries are all omitted from
74910 ** the build, then none of the following routines, except for
74911 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
74912 ** called with a NULL argument.
74913 */
74914 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
74915  || !defined(SQLITE_OMIT_SUBQUERY)
74916 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
74917   SrcList *pNew;
74918   int i;
74919   int nByte;
74920   if( p==0 ) return 0;
74921   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
74922   pNew = sqlite3DbMallocRaw(db, nByte );
74923   if( pNew==0 ) return 0;
74924   pNew->nSrc = pNew->nAlloc = p->nSrc;
74925   for(i=0; i<p->nSrc; i++){
74926     struct SrcList_item *pNewItem = &pNew->a[i];
74927     struct SrcList_item *pOldItem = &p->a[i];
74928     Table *pTab;
74929     pNewItem->pSchema = pOldItem->pSchema;
74930     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
74931     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74932     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
74933     pNewItem->jointype = pOldItem->jointype;
74934     pNewItem->iCursor = pOldItem->iCursor;
74935     pNewItem->addrFillSub = pOldItem->addrFillSub;
74936     pNewItem->regReturn = pOldItem->regReturn;
74937     pNewItem->isCorrelated = pOldItem->isCorrelated;
74938     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
74939     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
74940     pNewItem->notIndexed = pOldItem->notIndexed;
74941     pNewItem->pIndex = pOldItem->pIndex;
74942     pTab = pNewItem->pTab = pOldItem->pTab;
74943     if( pTab ){
74944       pTab->nRef++;
74945     }
74946     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
74947     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
74948     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
74949     pNewItem->colUsed = pOldItem->colUsed;
74950   }
74951   return pNew;
74952 }
74953 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
74954   IdList *pNew;
74955   int i;
74956   if( p==0 ) return 0;
74957   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
74958   if( pNew==0 ) return 0;
74959   pNew->nId = p->nId;
74960   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
74961   if( pNew->a==0 ){
74962     sqlite3DbFree(db, pNew);
74963     return 0;
74964   }
74965   /* Note that because the size of the allocation for p->a[] is not
74966   ** necessarily a power of two, sqlite3IdListAppend() may not be called
74967   ** on the duplicate created by this function. */
74968   for(i=0; i<p->nId; i++){
74969     struct IdList_item *pNewItem = &pNew->a[i];
74970     struct IdList_item *pOldItem = &p->a[i];
74971     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
74972     pNewItem->idx = pOldItem->idx;
74973   }
74974   return pNew;
74975 }
74976 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
74977   Select *pNew, *pPrior;
74978   if( p==0 ) return 0;
74979   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
74980   if( pNew==0 ) return 0;
74981   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
74982   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
74983   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
74984   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
74985   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
74986   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
74987   pNew->op = p->op;
74988   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
74989   if( pPrior ) pPrior->pNext = pNew;
74990   pNew->pNext = 0;
74991   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
74992   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
74993   pNew->iLimit = 0;
74994   pNew->iOffset = 0;
74995   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
74996   pNew->pRightmost = 0;
74997   pNew->addrOpenEphm[0] = -1;
74998   pNew->addrOpenEphm[1] = -1;
74999   pNew->addrOpenEphm[2] = -1;
75000   return pNew;
75001 }
75002 #else
75003 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
75004   assert( p==0 );
75005   return 0;
75006 }
75007 #endif
75008 
75009 
75010 /*
75011 ** Add a new element to the end of an expression list.  If pList is
75012 ** initially NULL, then create a new expression list.
75013 **
75014 ** If a memory allocation error occurs, the entire list is freed and
75015 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
75016 ** that the new entry was successfully appended.
75017 */
75018 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
75019   Parse *pParse,          /* Parsing context */
75020   ExprList *pList,        /* List to which to append. Might be NULL */
75021   Expr *pExpr             /* Expression to be appended. Might be NULL */
75022 ){
75023   sqlite3 *db = pParse->db;
75024   if( pList==0 ){
75025     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
75026     if( pList==0 ){
75027       goto no_mem;
75028     }
75029     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
75030     if( pList->a==0 ) goto no_mem;
75031   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
75032     struct ExprList_item *a;
75033     assert( pList->nExpr>0 );
75034     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
75035     if( a==0 ){
75036       goto no_mem;
75037     }
75038     pList->a = a;
75039   }
75040   assert( pList->a!=0 );
75041   if( 1 ){
75042     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
75043     memset(pItem, 0, sizeof(*pItem));
75044     pItem->pExpr = pExpr;
75045   }
75046   return pList;
75047 
75048 no_mem:
75049   /* Avoid leaking memory if malloc has failed. */
75050   sqlite3ExprDelete(db, pExpr);
75051   sqlite3ExprListDelete(db, pList);
75052   return 0;
75053 }
75054 
75055 /*
75056 ** Set the ExprList.a[].zName element of the most recently added item
75057 ** on the expression list.
75058 **
75059 ** pList might be NULL following an OOM error.  But pName should never be
75060 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75061 ** is set.
75062 */
75063 SQLITE_PRIVATE void sqlite3ExprListSetName(
75064   Parse *pParse,          /* Parsing context */
75065   ExprList *pList,        /* List to which to add the span. */
75066   Token *pName,           /* Name to be added */
75067   int dequote             /* True to cause the name to be dequoted */
75068 ){
75069   assert( pList!=0 || pParse->db->mallocFailed!=0 );
75070   if( pList ){
75071     struct ExprList_item *pItem;
75072     assert( pList->nExpr>0 );
75073     pItem = &pList->a[pList->nExpr-1];
75074     assert( pItem->zName==0 );
75075     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
75076     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
75077   }
75078 }
75079 
75080 /*
75081 ** Set the ExprList.a[].zSpan element of the most recently added item
75082 ** on the expression list.
75083 **
75084 ** pList might be NULL following an OOM error.  But pSpan should never be
75085 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75086 ** is set.
75087 */
75088 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
75089   Parse *pParse,          /* Parsing context */
75090   ExprList *pList,        /* List to which to add the span. */
75091   ExprSpan *pSpan         /* The span to be added */
75092 ){
75093   sqlite3 *db = pParse->db;
75094   assert( pList!=0 || db->mallocFailed!=0 );
75095   if( pList ){
75096     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
75097     assert( pList->nExpr>0 );
75098     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
75099     sqlite3DbFree(db, pItem->zSpan);
75100     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
75101                                     (int)(pSpan->zEnd - pSpan->zStart));
75102   }
75103 }
75104 
75105 /*
75106 ** If the expression list pEList contains more than iLimit elements,
75107 ** leave an error message in pParse.
75108 */
75109 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
75110   Parse *pParse,
75111   ExprList *pEList,
75112   const char *zObject
75113 ){
75114   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
75115   testcase( pEList && pEList->nExpr==mx );
75116   testcase( pEList && pEList->nExpr==mx+1 );
75117   if( pEList && pEList->nExpr>mx ){
75118     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
75119   }
75120 }
75121 
75122 /*
75123 ** Delete an entire expression list.
75124 */
75125 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
75126   int i;
75127   struct ExprList_item *pItem;
75128   if( pList==0 ) return;
75129   assert( pList->a!=0 || pList->nExpr==0 );
75130   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
75131     sqlite3ExprDelete(db, pItem->pExpr);
75132     sqlite3DbFree(db, pItem->zName);
75133     sqlite3DbFree(db, pItem->zSpan);
75134   }
75135   sqlite3DbFree(db, pList->a);
75136   sqlite3DbFree(db, pList);
75137 }
75138 
75139 /*
75140 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
75141 ** to an integer.  These routines are checking an expression to see
75142 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
75143 ** not constant.
75144 **
75145 ** These callback routines are used to implement the following:
75146 **
75147 **     sqlite3ExprIsConstant()
75148 **     sqlite3ExprIsConstantNotJoin()
75149 **     sqlite3ExprIsConstantOrFunction()
75150 **
75151 */
75152 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
75153 
75154   /* If pWalker->u.i is 3 then any term of the expression that comes from
75155   ** the ON or USING clauses of a join disqualifies the expression
75156   ** from being considered constant. */
75157   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
75158     pWalker->u.i = 0;
75159     return WRC_Abort;
75160   }
75161 
75162   switch( pExpr->op ){
75163     /* Consider functions to be constant if all their arguments are constant
75164     ** and pWalker->u.i==2 */
75165     case TK_FUNCTION:
75166       if( pWalker->u.i==2 ) return 0;
75167       /* Fall through */
75168     case TK_ID:
75169     case TK_COLUMN:
75170     case TK_AGG_FUNCTION:
75171     case TK_AGG_COLUMN:
75172       testcase( pExpr->op==TK_ID );
75173       testcase( pExpr->op==TK_COLUMN );
75174       testcase( pExpr->op==TK_AGG_FUNCTION );
75175       testcase( pExpr->op==TK_AGG_COLUMN );
75176       pWalker->u.i = 0;
75177       return WRC_Abort;
75178     default:
75179       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
75180       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
75181       return WRC_Continue;
75182   }
75183 }
75184 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
75185   UNUSED_PARAMETER(NotUsed);
75186   pWalker->u.i = 0;
75187   return WRC_Abort;
75188 }
75189 static int exprIsConst(Expr *p, int initFlag){
75190   Walker w;
75191   w.u.i = initFlag;
75192   w.xExprCallback = exprNodeIsConstant;
75193   w.xSelectCallback = selectNodeIsConstant;
75194   sqlite3WalkExpr(&w, p);
75195   return w.u.i;
75196 }
75197 
75198 /*
75199 ** Walk an expression tree.  Return 1 if the expression is constant
75200 ** and 0 if it involves variables or function calls.
75201 **
75202 ** For the purposes of this function, a double-quoted string (ex: "abc")
75203 ** is considered a variable but a single-quoted string (ex: 'abc') is
75204 ** a constant.
75205 */
75206 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
75207   return exprIsConst(p, 1);
75208 }
75209 
75210 /*
75211 ** Walk an expression tree.  Return 1 if the expression is constant
75212 ** that does no originate from the ON or USING clauses of a join.
75213 ** Return 0 if it involves variables or function calls or terms from
75214 ** an ON or USING clause.
75215 */
75216 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
75217   return exprIsConst(p, 3);
75218 }
75219 
75220 /*
75221 ** Walk an expression tree.  Return 1 if the expression is constant
75222 ** or a function call with constant arguments.  Return and 0 if there
75223 ** are any variables.
75224 **
75225 ** For the purposes of this function, a double-quoted string (ex: "abc")
75226 ** is considered a variable but a single-quoted string (ex: 'abc') is
75227 ** a constant.
75228 */
75229 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
75230   return exprIsConst(p, 2);
75231 }
75232 
75233 /*
75234 ** If the expression p codes a constant integer that is small enough
75235 ** to fit in a 32-bit integer, return 1 and put the value of the integer
75236 ** in *pValue.  If the expression is not an integer or if it is too big
75237 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75238 */
75239 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
75240   int rc = 0;
75241 
75242   /* If an expression is an integer literal that fits in a signed 32-bit
75243   ** integer, then the EP_IntValue flag will have already been set */
75244   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75245            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
75246 
75247   if( p->flags & EP_IntValue ){
75248     *pValue = p->u.iValue;
75249     return 1;
75250   }
75251   switch( p->op ){
75252     case TK_UPLUS: {
75253       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
75254       break;
75255     }
75256     case TK_UMINUS: {
75257       int v;
75258       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
75259         *pValue = -v;
75260         rc = 1;
75261       }
75262       break;
75263     }
75264     default: break;
75265   }
75266   return rc;
75267 }
75268 
75269 /*
75270 ** Return FALSE if there is no chance that the expression can be NULL.
75271 **
75272 ** If the expression might be NULL or if the expression is too complex
75273 ** to tell return TRUE.
75274 **
75275 ** This routine is used as an optimization, to skip OP_IsNull opcodes
75276 ** when we know that a value cannot be NULL.  Hence, a false positive
75277 ** (returning TRUE when in fact the expression can never be NULL) might
75278 ** be a small performance hit but is otherwise harmless.  On the other
75279 ** hand, a false negative (returning FALSE when the result could be NULL)
75280 ** will likely result in an incorrect answer.  So when in doubt, return
75281 ** TRUE.
75282 */
75283 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
75284   u8 op;
75285   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75286   op = p->op;
75287   if( op==TK_REGISTER ) op = p->op2;
75288   switch( op ){
75289     case TK_INTEGER:
75290     case TK_STRING:
75291     case TK_FLOAT:
75292     case TK_BLOB:
75293       return 0;
75294     default:
75295       return 1;
75296   }
75297 }
75298 
75299 /*
75300 ** Generate an OP_IsNull instruction that tests register iReg and jumps
75301 ** to location iDest if the value in iReg is NULL.  The value in iReg
75302 ** was computed by pExpr.  If we can look at pExpr at compile-time and
75303 ** determine that it can never generate a NULL, then the OP_IsNull operation
75304 ** can be omitted.
75305 */
75306 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
75307   Vdbe *v,            /* The VDBE under construction */
75308   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75309   int iReg,           /* Test the value in this register for NULL */
75310   int iDest           /* Jump here if the value is null */
75311 ){
75312   if( sqlite3ExprCanBeNull(pExpr) ){
75313     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75314   }
75315 }
75316 
75317 /*
75318 ** Return TRUE if the given expression is a constant which would be
75319 ** unchanged by OP_Affinity with the affinity given in the second
75320 ** argument.
75321 **
75322 ** This routine is used to determine if the OP_Affinity operation
75323 ** can be omitted.  When in doubt return FALSE.  A false negative
75324 ** is harmless.  A false positive, however, can result in the wrong
75325 ** answer.
75326 */
75327 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75328   u8 op;
75329   if( aff==SQLITE_AFF_NONE ) return 1;
75330   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75331   op = p->op;
75332   if( op==TK_REGISTER ) op = p->op2;
75333   switch( op ){
75334     case TK_INTEGER: {
75335       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
75336     }
75337     case TK_FLOAT: {
75338       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
75339     }
75340     case TK_STRING: {
75341       return aff==SQLITE_AFF_TEXT;
75342     }
75343     case TK_BLOB: {
75344       return 1;
75345     }
75346     case TK_COLUMN: {
75347       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75348       return p->iColumn<0
75349           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
75350     }
75351     default: {
75352       return 0;
75353     }
75354   }
75355 }
75356 
75357 /*
75358 ** Return TRUE if the given string is a row-id column name.
75359 */
75360 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
75361   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
75362   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
75363   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
75364   return 0;
75365 }
75366 
75367 /*
75368 ** Return true if we are able to the IN operator optimization on a
75369 ** query of the form
75370 **
75371 **       x IN (SELECT ...)
75372 **
75373 ** Where the SELECT... clause is as specified by the parameter to this
75374 ** routine.
75375 **
75376 ** The Select object passed in has already been preprocessed and no
75377 ** errors have been found.
75378 */
75379 #ifndef SQLITE_OMIT_SUBQUERY
75380 static int isCandidateForInOpt(Select *p){
75381   SrcList *pSrc;
75382   ExprList *pEList;
75383   Table *pTab;
75384   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75385   if( p->pPrior ) return 0;              /* Not a compound SELECT */
75386   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75387     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75388     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75389     return 0; /* No DISTINCT keyword and no aggregate functions */
75390   }
75391   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75392   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75393   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75394   if( p->pWhere ) return 0;              /* Has no WHERE clause */
75395   pSrc = p->pSrc;
75396   assert( pSrc!=0 );
75397   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75398   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75399   pTab = pSrc->a[0].pTab;
75400   if( NEVER(pTab==0) ) return 0;
75401   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75402   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75403   pEList = p->pEList;
75404   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75405   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75406   return 1;
75407 }
75408 #endif /* SQLITE_OMIT_SUBQUERY */
75409 
75410 /*
75411 ** Code an OP_Once instruction and allocate space for its flag. Return the
75412 ** address of the new instruction.
75413 */
75414 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
75415   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
75416   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
75417 }
75418 
75419 /*
75420 ** This function is used by the implementation of the IN (...) operator.
75421 ** The pX parameter is the expression on the RHS of the IN operator, which
75422 ** might be either a list of expressions or a subquery.
75423 **
75424 ** The job of this routine is to find or create a b-tree object that can
75425 ** be used either to test for membership in the RHS set or to iterate through
75426 ** all members of the RHS set, skipping duplicates.
75427 **
75428 ** A cursor is opened on the b-tree object that the RHS of the IN operator
75429 ** and pX->iTable is set to the index of that cursor.
75430 **
75431 ** The returned value of this function indicates the b-tree type, as follows:
75432 **
75433 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
75434 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
75435 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
75436 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
75437 **                         populated epheremal table.
75438 **
75439 ** An existing b-tree might be used if the RHS expression pX is a simple
75440 ** subquery such as:
75441 **
75442 **     SELECT <column> FROM <table>
75443 **
75444 ** If the RHS of the IN operator is a list or a more complex subquery, then
75445 ** an ephemeral table might need to be generated from the RHS and then
75446 ** pX->iTable made to point to the ephermeral table instead of an
75447 ** existing table.
75448 **
75449 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75450 ** through the set members, skipping any duplicates. In this case an
75451 ** epheremal table must be used unless the selected <column> is guaranteed
75452 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
75453 ** has a UNIQUE constraint or UNIQUE index.
75454 **
75455 ** If the prNotFound parameter is not 0, then the b-tree will be used
75456 ** for fast set membership tests. In this case an epheremal table must
75457 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
75458 ** be found with <column> as its left-most column.
75459 **
75460 ** When the b-tree is being used for membership tests, the calling function
75461 ** needs to know whether or not the structure contains an SQL NULL
75462 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75463 ** If there is any chance that the (...) might contain a NULL value at
75464 ** runtime, then a register is allocated and the register number written
75465 ** to *prNotFound. If there is no chance that the (...) contains a
75466 ** NULL value, then *prNotFound is left unchanged.
75467 **
75468 ** If a register is allocated and its location stored in *prNotFound, then
75469 ** its initial value is NULL.  If the (...) does not remain constant
75470 ** for the duration of the query (i.e. the SELECT within the (...)
75471 ** is a correlated subquery) then the value of the allocated register is
75472 ** reset to NULL each time the subquery is rerun. This allows the
75473 ** caller to use vdbe code equivalent to the following:
75474 **
75475 **   if( register==NULL ){
75476 **     has_null = <test if data structure contains null>
75477 **     register = 1
75478 **   }
75479 **
75480 ** in order to avoid running the <test if data structure contains null>
75481 ** test more often than is necessary.
75482 */
75483 #ifndef SQLITE_OMIT_SUBQUERY
75484 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75485   Select *p;                            /* SELECT to the right of IN operator */
75486   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75487   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75488   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75489   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
75490 
75491   assert( pX->op==TK_IN );
75492 
75493   /* Check to see if an existing table or index can be used to
75494   ** satisfy the query.  This is preferable to generating a new
75495   ** ephemeral table.
75496   */
75497   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75498   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75499     sqlite3 *db = pParse->db;              /* Database connection */
75500     Table *pTab;                           /* Table <table>. */
75501     Expr *pExpr;                           /* Expression <column> */
75502     int iCol;                              /* Index of column <column> */
75503     int iDb;                               /* Database idx for pTab */
75504 
75505     assert( p );                        /* Because of isCandidateForInOpt(p) */
75506     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75507     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75508     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75509     pTab = p->pSrc->a[0].pTab;
75510     pExpr = p->pEList->a[0].pExpr;
75511     iCol = pExpr->iColumn;
75512 
75513     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75514     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75515     sqlite3CodeVerifySchema(pParse, iDb);
75516     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75517 
75518     /* This function is only called from two places. In both cases the vdbe
75519     ** has already been allocated. So assume sqlite3GetVdbe() is always
75520     ** successful here.
75521     */
75522     assert(v);
75523     if( iCol<0 ){
75524       int iAddr;
75525 
75526       iAddr = sqlite3CodeOnce(pParse);
75527 
75528       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75529       eType = IN_INDEX_ROWID;
75530 
75531       sqlite3VdbeJumpHere(v, iAddr);
75532     }else{
75533       Index *pIdx;                         /* Iterator variable */
75534 
75535       /* The collation sequence used by the comparison. If an index is to
75536       ** be used in place of a temp-table, it must be ordered according
75537       ** to this collation sequence.  */
75538       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75539 
75540       /* Check that the affinity that will be used to perform the
75541       ** comparison is the same as the affinity of the column. If
75542       ** it is not, it is not possible to use any index.
75543       */
75544       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
75545 
75546       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75547         if( (pIdx->aiColumn[0]==iCol)
75548          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75549          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75550         ){
75551           int iAddr;
75552           char *pKey;
75553 
75554           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
75555           iAddr = sqlite3CodeOnce(pParse);
75556 
75557           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75558                                pKey,P4_KEYINFO_HANDOFF);
75559           VdbeComment((v, "%s", pIdx->zName));
75560           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
75561           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
75562 
75563           sqlite3VdbeJumpHere(v, iAddr);
75564           if( prNotFound && !pTab->aCol[iCol].notNull ){
75565             *prNotFound = ++pParse->nMem;
75566             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75567           }
75568         }
75569       }
75570     }
75571   }
75572 
75573   if( eType==0 ){
75574     /* Could not found an existing table or index to use as the RHS b-tree.
75575     ** We will have to generate an ephemeral table to do the job.
75576     */
75577     double savedNQueryLoop = pParse->nQueryLoop;
75578     int rMayHaveNull = 0;
75579     eType = IN_INDEX_EPH;
75580     if( prNotFound ){
75581       *prNotFound = rMayHaveNull = ++pParse->nMem;
75582       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75583     }else{
75584       testcase( pParse->nQueryLoop>(double)1 );
75585       pParse->nQueryLoop = (double)1;
75586       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75587         eType = IN_INDEX_ROWID;
75588       }
75589     }
75590     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75591     pParse->nQueryLoop = savedNQueryLoop;
75592   }else{
75593     pX->iTable = iTab;
75594   }
75595   return eType;
75596 }
75597 #endif
75598 
75599 /*
75600 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75601 ** or IN operators.  Examples:
75602 **
75603 **     (SELECT a FROM b)          -- subquery
75604 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75605 **     x IN (4,5,11)              -- IN operator with list on right-hand side
75606 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75607 **
75608 ** The pExpr parameter describes the expression that contains the IN
75609 ** operator or subquery.
75610 **
75611 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75612 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75613 ** to some integer key column of a table B-Tree. In this case, use an
75614 ** intkey B-Tree to store the set of IN(...) values instead of the usual
75615 ** (slower) variable length keys B-Tree.
75616 **
75617 ** If rMayHaveNull is non-zero, that means that the operation is an IN
75618 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75619 ** Furthermore, the IN is in a WHERE clause and that we really want
75620 ** to iterate over the RHS of the IN operator in order to quickly locate
75621 ** all corresponding LHS elements.  All this routine does is initialize
75622 ** the register given by rMayHaveNull to NULL.  Calling routines will take
75623 ** care of changing this register value to non-NULL if the RHS is NULL-free.
75624 **
75625 ** If rMayHaveNull is zero, that means that the subquery is being used
75626 ** for membership testing only.  There is no need to initialize any
75627 ** registers to indicate the presense or absence of NULLs on the RHS.
75628 **
75629 ** For a SELECT or EXISTS operator, return the register that holds the
75630 ** result.  For IN operators or if an error occurs, the return value is 0.
75631 */
75632 #ifndef SQLITE_OMIT_SUBQUERY
75633 SQLITE_PRIVATE int sqlite3CodeSubselect(
75634   Parse *pParse,          /* Parsing context */
75635   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
75636   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
75637   int isRowid             /* If true, LHS of IN operator is a rowid */
75638 ){
75639   int testAddr = -1;                      /* One-time test address */
75640   int rReg = 0;                           /* Register storing resulting */
75641   Vdbe *v = sqlite3GetVdbe(pParse);
75642   if( NEVER(v==0) ) return 0;
75643   sqlite3ExprCachePush(pParse);
75644 
75645   /* This code must be run in its entirety every time it is encountered
75646   ** if any of the following is true:
75647   **
75648   **    *  The right-hand side is a correlated subquery
75649   **    *  The right-hand side is an expression list containing variables
75650   **    *  We are inside a trigger
75651   **
75652   ** If all of the above are false, then we can run this code just once
75653   ** save the results, and reuse the same result on subsequent invocations.
75654   */
75655   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
75656     testAddr = sqlite3CodeOnce(pParse);
75657   }
75658 
75659 #ifndef SQLITE_OMIT_EXPLAIN
75660   if( pParse->explain==2 ){
75661     char *zMsg = sqlite3MPrintf(
75662         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
75663         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
75664     );
75665     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
75666   }
75667 #endif
75668 
75669   switch( pExpr->op ){
75670     case TK_IN: {
75671       char affinity;              /* Affinity of the LHS of the IN */
75672       KeyInfo keyInfo;            /* Keyinfo for the generated table */
75673       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
75674       int addr;                   /* Address of OP_OpenEphemeral instruction */
75675       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
75676 
75677       if( rMayHaveNull ){
75678         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
75679       }
75680 
75681       affinity = sqlite3ExprAffinity(pLeft);
75682 
75683       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
75684       ** expression it is handled the same way.  An ephemeral table is
75685       ** filled with single-field index keys representing the results
75686       ** from the SELECT or the <exprlist>.
75687       **
75688       ** If the 'x' expression is a column value, or the SELECT...
75689       ** statement returns a column value, then the affinity of that
75690       ** column is used to build the index keys. If both 'x' and the
75691       ** SELECT... statement are columns, then numeric affinity is used
75692       ** if either column has NUMERIC or INTEGER affinity. If neither
75693       ** 'x' nor the SELECT... statement are columns, then numeric affinity
75694       ** is used.
75695       */
75696       pExpr->iTable = pParse->nTab++;
75697       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
75698       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
75699       memset(&keyInfo, 0, sizeof(keyInfo));
75700       keyInfo.nField = 1;
75701       keyInfo.aSortOrder = &sortOrder;
75702 
75703       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75704         /* Case 1:     expr IN (SELECT ...)
75705         **
75706         ** Generate code to write the results of the select into the temporary
75707         ** table allocated and opened above.
75708         */
75709         SelectDest dest;
75710         ExprList *pEList;
75711 
75712         assert( !isRowid );
75713         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
75714         dest.affSdst = (u8)affinity;
75715         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
75716         pExpr->x.pSelect->iLimit = 0;
75717         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
75718           return 0;
75719         }
75720         pEList = pExpr->x.pSelect->pEList;
75721         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
75722           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
75723               pEList->a[0].pExpr);
75724         }
75725       }else if( ALWAYS(pExpr->x.pList!=0) ){
75726         /* Case 2:     expr IN (exprlist)
75727         **
75728         ** For each expression, build an index key from the evaluation and
75729         ** store it in the temporary table. If <expr> is a column, then use
75730         ** that columns affinity when building index keys. If <expr> is not
75731         ** a column, use numeric affinity.
75732         */
75733         int i;
75734         ExprList *pList = pExpr->x.pList;
75735         struct ExprList_item *pItem;
75736         int r1, r2, r3;
75737 
75738         if( !affinity ){
75739           affinity = SQLITE_AFF_NONE;
75740         }
75741         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
75742         keyInfo.aSortOrder = &sortOrder;
75743 
75744         /* Loop through each expression in <exprlist>. */
75745         r1 = sqlite3GetTempReg(pParse);
75746         r2 = sqlite3GetTempReg(pParse);
75747         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
75748         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
75749           Expr *pE2 = pItem->pExpr;
75750           int iValToIns;
75751 
75752           /* If the expression is not constant then we will need to
75753           ** disable the test that was generated above that makes sure
75754           ** this code only executes once.  Because for a non-constant
75755           ** expression we need to rerun this code each time.
75756           */
75757           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
75758             sqlite3VdbeChangeToNoop(v, testAddr);
75759             testAddr = -1;
75760           }
75761 
75762           /* Evaluate the expression and insert it into the temp table */
75763           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
75764             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
75765           }else{
75766             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
75767             if( isRowid ){
75768               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
75769                                 sqlite3VdbeCurrentAddr(v)+2);
75770               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
75771             }else{
75772               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
75773               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
75774               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
75775             }
75776           }
75777         }
75778         sqlite3ReleaseTempReg(pParse, r1);
75779         sqlite3ReleaseTempReg(pParse, r2);
75780       }
75781       if( !isRowid ){
75782         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
75783       }
75784       break;
75785     }
75786 
75787     case TK_EXISTS:
75788     case TK_SELECT:
75789     default: {
75790       /* If this has to be a scalar SELECT.  Generate code to put the
75791       ** value of this select in a memory cell and record the number
75792       ** of the memory cell in iColumn.  If this is an EXISTS, write
75793       ** an integer 0 (not exists) or 1 (exists) into a memory cell
75794       ** and record that memory cell in iColumn.
75795       */
75796       Select *pSel;                         /* SELECT statement to encode */
75797       SelectDest dest;                      /* How to deal with SELECt result */
75798 
75799       testcase( pExpr->op==TK_EXISTS );
75800       testcase( pExpr->op==TK_SELECT );
75801       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
75802 
75803       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
75804       pSel = pExpr->x.pSelect;
75805       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
75806       if( pExpr->op==TK_SELECT ){
75807         dest.eDest = SRT_Mem;
75808         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
75809         VdbeComment((v, "Init subquery result"));
75810       }else{
75811         dest.eDest = SRT_Exists;
75812         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
75813         VdbeComment((v, "Init EXISTS result"));
75814       }
75815       sqlite3ExprDelete(pParse->db, pSel->pLimit);
75816       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
75817                                   &sqlite3IntTokens[1]);
75818       pSel->iLimit = 0;
75819       if( sqlite3Select(pParse, pSel, &dest) ){
75820         return 0;
75821       }
75822       rReg = dest.iSDParm;
75823       ExprSetIrreducible(pExpr);
75824       break;
75825     }
75826   }
75827 
75828   if( testAddr>=0 ){
75829     sqlite3VdbeJumpHere(v, testAddr);
75830   }
75831   sqlite3ExprCachePop(pParse, 1);
75832 
75833   return rReg;
75834 }
75835 #endif /* SQLITE_OMIT_SUBQUERY */
75836 
75837 #ifndef SQLITE_OMIT_SUBQUERY
75838 /*
75839 ** Generate code for an IN expression.
75840 **
75841 **      x IN (SELECT ...)
75842 **      x IN (value, value, ...)
75843 **
75844 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
75845 ** is an array of zero or more values.  The expression is true if the LHS is
75846 ** contained within the RHS.  The value of the expression is unknown (NULL)
75847 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
75848 ** RHS contains one or more NULL values.
75849 **
75850 ** This routine generates code will jump to destIfFalse if the LHS is not
75851 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
75852 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
75853 ** within the RHS then fall through.
75854 */
75855 static void sqlite3ExprCodeIN(
75856   Parse *pParse,        /* Parsing and code generating context */
75857   Expr *pExpr,          /* The IN expression */
75858   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
75859   int destIfNull        /* Jump here if the results are unknown due to NULLs */
75860 ){
75861   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
75862   char affinity;        /* Comparison affinity to use */
75863   int eType;            /* Type of the RHS */
75864   int r1;               /* Temporary use register */
75865   Vdbe *v;              /* Statement under construction */
75866 
75867   /* Compute the RHS.   After this step, the table with cursor
75868   ** pExpr->iTable will contains the values that make up the RHS.
75869   */
75870   v = pParse->pVdbe;
75871   assert( v!=0 );       /* OOM detected prior to this routine */
75872   VdbeNoopComment((v, "begin IN expr"));
75873   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
75874 
75875   /* Figure out the affinity to use to create a key from the results
75876   ** of the expression. affinityStr stores a static string suitable for
75877   ** P4 of OP_MakeRecord.
75878   */
75879   affinity = comparisonAffinity(pExpr);
75880 
75881   /* Code the LHS, the <expr> from "<expr> IN (...)".
75882   */
75883   sqlite3ExprCachePush(pParse);
75884   r1 = sqlite3GetTempReg(pParse);
75885   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
75886 
75887   /* If the LHS is NULL, then the result is either false or NULL depending
75888   ** on whether the RHS is empty or not, respectively.
75889   */
75890   if( destIfNull==destIfFalse ){
75891     /* Shortcut for the common case where the false and NULL outcomes are
75892     ** the same. */
75893     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
75894   }else{
75895     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
75896     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
75897     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
75898     sqlite3VdbeJumpHere(v, addr1);
75899   }
75900 
75901   if( eType==IN_INDEX_ROWID ){
75902     /* In this case, the RHS is the ROWID of table b-tree
75903     */
75904     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
75905     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
75906   }else{
75907     /* In this case, the RHS is an index b-tree.
75908     */
75909     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
75910 
75911     /* If the set membership test fails, then the result of the
75912     ** "x IN (...)" expression must be either 0 or NULL. If the set
75913     ** contains no NULL values, then the result is 0. If the set
75914     ** contains one or more NULL values, then the result of the
75915     ** expression is also NULL.
75916     */
75917     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
75918       /* This branch runs if it is known at compile time that the RHS
75919       ** cannot contain NULL values. This happens as the result
75920       ** of a "NOT NULL" constraint in the database schema.
75921       **
75922       ** Also run this branch if NULL is equivalent to FALSE
75923       ** for this particular IN operator.
75924       */
75925       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
75926 
75927     }else{
75928       /* In this branch, the RHS of the IN might contain a NULL and
75929       ** the presence of a NULL on the RHS makes a difference in the
75930       ** outcome.
75931       */
75932       int j1, j2, j3;
75933 
75934       /* First check to see if the LHS is contained in the RHS.  If so,
75935       ** then the presence of NULLs in the RHS does not matter, so jump
75936       ** over all of the code that follows.
75937       */
75938       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
75939 
75940       /* Here we begin generating code that runs if the LHS is not
75941       ** contained within the RHS.  Generate additional code that
75942       ** tests the RHS for NULLs.  If the RHS contains a NULL then
75943       ** jump to destIfNull.  If there are no NULLs in the RHS then
75944       ** jump to destIfFalse.
75945       */
75946       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
75947       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
75948       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
75949       sqlite3VdbeJumpHere(v, j3);
75950       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
75951       sqlite3VdbeJumpHere(v, j2);
75952 
75953       /* Jump to the appropriate target depending on whether or not
75954       ** the RHS contains a NULL
75955       */
75956       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
75957       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
75958 
75959       /* The OP_Found at the top of this branch jumps here when true,
75960       ** causing the overall IN expression evaluation to fall through.
75961       */
75962       sqlite3VdbeJumpHere(v, j1);
75963     }
75964   }
75965   sqlite3ReleaseTempReg(pParse, r1);
75966   sqlite3ExprCachePop(pParse, 1);
75967   VdbeComment((v, "end IN expr"));
75968 }
75969 #endif /* SQLITE_OMIT_SUBQUERY */
75970 
75971 /*
75972 ** Duplicate an 8-byte value
75973 */
75974 static char *dup8bytes(Vdbe *v, const char *in){
75975   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
75976   if( out ){
75977     memcpy(out, in, 8);
75978   }
75979   return out;
75980 }
75981 
75982 #ifndef SQLITE_OMIT_FLOATING_POINT
75983 /*
75984 ** Generate an instruction that will put the floating point
75985 ** value described by z[0..n-1] into register iMem.
75986 **
75987 ** The z[] string will probably not be zero-terminated.  But the
75988 ** z[n] character is guaranteed to be something that does not look
75989 ** like the continuation of the number.
75990 */
75991 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
75992   if( ALWAYS(z!=0) ){
75993     double value;
75994     char *zV;
75995     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
75996     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
75997     if( negateFlag ) value = -value;
75998     zV = dup8bytes(v, (char*)&value);
75999     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
76000   }
76001 }
76002 #endif
76003 
76004 
76005 /*
76006 ** Generate an instruction that will put the integer describe by
76007 ** text z[0..n-1] into register iMem.
76008 **
76009 ** Expr.u.zToken is always UTF8 and zero-terminated.
76010 */
76011 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
76012   Vdbe *v = pParse->pVdbe;
76013   if( pExpr->flags & EP_IntValue ){
76014     int i = pExpr->u.iValue;
76015     assert( i>=0 );
76016     if( negFlag ) i = -i;
76017     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
76018   }else{
76019     int c;
76020     i64 value;
76021     const char *z = pExpr->u.zToken;
76022     assert( z!=0 );
76023     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76024     if( c==0 || (c==2 && negFlag) ){
76025       char *zV;
76026       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
76027       zV = dup8bytes(v, (char*)&value);
76028       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
76029     }else{
76030 #ifdef SQLITE_OMIT_FLOATING_POINT
76031       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
76032 #else
76033       codeReal(v, z, negFlag, iMem);
76034 #endif
76035     }
76036   }
76037 }
76038 
76039 /*
76040 ** Clear a cache entry.
76041 */
76042 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
76043   if( p->tempReg ){
76044     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76045       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
76046     }
76047     p->tempReg = 0;
76048   }
76049 }
76050 
76051 
76052 /*
76053 ** Record in the column cache that a particular column from a
76054 ** particular table is stored in a particular register.
76055 */
76056 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
76057   int i;
76058   int minLru;
76059   int idxLru;
76060   struct yColCache *p;
76061 
76062   assert( iReg>0 );  /* Register numbers are always positive */
76063   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
76064 
76065   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
76066   ** for testing only - to verify that SQLite always gets the same answer
76067   ** with and without the column cache.
76068   */
76069   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
76070 
76071   /* First replace any existing entry.
76072   **
76073   ** Actually, the way the column cache is currently used, we are guaranteed
76074   ** that the object will never already be in cache.  Verify this guarantee.
76075   */
76076 #ifndef NDEBUG
76077   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76078     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
76079   }
76080 #endif
76081 
76082   /* Find an empty slot and replace it */
76083   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76084     if( p->iReg==0 ){
76085       p->iLevel = pParse->iCacheLevel;
76086       p->iTable = iTab;
76087       p->iColumn = iCol;
76088       p->iReg = iReg;
76089       p->tempReg = 0;
76090       p->lru = pParse->iCacheCnt++;
76091       return;
76092     }
76093   }
76094 
76095   /* Replace the last recently used */
76096   minLru = 0x7fffffff;
76097   idxLru = -1;
76098   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76099     if( p->lru<minLru ){
76100       idxLru = i;
76101       minLru = p->lru;
76102     }
76103   }
76104   if( ALWAYS(idxLru>=0) ){
76105     p = &pParse->aColCache[idxLru];
76106     p->iLevel = pParse->iCacheLevel;
76107     p->iTable = iTab;
76108     p->iColumn = iCol;
76109     p->iReg = iReg;
76110     p->tempReg = 0;
76111     p->lru = pParse->iCacheCnt++;
76112     return;
76113   }
76114 }
76115 
76116 /*
76117 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
76118 ** Purge the range of registers from the column cache.
76119 */
76120 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
76121   int i;
76122   int iLast = iReg + nReg - 1;
76123   struct yColCache *p;
76124   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76125     int r = p->iReg;
76126     if( r>=iReg && r<=iLast ){
76127       cacheEntryClear(pParse, p);
76128       p->iReg = 0;
76129     }
76130   }
76131 }
76132 
76133 /*
76134 ** Remember the current column cache context.  Any new entries added
76135 ** added to the column cache after this call are removed when the
76136 ** corresponding pop occurs.
76137 */
76138 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
76139   pParse->iCacheLevel++;
76140 }
76141 
76142 /*
76143 ** Remove from the column cache any entries that were added since the
76144 ** the previous N Push operations.  In other words, restore the cache
76145 ** to the state it was in N Pushes ago.
76146 */
76147 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
76148   int i;
76149   struct yColCache *p;
76150   assert( N>0 );
76151   assert( pParse->iCacheLevel>=N );
76152   pParse->iCacheLevel -= N;
76153   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76154     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
76155       cacheEntryClear(pParse, p);
76156       p->iReg = 0;
76157     }
76158   }
76159 }
76160 
76161 /*
76162 ** When a cached column is reused, make sure that its register is
76163 ** no longer available as a temp register.  ticket #3879:  that same
76164 ** register might be in the cache in multiple places, so be sure to
76165 ** get them all.
76166 */
76167 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
76168   int i;
76169   struct yColCache *p;
76170   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76171     if( p->iReg==iReg ){
76172       p->tempReg = 0;
76173     }
76174   }
76175 }
76176 
76177 /*
76178 ** Generate code to extract the value of the iCol-th column of a table.
76179 */
76180 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
76181   Vdbe *v,        /* The VDBE under construction */
76182   Table *pTab,    /* The table containing the value */
76183   int iTabCur,    /* The cursor for this table */
76184   int iCol,       /* Index of the column to extract */
76185   int regOut      /* Extract the valud into this register */
76186 ){
76187   if( iCol<0 || iCol==pTab->iPKey ){
76188     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
76189   }else{
76190     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
76191     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
76192   }
76193   if( iCol>=0 ){
76194     sqlite3ColumnDefault(v, pTab, iCol, regOut);
76195   }
76196 }
76197 
76198 /*
76199 ** Generate code that will extract the iColumn-th column from
76200 ** table pTab and store the column value in a register.  An effort
76201 ** is made to store the column value in register iReg, but this is
76202 ** not guaranteed.  The location of the column value is returned.
76203 **
76204 ** There must be an open cursor to pTab in iTable when this routine
76205 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
76206 */
76207 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
76208   Parse *pParse,   /* Parsing and code generating context */
76209   Table *pTab,     /* Description of the table we are reading from */
76210   int iColumn,     /* Index of the table column */
76211   int iTable,      /* The cursor pointing to the table */
76212   int iReg,        /* Store results here */
76213   u8 p5            /* P5 value for OP_Column */
76214 ){
76215   Vdbe *v = pParse->pVdbe;
76216   int i;
76217   struct yColCache *p;
76218 
76219   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76220     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76221       p->lru = pParse->iCacheCnt++;
76222       sqlite3ExprCachePinRegister(pParse, p->iReg);
76223       return p->iReg;
76224     }
76225   }
76226   assert( v!=0 );
76227   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76228   if( p5 ){
76229     sqlite3VdbeChangeP5(v, p5);
76230   }else{
76231     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
76232   }
76233   return iReg;
76234 }
76235 
76236 /*
76237 ** Clear all column cache entries.
76238 */
76239 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
76240   int i;
76241   struct yColCache *p;
76242 
76243   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76244     if( p->iReg ){
76245       cacheEntryClear(pParse, p);
76246       p->iReg = 0;
76247     }
76248   }
76249 }
76250 
76251 /*
76252 ** Record the fact that an affinity change has occurred on iCount
76253 ** registers starting with iStart.
76254 */
76255 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76256   sqlite3ExprCacheRemove(pParse, iStart, iCount);
76257 }
76258 
76259 /*
76260 ** Generate code to move content from registers iFrom...iFrom+nReg-1
76261 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76262 */
76263 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76264   int i;
76265   struct yColCache *p;
76266   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
76267   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
76268   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76269     int x = p->iReg;
76270     if( x>=iFrom && x<iFrom+nReg ){
76271       p->iReg += iTo-iFrom;
76272     }
76273   }
76274 }
76275 
76276 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
76277 /*
76278 ** Return true if any register in the range iFrom..iTo (inclusive)
76279 ** is used as part of the column cache.
76280 **
76281 ** This routine is used within assert() and testcase() macros only
76282 ** and does not appear in a normal build.
76283 */
76284 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76285   int i;
76286   struct yColCache *p;
76287   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76288     int r = p->iReg;
76289     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76290   }
76291   return 0;
76292 }
76293 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
76294 
76295 /*
76296 ** Generate code into the current Vdbe to evaluate the given
76297 ** expression.  Attempt to store the results in register "target".
76298 ** Return the register where results are stored.
76299 **
76300 ** With this routine, there is no guarantee that results will
76301 ** be stored in target.  The result might be stored in some other
76302 ** register if it is convenient to do so.  The calling function
76303 ** must check the return code and move the results to the desired
76304 ** register.
76305 */
76306 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76307   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76308   int op;                   /* The opcode being coded */
76309   int inReg = target;       /* Results stored in register inReg */
76310   int regFree1 = 0;         /* If non-zero free this temporary register */
76311   int regFree2 = 0;         /* If non-zero free this temporary register */
76312   int r1, r2, r3, r4;       /* Various register numbers */
76313   sqlite3 *db = pParse->db; /* The database connection */
76314 
76315   assert( target>0 && target<=pParse->nMem );
76316   if( v==0 ){
76317     assert( pParse->db->mallocFailed );
76318     return 0;
76319   }
76320 
76321   if( pExpr==0 ){
76322     op = TK_NULL;
76323   }else{
76324     op = pExpr->op;
76325   }
76326   switch( op ){
76327     case TK_AGG_COLUMN: {
76328       AggInfo *pAggInfo = pExpr->pAggInfo;
76329       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76330       if( !pAggInfo->directMode ){
76331         assert( pCol->iMem>0 );
76332         inReg = pCol->iMem;
76333         break;
76334       }else if( pAggInfo->useSortingIdx ){
76335         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76336                               pCol->iSorterColumn, target);
76337         break;
76338       }
76339       /* Otherwise, fall thru into the TK_COLUMN case */
76340     }
76341     case TK_COLUMN: {
76342       if( pExpr->iTable<0 ){
76343         /* This only happens when coding check constraints */
76344         assert( pParse->ckBase>0 );
76345         inReg = pExpr->iColumn + pParse->ckBase;
76346       }else{
76347         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
76348                                  pExpr->iColumn, pExpr->iTable, target,
76349                                  pExpr->op2);
76350       }
76351       break;
76352     }
76353     case TK_INTEGER: {
76354       codeInteger(pParse, pExpr, 0, target);
76355       break;
76356     }
76357 #ifndef SQLITE_OMIT_FLOATING_POINT
76358     case TK_FLOAT: {
76359       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76360       codeReal(v, pExpr->u.zToken, 0, target);
76361       break;
76362     }
76363 #endif
76364     case TK_STRING: {
76365       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76366       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76367       break;
76368     }
76369     case TK_NULL: {
76370       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76371       break;
76372     }
76373 #ifndef SQLITE_OMIT_BLOB_LITERAL
76374     case TK_BLOB: {
76375       int n;
76376       const char *z;
76377       char *zBlob;
76378       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76379       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76380       assert( pExpr->u.zToken[1]=='\'' );
76381       z = &pExpr->u.zToken[2];
76382       n = sqlite3Strlen30(z) - 1;
76383       assert( z[n]=='\'' );
76384       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
76385       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76386       break;
76387     }
76388 #endif
76389     case TK_VARIABLE: {
76390       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76391       assert( pExpr->u.zToken!=0 );
76392       assert( pExpr->u.zToken[0]!=0 );
76393       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76394       if( pExpr->u.zToken[1]!=0 ){
76395         assert( pExpr->u.zToken[0]=='?'
76396              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76397         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76398       }
76399       break;
76400     }
76401     case TK_REGISTER: {
76402       inReg = pExpr->iTable;
76403       break;
76404     }
76405     case TK_AS: {
76406       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76407       break;
76408     }
76409 #ifndef SQLITE_OMIT_CAST
76410     case TK_CAST: {
76411       /* Expressions of the form:   CAST(pLeft AS token) */
76412       int aff, to_op;
76413       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76414       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76415       aff = sqlite3AffinityType(pExpr->u.zToken);
76416       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
76417       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
76418       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
76419       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
76420       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
76421       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
76422       testcase( to_op==OP_ToText );
76423       testcase( to_op==OP_ToBlob );
76424       testcase( to_op==OP_ToNumeric );
76425       testcase( to_op==OP_ToInt );
76426       testcase( to_op==OP_ToReal );
76427       if( inReg!=target ){
76428         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
76429         inReg = target;
76430       }
76431       sqlite3VdbeAddOp1(v, to_op, inReg);
76432       testcase( usedAsColumnCache(pParse, inReg, inReg) );
76433       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
76434       break;
76435     }
76436 #endif /* SQLITE_OMIT_CAST */
76437     case TK_LT:
76438     case TK_LE:
76439     case TK_GT:
76440     case TK_GE:
76441     case TK_NE:
76442     case TK_EQ: {
76443       assert( TK_LT==OP_Lt );
76444       assert( TK_LE==OP_Le );
76445       assert( TK_GT==OP_Gt );
76446       assert( TK_GE==OP_Ge );
76447       assert( TK_EQ==OP_Eq );
76448       assert( TK_NE==OP_Ne );
76449       testcase( op==TK_LT );
76450       testcase( op==TK_LE );
76451       testcase( op==TK_GT );
76452       testcase( op==TK_GE );
76453       testcase( op==TK_EQ );
76454       testcase( op==TK_NE );
76455       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76456       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76457       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76458                   r1, r2, inReg, SQLITE_STOREP2);
76459       testcase( regFree1==0 );
76460       testcase( regFree2==0 );
76461       break;
76462     }
76463     case TK_IS:
76464     case TK_ISNOT: {
76465       testcase( op==TK_IS );
76466       testcase( op==TK_ISNOT );
76467       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76468       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76469       op = (op==TK_IS) ? TK_EQ : TK_NE;
76470       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76471                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
76472       testcase( regFree1==0 );
76473       testcase( regFree2==0 );
76474       break;
76475     }
76476     case TK_AND:
76477     case TK_OR:
76478     case TK_PLUS:
76479     case TK_STAR:
76480     case TK_MINUS:
76481     case TK_REM:
76482     case TK_BITAND:
76483     case TK_BITOR:
76484     case TK_SLASH:
76485     case TK_LSHIFT:
76486     case TK_RSHIFT:
76487     case TK_CONCAT: {
76488       assert( TK_AND==OP_And );
76489       assert( TK_OR==OP_Or );
76490       assert( TK_PLUS==OP_Add );
76491       assert( TK_MINUS==OP_Subtract );
76492       assert( TK_REM==OP_Remainder );
76493       assert( TK_BITAND==OP_BitAnd );
76494       assert( TK_BITOR==OP_BitOr );
76495       assert( TK_SLASH==OP_Divide );
76496       assert( TK_LSHIFT==OP_ShiftLeft );
76497       assert( TK_RSHIFT==OP_ShiftRight );
76498       assert( TK_CONCAT==OP_Concat );
76499       testcase( op==TK_AND );
76500       testcase( op==TK_OR );
76501       testcase( op==TK_PLUS );
76502       testcase( op==TK_MINUS );
76503       testcase( op==TK_REM );
76504       testcase( op==TK_BITAND );
76505       testcase( op==TK_BITOR );
76506       testcase( op==TK_SLASH );
76507       testcase( op==TK_LSHIFT );
76508       testcase( op==TK_RSHIFT );
76509       testcase( op==TK_CONCAT );
76510       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76511       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76512       sqlite3VdbeAddOp3(v, op, r2, r1, target);
76513       testcase( regFree1==0 );
76514       testcase( regFree2==0 );
76515       break;
76516     }
76517     case TK_UMINUS: {
76518       Expr *pLeft = pExpr->pLeft;
76519       assert( pLeft );
76520       if( pLeft->op==TK_INTEGER ){
76521         codeInteger(pParse, pLeft, 1, target);
76522 #ifndef SQLITE_OMIT_FLOATING_POINT
76523       }else if( pLeft->op==TK_FLOAT ){
76524         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76525         codeReal(v, pLeft->u.zToken, 1, target);
76526 #endif
76527       }else{
76528         regFree1 = r1 = sqlite3GetTempReg(pParse);
76529         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
76530         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76531         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76532         testcase( regFree2==0 );
76533       }
76534       inReg = target;
76535       break;
76536     }
76537     case TK_BITNOT:
76538     case TK_NOT: {
76539       assert( TK_BITNOT==OP_BitNot );
76540       assert( TK_NOT==OP_Not );
76541       testcase( op==TK_BITNOT );
76542       testcase( op==TK_NOT );
76543       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76544       testcase( regFree1==0 );
76545       inReg = target;
76546       sqlite3VdbeAddOp2(v, op, r1, inReg);
76547       break;
76548     }
76549     case TK_ISNULL:
76550     case TK_NOTNULL: {
76551       int addr;
76552       assert( TK_ISNULL==OP_IsNull );
76553       assert( TK_NOTNULL==OP_NotNull );
76554       testcase( op==TK_ISNULL );
76555       testcase( op==TK_NOTNULL );
76556       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76557       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76558       testcase( regFree1==0 );
76559       addr = sqlite3VdbeAddOp1(v, op, r1);
76560       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
76561       sqlite3VdbeJumpHere(v, addr);
76562       break;
76563     }
76564     case TK_AGG_FUNCTION: {
76565       AggInfo *pInfo = pExpr->pAggInfo;
76566       if( pInfo==0 ){
76567         assert( !ExprHasProperty(pExpr, EP_IntValue) );
76568         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76569       }else{
76570         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76571       }
76572       break;
76573     }
76574     case TK_CONST_FUNC:
76575     case TK_FUNCTION: {
76576       ExprList *pFarg;       /* List of function arguments */
76577       int nFarg;             /* Number of function arguments */
76578       FuncDef *pDef;         /* The function definition object */
76579       int nId;               /* Length of the function name in bytes */
76580       const char *zId;       /* The function name */
76581       int constMask = 0;     /* Mask of function arguments that are constant */
76582       int i;                 /* Loop counter */
76583       u8 enc = ENC(db);      /* The text encoding used by this database */
76584       CollSeq *pColl = 0;    /* A collating sequence */
76585 
76586       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76587       testcase( op==TK_CONST_FUNC );
76588       testcase( op==TK_FUNCTION );
76589       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76590         pFarg = 0;
76591       }else{
76592         pFarg = pExpr->x.pList;
76593       }
76594       nFarg = pFarg ? pFarg->nExpr : 0;
76595       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76596       zId = pExpr->u.zToken;
76597       nId = sqlite3Strlen30(zId);
76598       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
76599       if( pDef==0 ){
76600         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76601         break;
76602       }
76603 
76604       /* Attempt a direct implementation of the built-in COALESCE() and
76605       ** IFNULL() functions.  This avoids unnecessary evalation of
76606       ** arguments past the first non-NULL argument.
76607       */
76608       if( pDef->flags & SQLITE_FUNC_COALESCE ){
76609         int endCoalesce = sqlite3VdbeMakeLabel(v);
76610         assert( nFarg>=2 );
76611         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
76612         for(i=1; i<nFarg; i++){
76613           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76614           sqlite3ExprCacheRemove(pParse, target, 1);
76615           sqlite3ExprCachePush(pParse);
76616           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
76617           sqlite3ExprCachePop(pParse, 1);
76618         }
76619         sqlite3VdbeResolveLabel(v, endCoalesce);
76620         break;
76621       }
76622 
76623 
76624       if( pFarg ){
76625         r1 = sqlite3GetTempRange(pParse, nFarg);
76626 
76627         /* For length() and typeof() functions with a column argument,
76628         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
76629         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
76630         ** loading.
76631         */
76632         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
76633           u8 exprOp;
76634           assert( nFarg==1 );
76635           assert( pFarg->a[0].pExpr!=0 );
76636           exprOp = pFarg->a[0].pExpr->op;
76637           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
76638             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
76639             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
76640             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
76641             pFarg->a[0].pExpr->op2 = pDef->flags;
76642           }
76643         }
76644 
76645         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
76646         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
76647         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
76648       }else{
76649         r1 = 0;
76650       }
76651 #ifndef SQLITE_OMIT_VIRTUALTABLE
76652       /* Possibly overload the function if the first argument is
76653       ** a virtual table column.
76654       **
76655       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
76656       ** second argument, not the first, as the argument to test to
76657       ** see if it is a column in a virtual table.  This is done because
76658       ** the left operand of infix functions (the operand we want to
76659       ** control overloading) ends up as the second argument to the
76660       ** function.  The expression "A glob B" is equivalent to
76661       ** "glob(B,A).  We want to use the A in "A glob B" to test
76662       ** for function overloading.  But we use the B term in "glob(B,A)".
76663       */
76664       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
76665         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
76666       }else if( nFarg>0 ){
76667         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
76668       }
76669 #endif
76670       for(i=0; i<nFarg; i++){
76671         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
76672           constMask |= (1<<i);
76673         }
76674         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
76675           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
76676         }
76677       }
76678       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
76679         if( !pColl ) pColl = db->pDfltColl;
76680         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
76681       }
76682       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
76683                         (char*)pDef, P4_FUNCDEF);
76684       sqlite3VdbeChangeP5(v, (u8)nFarg);
76685       if( nFarg ){
76686         sqlite3ReleaseTempRange(pParse, r1, nFarg);
76687       }
76688       break;
76689     }
76690 #ifndef SQLITE_OMIT_SUBQUERY
76691     case TK_EXISTS:
76692     case TK_SELECT: {
76693       testcase( op==TK_EXISTS );
76694       testcase( op==TK_SELECT );
76695       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
76696       break;
76697     }
76698     case TK_IN: {
76699       int destIfFalse = sqlite3VdbeMakeLabel(v);
76700       int destIfNull = sqlite3VdbeMakeLabel(v);
76701       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76702       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76703       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76704       sqlite3VdbeResolveLabel(v, destIfFalse);
76705       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
76706       sqlite3VdbeResolveLabel(v, destIfNull);
76707       break;
76708     }
76709 #endif /* SQLITE_OMIT_SUBQUERY */
76710 
76711 
76712     /*
76713     **    x BETWEEN y AND z
76714     **
76715     ** This is equivalent to
76716     **
76717     **    x>=y AND x<=z
76718     **
76719     ** X is stored in pExpr->pLeft.
76720     ** Y is stored in pExpr->pList->a[0].pExpr.
76721     ** Z is stored in pExpr->pList->a[1].pExpr.
76722     */
76723     case TK_BETWEEN: {
76724       Expr *pLeft = pExpr->pLeft;
76725       struct ExprList_item *pLItem = pExpr->x.pList->a;
76726       Expr *pRight = pLItem->pExpr;
76727 
76728       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
76729       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
76730       testcase( regFree1==0 );
76731       testcase( regFree2==0 );
76732       r3 = sqlite3GetTempReg(pParse);
76733       r4 = sqlite3GetTempReg(pParse);
76734       codeCompare(pParse, pLeft, pRight, OP_Ge,
76735                   r1, r2, r3, SQLITE_STOREP2);
76736       pLItem++;
76737       pRight = pLItem->pExpr;
76738       sqlite3ReleaseTempReg(pParse, regFree2);
76739       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
76740       testcase( regFree2==0 );
76741       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
76742       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
76743       sqlite3ReleaseTempReg(pParse, r3);
76744       sqlite3ReleaseTempReg(pParse, r4);
76745       break;
76746     }
76747     case TK_COLLATE:
76748     case TK_UPLUS: {
76749       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76750       break;
76751     }
76752 
76753     case TK_TRIGGER: {
76754       /* If the opcode is TK_TRIGGER, then the expression is a reference
76755       ** to a column in the new.* or old.* pseudo-tables available to
76756       ** trigger programs. In this case Expr.iTable is set to 1 for the
76757       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
76758       ** is set to the column of the pseudo-table to read, or to -1 to
76759       ** read the rowid field.
76760       **
76761       ** The expression is implemented using an OP_Param opcode. The p1
76762       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
76763       ** to reference another column of the old.* pseudo-table, where
76764       ** i is the index of the column. For a new.rowid reference, p1 is
76765       ** set to (n+1), where n is the number of columns in each pseudo-table.
76766       ** For a reference to any other column in the new.* pseudo-table, p1
76767       ** is set to (n+2+i), where n and i are as defined previously. For
76768       ** example, if the table on which triggers are being fired is
76769       ** declared as:
76770       **
76771       **   CREATE TABLE t1(a, b);
76772       **
76773       ** Then p1 is interpreted as follows:
76774       **
76775       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
76776       **   p1==1   ->    old.a         p1==4   ->    new.a
76777       **   p1==2   ->    old.b         p1==5   ->    new.b
76778       */
76779       Table *pTab = pExpr->pTab;
76780       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
76781 
76782       assert( pExpr->iTable==0 || pExpr->iTable==1 );
76783       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
76784       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
76785       assert( p1>=0 && p1<(pTab->nCol*2+2) );
76786 
76787       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
76788       VdbeComment((v, "%s.%s -> $%d",
76789         (pExpr->iTable ? "new" : "old"),
76790         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
76791         target
76792       ));
76793 
76794 #ifndef SQLITE_OMIT_FLOATING_POINT
76795       /* If the column has REAL affinity, it may currently be stored as an
76796       ** integer. Use OP_RealAffinity to make sure it is really real.  */
76797       if( pExpr->iColumn>=0
76798        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
76799       ){
76800         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
76801       }
76802 #endif
76803       break;
76804     }
76805 
76806 
76807     /*
76808     ** Form A:
76809     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76810     **
76811     ** Form B:
76812     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
76813     **
76814     ** Form A is can be transformed into the equivalent form B as follows:
76815     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
76816     **        WHEN x=eN THEN rN ELSE y END
76817     **
76818     ** X (if it exists) is in pExpr->pLeft.
76819     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
76820     ** ELSE clause and no other term matches, then the result of the
76821     ** exprssion is NULL.
76822     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
76823     **
76824     ** The result of the expression is the Ri for the first matching Ei,
76825     ** or if there is no matching Ei, the ELSE term Y, or if there is
76826     ** no ELSE term, NULL.
76827     */
76828     default: assert( op==TK_CASE ); {
76829       int endLabel;                     /* GOTO label for end of CASE stmt */
76830       int nextCase;                     /* GOTO label for next WHEN clause */
76831       int nExpr;                        /* 2x number of WHEN terms */
76832       int i;                            /* Loop counter */
76833       ExprList *pEList;                 /* List of WHEN terms */
76834       struct ExprList_item *aListelem;  /* Array of WHEN terms */
76835       Expr opCompare;                   /* The X==Ei expression */
76836       Expr cacheX;                      /* Cached expression X */
76837       Expr *pX;                         /* The X expression */
76838       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
76839       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
76840 
76841       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
76842       assert((pExpr->x.pList->nExpr % 2) == 0);
76843       assert(pExpr->x.pList->nExpr > 0);
76844       pEList = pExpr->x.pList;
76845       aListelem = pEList->a;
76846       nExpr = pEList->nExpr;
76847       endLabel = sqlite3VdbeMakeLabel(v);
76848       if( (pX = pExpr->pLeft)!=0 ){
76849         cacheX = *pX;
76850         testcase( pX->op==TK_COLUMN );
76851         testcase( pX->op==TK_REGISTER );
76852         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
76853         testcase( regFree1==0 );
76854         cacheX.op = TK_REGISTER;
76855         opCompare.op = TK_EQ;
76856         opCompare.pLeft = &cacheX;
76857         pTest = &opCompare;
76858         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
76859         ** The value in regFree1 might get SCopy-ed into the file result.
76860         ** So make sure that the regFree1 register is not reused for other
76861         ** purposes and possibly overwritten.  */
76862         regFree1 = 0;
76863       }
76864       for(i=0; i<nExpr; i=i+2){
76865         sqlite3ExprCachePush(pParse);
76866         if( pX ){
76867           assert( pTest!=0 );
76868           opCompare.pRight = aListelem[i].pExpr;
76869         }else{
76870           pTest = aListelem[i].pExpr;
76871         }
76872         nextCase = sqlite3VdbeMakeLabel(v);
76873         testcase( pTest->op==TK_COLUMN );
76874         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
76875         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
76876         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
76877         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
76878         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
76879         sqlite3ExprCachePop(pParse, 1);
76880         sqlite3VdbeResolveLabel(v, nextCase);
76881       }
76882       if( pExpr->pRight ){
76883         sqlite3ExprCachePush(pParse);
76884         sqlite3ExprCode(pParse, pExpr->pRight, target);
76885         sqlite3ExprCachePop(pParse, 1);
76886       }else{
76887         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76888       }
76889       assert( db->mallocFailed || pParse->nErr>0
76890            || pParse->iCacheLevel==iCacheLevel );
76891       sqlite3VdbeResolveLabel(v, endLabel);
76892       break;
76893     }
76894 #ifndef SQLITE_OMIT_TRIGGER
76895     case TK_RAISE: {
76896       assert( pExpr->affinity==OE_Rollback
76897            || pExpr->affinity==OE_Abort
76898            || pExpr->affinity==OE_Fail
76899            || pExpr->affinity==OE_Ignore
76900       );
76901       if( !pParse->pTriggerTab ){
76902         sqlite3ErrorMsg(pParse,
76903                        "RAISE() may only be used within a trigger-program");
76904         return 0;
76905       }
76906       if( pExpr->affinity==OE_Abort ){
76907         sqlite3MayAbort(pParse);
76908       }
76909       assert( !ExprHasProperty(pExpr, EP_IntValue) );
76910       if( pExpr->affinity==OE_Ignore ){
76911         sqlite3VdbeAddOp4(
76912             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
76913       }else{
76914         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
76915                               pExpr->affinity, pExpr->u.zToken, 0);
76916       }
76917 
76918       break;
76919     }
76920 #endif
76921   }
76922   sqlite3ReleaseTempReg(pParse, regFree1);
76923   sqlite3ReleaseTempReg(pParse, regFree2);
76924   return inReg;
76925 }
76926 
76927 /*
76928 ** Generate code to evaluate an expression and store the results
76929 ** into a register.  Return the register number where the results
76930 ** are stored.
76931 **
76932 ** If the register is a temporary register that can be deallocated,
76933 ** then write its number into *pReg.  If the result register is not
76934 ** a temporary, then set *pReg to zero.
76935 */
76936 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
76937   int r1 = sqlite3GetTempReg(pParse);
76938   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
76939   if( r2==r1 ){
76940     *pReg = r1;
76941   }else{
76942     sqlite3ReleaseTempReg(pParse, r1);
76943     *pReg = 0;
76944   }
76945   return r2;
76946 }
76947 
76948 /*
76949 ** Generate code that will evaluate expression pExpr and store the
76950 ** results in register target.  The results are guaranteed to appear
76951 ** in register target.
76952 */
76953 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
76954   int inReg;
76955 
76956   assert( target>0 && target<=pParse->nMem );
76957   if( pExpr && pExpr->op==TK_REGISTER ){
76958     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
76959   }else{
76960     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
76961     assert( pParse->pVdbe || pParse->db->mallocFailed );
76962     if( inReg!=target && pParse->pVdbe ){
76963       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
76964     }
76965   }
76966   return target;
76967 }
76968 
76969 /*
76970 ** Generate code that evalutes the given expression and puts the result
76971 ** in register target.
76972 **
76973 ** Also make a copy of the expression results into another "cache" register
76974 ** and modify the expression so that the next time it is evaluated,
76975 ** the result is a copy of the cache register.
76976 **
76977 ** This routine is used for expressions that are used multiple
76978 ** times.  They are evaluated once and the results of the expression
76979 ** are reused.
76980 */
76981 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
76982   Vdbe *v = pParse->pVdbe;
76983   int inReg;
76984   inReg = sqlite3ExprCode(pParse, pExpr, target);
76985   assert( target>0 );
76986   /* This routine is called for terms to INSERT or UPDATE.  And the only
76987   ** other place where expressions can be converted into TK_REGISTER is
76988   ** in WHERE clause processing.  So as currently implemented, there is
76989   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
76990   ** keep the ALWAYS() in case the conditions above change with future
76991   ** modifications or enhancements. */
76992   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
76993     int iMem;
76994     iMem = ++pParse->nMem;
76995     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
76996     pExpr->iTable = iMem;
76997     pExpr->op2 = pExpr->op;
76998     pExpr->op = TK_REGISTER;
76999   }
77000   return inReg;
77001 }
77002 
77003 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77004 /*
77005 ** Generate a human-readable explanation of an expression tree.
77006 */
77007 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
77008   int op;                   /* The opcode being coded */
77009   const char *zBinOp = 0;   /* Binary operator */
77010   const char *zUniOp = 0;   /* Unary operator */
77011   if( pExpr==0 ){
77012     op = TK_NULL;
77013   }else{
77014     op = pExpr->op;
77015   }
77016   switch( op ){
77017     case TK_AGG_COLUMN: {
77018       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
77019             pExpr->iTable, pExpr->iColumn);
77020       break;
77021     }
77022     case TK_COLUMN: {
77023       if( pExpr->iTable<0 ){
77024         /* This only happens when coding check constraints */
77025         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
77026       }else{
77027         sqlite3ExplainPrintf(pOut, "{%d:%d}",
77028                              pExpr->iTable, pExpr->iColumn);
77029       }
77030       break;
77031     }
77032     case TK_INTEGER: {
77033       if( pExpr->flags & EP_IntValue ){
77034         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
77035       }else{
77036         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
77037       }
77038       break;
77039     }
77040 #ifndef SQLITE_OMIT_FLOATING_POINT
77041     case TK_FLOAT: {
77042       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77043       break;
77044     }
77045 #endif
77046     case TK_STRING: {
77047       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
77048       break;
77049     }
77050     case TK_NULL: {
77051       sqlite3ExplainPrintf(pOut,"NULL");
77052       break;
77053     }
77054 #ifndef SQLITE_OMIT_BLOB_LITERAL
77055     case TK_BLOB: {
77056       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77057       break;
77058     }
77059 #endif
77060     case TK_VARIABLE: {
77061       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
77062                            pExpr->u.zToken, pExpr->iColumn);
77063       break;
77064     }
77065     case TK_REGISTER: {
77066       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
77067       break;
77068     }
77069     case TK_AS: {
77070       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77071       break;
77072     }
77073 #ifndef SQLITE_OMIT_CAST
77074     case TK_CAST: {
77075       /* Expressions of the form:   CAST(pLeft AS token) */
77076       const char *zAff = "unk";
77077       switch( sqlite3AffinityType(pExpr->u.zToken) ){
77078         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
77079         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
77080         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
77081         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
77082         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
77083       }
77084       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
77085       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77086       sqlite3ExplainPrintf(pOut, ")");
77087       break;
77088     }
77089 #endif /* SQLITE_OMIT_CAST */
77090     case TK_LT:      zBinOp = "LT";     break;
77091     case TK_LE:      zBinOp = "LE";     break;
77092     case TK_GT:      zBinOp = "GT";     break;
77093     case TK_GE:      zBinOp = "GE";     break;
77094     case TK_NE:      zBinOp = "NE";     break;
77095     case TK_EQ:      zBinOp = "EQ";     break;
77096     case TK_IS:      zBinOp = "IS";     break;
77097     case TK_ISNOT:   zBinOp = "ISNOT";  break;
77098     case TK_AND:     zBinOp = "AND";    break;
77099     case TK_OR:      zBinOp = "OR";     break;
77100     case TK_PLUS:    zBinOp = "ADD";    break;
77101     case TK_STAR:    zBinOp = "MUL";    break;
77102     case TK_MINUS:   zBinOp = "SUB";    break;
77103     case TK_REM:     zBinOp = "REM";    break;
77104     case TK_BITAND:  zBinOp = "BITAND"; break;
77105     case TK_BITOR:   zBinOp = "BITOR";  break;
77106     case TK_SLASH:   zBinOp = "DIV";    break;
77107     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
77108     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
77109     case TK_CONCAT:  zBinOp = "CONCAT"; break;
77110 
77111     case TK_UMINUS:  zUniOp = "UMINUS"; break;
77112     case TK_UPLUS:   zUniOp = "UPLUS";  break;
77113     case TK_BITNOT:  zUniOp = "BITNOT"; break;
77114     case TK_NOT:     zUniOp = "NOT";    break;
77115     case TK_ISNULL:  zUniOp = "ISNULL"; break;
77116     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
77117 
77118     case TK_COLLATE: {
77119       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77120       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
77121       break;
77122     }
77123 
77124     case TK_AGG_FUNCTION:
77125     case TK_CONST_FUNC:
77126     case TK_FUNCTION: {
77127       ExprList *pFarg;       /* List of function arguments */
77128       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77129         pFarg = 0;
77130       }else{
77131         pFarg = pExpr->x.pList;
77132       }
77133       if( op==TK_AGG_FUNCTION ){
77134         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
77135                              pExpr->op2, pExpr->u.zToken);
77136       }else{
77137         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
77138       }
77139       if( pFarg ){
77140         sqlite3ExplainExprList(pOut, pFarg);
77141       }
77142       sqlite3ExplainPrintf(pOut, ")");
77143       break;
77144     }
77145 #ifndef SQLITE_OMIT_SUBQUERY
77146     case TK_EXISTS: {
77147       sqlite3ExplainPrintf(pOut, "EXISTS(");
77148       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77149       sqlite3ExplainPrintf(pOut,")");
77150       break;
77151     }
77152     case TK_SELECT: {
77153       sqlite3ExplainPrintf(pOut, "(");
77154       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77155       sqlite3ExplainPrintf(pOut, ")");
77156       break;
77157     }
77158     case TK_IN: {
77159       sqlite3ExplainPrintf(pOut, "IN(");
77160       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77161       sqlite3ExplainPrintf(pOut, ",");
77162       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77163         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77164       }else{
77165         sqlite3ExplainExprList(pOut, pExpr->x.pList);
77166       }
77167       sqlite3ExplainPrintf(pOut, ")");
77168       break;
77169     }
77170 #endif /* SQLITE_OMIT_SUBQUERY */
77171 
77172     /*
77173     **    x BETWEEN y AND z
77174     **
77175     ** This is equivalent to
77176     **
77177     **    x>=y AND x<=z
77178     **
77179     ** X is stored in pExpr->pLeft.
77180     ** Y is stored in pExpr->pList->a[0].pExpr.
77181     ** Z is stored in pExpr->pList->a[1].pExpr.
77182     */
77183     case TK_BETWEEN: {
77184       Expr *pX = pExpr->pLeft;
77185       Expr *pY = pExpr->x.pList->a[0].pExpr;
77186       Expr *pZ = pExpr->x.pList->a[1].pExpr;
77187       sqlite3ExplainPrintf(pOut, "BETWEEN(");
77188       sqlite3ExplainExpr(pOut, pX);
77189       sqlite3ExplainPrintf(pOut, ",");
77190       sqlite3ExplainExpr(pOut, pY);
77191       sqlite3ExplainPrintf(pOut, ",");
77192       sqlite3ExplainExpr(pOut, pZ);
77193       sqlite3ExplainPrintf(pOut, ")");
77194       break;
77195     }
77196     case TK_TRIGGER: {
77197       /* If the opcode is TK_TRIGGER, then the expression is a reference
77198       ** to a column in the new.* or old.* pseudo-tables available to
77199       ** trigger programs. In this case Expr.iTable is set to 1 for the
77200       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77201       ** is set to the column of the pseudo-table to read, or to -1 to
77202       ** read the rowid field.
77203       */
77204       sqlite3ExplainPrintf(pOut, "%s(%d)",
77205           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
77206       break;
77207     }
77208     case TK_CASE: {
77209       sqlite3ExplainPrintf(pOut, "CASE(");
77210       sqlite3ExplainExpr(pOut, pExpr->pLeft);
77211       sqlite3ExplainPrintf(pOut, ",");
77212       sqlite3ExplainExprList(pOut, pExpr->x.pList);
77213       break;
77214     }
77215 #ifndef SQLITE_OMIT_TRIGGER
77216     case TK_RAISE: {
77217       const char *zType = "unk";
77218       switch( pExpr->affinity ){
77219         case OE_Rollback:   zType = "rollback";  break;
77220         case OE_Abort:      zType = "abort";     break;
77221         case OE_Fail:       zType = "fail";      break;
77222         case OE_Ignore:     zType = "ignore";    break;
77223       }
77224       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
77225       break;
77226     }
77227 #endif
77228   }
77229   if( zBinOp ){
77230     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
77231     sqlite3ExplainExpr(pOut, pExpr->pLeft);
77232     sqlite3ExplainPrintf(pOut,",");
77233     sqlite3ExplainExpr(pOut, pExpr->pRight);
77234     sqlite3ExplainPrintf(pOut,")");
77235   }else if( zUniOp ){
77236     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
77237     sqlite3ExplainExpr(pOut, pExpr->pLeft);
77238     sqlite3ExplainPrintf(pOut,")");
77239   }
77240 }
77241 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
77242 
77243 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77244 /*
77245 ** Generate a human-readable explanation of an expression list.
77246 */
77247 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
77248   int i;
77249   if( pList==0 || pList->nExpr==0 ){
77250     sqlite3ExplainPrintf(pOut, "(empty-list)");
77251     return;
77252   }else if( pList->nExpr==1 ){
77253     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
77254   }else{
77255     sqlite3ExplainPush(pOut);
77256     for(i=0; i<pList->nExpr; i++){
77257       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
77258       sqlite3ExplainPush(pOut);
77259       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
77260       sqlite3ExplainPop(pOut);
77261       if( pList->a[i].zName ){
77262         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
77263       }
77264       if( pList->a[i].bSpanIsTab ){
77265         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
77266       }
77267       if( i<pList->nExpr-1 ){
77268         sqlite3ExplainNL(pOut);
77269       }
77270     }
77271     sqlite3ExplainPop(pOut);
77272   }
77273 }
77274 #endif /* SQLITE_DEBUG */
77275 
77276 /*
77277 ** Return TRUE if pExpr is an constant expression that is appropriate
77278 ** for factoring out of a loop.  Appropriate expressions are:
77279 **
77280 **    *  Any expression that evaluates to two or more opcodes.
77281 **
77282 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
77283 **       or OP_Variable that does not need to be placed in a
77284 **       specific register.
77285 **
77286 ** There is no point in factoring out single-instruction constant
77287 ** expressions that need to be placed in a particular register.
77288 ** We could factor them out, but then we would end up adding an
77289 ** OP_SCopy instruction to move the value into the correct register
77290 ** later.  We might as well just use the original instruction and
77291 ** avoid the OP_SCopy.
77292 */
77293 static int isAppropriateForFactoring(Expr *p){
77294   if( !sqlite3ExprIsConstantNotJoin(p) ){
77295     return 0;  /* Only constant expressions are appropriate for factoring */
77296   }
77297   if( (p->flags & EP_FixedDest)==0 ){
77298     return 1;  /* Any constant without a fixed destination is appropriate */
77299   }
77300   while( p->op==TK_UPLUS ) p = p->pLeft;
77301   switch( p->op ){
77302 #ifndef SQLITE_OMIT_BLOB_LITERAL
77303     case TK_BLOB:
77304 #endif
77305     case TK_VARIABLE:
77306     case TK_INTEGER:
77307     case TK_FLOAT:
77308     case TK_NULL:
77309     case TK_STRING: {
77310       testcase( p->op==TK_BLOB );
77311       testcase( p->op==TK_VARIABLE );
77312       testcase( p->op==TK_INTEGER );
77313       testcase( p->op==TK_FLOAT );
77314       testcase( p->op==TK_NULL );
77315       testcase( p->op==TK_STRING );
77316       /* Single-instruction constants with a fixed destination are
77317       ** better done in-line.  If we factor them, they will just end
77318       ** up generating an OP_SCopy to move the value to the destination
77319       ** register. */
77320       return 0;
77321     }
77322     case TK_UMINUS: {
77323       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77324         return 0;
77325       }
77326       break;
77327     }
77328     default: {
77329       break;
77330     }
77331   }
77332   return 1;
77333 }
77334 
77335 /*
77336 ** If pExpr is a constant expression that is appropriate for
77337 ** factoring out of a loop, then evaluate the expression
77338 ** into a register and convert the expression into a TK_REGISTER
77339 ** expression.
77340 */
77341 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77342   Parse *pParse = pWalker->pParse;
77343   switch( pExpr->op ){
77344     case TK_IN:
77345     case TK_REGISTER: {
77346       return WRC_Prune;
77347     }
77348     case TK_COLLATE: {
77349       return WRC_Continue;
77350     }
77351     case TK_FUNCTION:
77352     case TK_AGG_FUNCTION:
77353     case TK_CONST_FUNC: {
77354       /* The arguments to a function have a fixed destination.
77355       ** Mark them this way to avoid generated unneeded OP_SCopy
77356       ** instructions.
77357       */
77358       ExprList *pList = pExpr->x.pList;
77359       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77360       if( pList ){
77361         int i = pList->nExpr;
77362         struct ExprList_item *pItem = pList->a;
77363         for(; i>0; i--, pItem++){
77364           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77365         }
77366       }
77367       break;
77368     }
77369   }
77370   if( isAppropriateForFactoring(pExpr) ){
77371     int r1 = ++pParse->nMem;
77372     int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77373     /* If r2!=r1, it means that register r1 is never used.  That is harmless
77374     ** but suboptimal, so we want to know about the situation to fix it.
77375     ** Hence the following assert: */
77376     assert( r2==r1 );
77377     pExpr->op2 = pExpr->op;
77378     pExpr->op = TK_REGISTER;
77379     pExpr->iTable = r2;
77380     return WRC_Prune;
77381   }
77382   return WRC_Continue;
77383 }
77384 
77385 /*
77386 ** Preevaluate constant subexpressions within pExpr and store the
77387 ** results in registers.  Modify pExpr so that the constant subexpresions
77388 ** are TK_REGISTER opcodes that refer to the precomputed values.
77389 **
77390 ** This routine is a no-op if the jump to the cookie-check code has
77391 ** already occur.  Since the cookie-check jump is generated prior to
77392 ** any other serious processing, this check ensures that there is no
77393 ** way to accidently bypass the constant initializations.
77394 **
77395 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
77396 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
77397 ** interface.  This allows test logic to verify that the same answer is
77398 ** obtained for queries regardless of whether or not constants are
77399 ** precomputed into registers or if they are inserted in-line.
77400 */
77401 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77402   Walker w;
77403   if( pParse->cookieGoto ) return;
77404   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
77405   w.xExprCallback = evalConstExpr;
77406   w.xSelectCallback = 0;
77407   w.pParse = pParse;
77408   sqlite3WalkExpr(&w, pExpr);
77409 }
77410 
77411 
77412 /*
77413 ** Generate code that pushes the value of every element of the given
77414 ** expression list into a sequence of registers beginning at target.
77415 **
77416 ** Return the number of elements evaluated.
77417 */
77418 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
77419   Parse *pParse,     /* Parsing context */
77420   ExprList *pList,   /* The expression list to be coded */
77421   int target,        /* Where to write results */
77422   int doHardCopy     /* Make a hard copy of every element */
77423 ){
77424   struct ExprList_item *pItem;
77425   int i, n;
77426   assert( pList!=0 );
77427   assert( target>0 );
77428   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77429   n = pList->nExpr;
77430   for(pItem=pList->a, i=0; i<n; i++, pItem++){
77431     Expr *pExpr = pItem->pExpr;
77432     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
77433     if( inReg!=target+i ){
77434       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77435                         inReg, target+i);
77436     }
77437   }
77438   return n;
77439 }
77440 
77441 /*
77442 ** Generate code for a BETWEEN operator.
77443 **
77444 **    x BETWEEN y AND z
77445 **
77446 ** The above is equivalent to
77447 **
77448 **    x>=y AND x<=z
77449 **
77450 ** Code it as such, taking care to do the common subexpression
77451 ** elementation of x.
77452 */
77453 static void exprCodeBetween(
77454   Parse *pParse,    /* Parsing and code generating context */
77455   Expr *pExpr,      /* The BETWEEN expression */
77456   int dest,         /* Jump here if the jump is taken */
77457   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77458   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77459 ){
77460   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77461   Expr compLeft;    /* The  x>=y  term */
77462   Expr compRight;   /* The  x<=z  term */
77463   Expr exprX;       /* The  x  subexpression */
77464   int regFree1 = 0; /* Temporary use register */
77465 
77466   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77467   exprX = *pExpr->pLeft;
77468   exprAnd.op = TK_AND;
77469   exprAnd.pLeft = &compLeft;
77470   exprAnd.pRight = &compRight;
77471   compLeft.op = TK_GE;
77472   compLeft.pLeft = &exprX;
77473   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77474   compRight.op = TK_LE;
77475   compRight.pLeft = &exprX;
77476   compRight.pRight = pExpr->x.pList->a[1].pExpr;
77477   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
77478   exprX.op = TK_REGISTER;
77479   if( jumpIfTrue ){
77480     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77481   }else{
77482     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77483   }
77484   sqlite3ReleaseTempReg(pParse, regFree1);
77485 
77486   /* Ensure adequate test coverage */
77487   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77488   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77489   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77490   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77491   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77492   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77493   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77494   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77495 }
77496 
77497 /*
77498 ** Generate code for a boolean expression such that a jump is made
77499 ** to the label "dest" if the expression is true but execution
77500 ** continues straight thru if the expression is false.
77501 **
77502 ** If the expression evaluates to NULL (neither true nor false), then
77503 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
77504 **
77505 ** This code depends on the fact that certain token values (ex: TK_EQ)
77506 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77507 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77508 ** the make process cause these values to align.  Assert()s in the code
77509 ** below verify that the numbers are aligned correctly.
77510 */
77511 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77512   Vdbe *v = pParse->pVdbe;
77513   int op = 0;
77514   int regFree1 = 0;
77515   int regFree2 = 0;
77516   int r1, r2;
77517 
77518   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77519   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
77520   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77521   op = pExpr->op;
77522   switch( op ){
77523     case TK_AND: {
77524       int d2 = sqlite3VdbeMakeLabel(v);
77525       testcase( jumpIfNull==0 );
77526       sqlite3ExprCachePush(pParse);
77527       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
77528       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77529       sqlite3VdbeResolveLabel(v, d2);
77530       sqlite3ExprCachePop(pParse, 1);
77531       break;
77532     }
77533     case TK_OR: {
77534       testcase( jumpIfNull==0 );
77535       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77536       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77537       break;
77538     }
77539     case TK_NOT: {
77540       testcase( jumpIfNull==0 );
77541       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77542       break;
77543     }
77544     case TK_LT:
77545     case TK_LE:
77546     case TK_GT:
77547     case TK_GE:
77548     case TK_NE:
77549     case TK_EQ: {
77550       assert( TK_LT==OP_Lt );
77551       assert( TK_LE==OP_Le );
77552       assert( TK_GT==OP_Gt );
77553       assert( TK_GE==OP_Ge );
77554       assert( TK_EQ==OP_Eq );
77555       assert( TK_NE==OP_Ne );
77556       testcase( op==TK_LT );
77557       testcase( op==TK_LE );
77558       testcase( op==TK_GT );
77559       testcase( op==TK_GE );
77560       testcase( op==TK_EQ );
77561       testcase( op==TK_NE );
77562       testcase( jumpIfNull==0 );
77563       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77564       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77565       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77566                   r1, r2, dest, jumpIfNull);
77567       testcase( regFree1==0 );
77568       testcase( regFree2==0 );
77569       break;
77570     }
77571     case TK_IS:
77572     case TK_ISNOT: {
77573       testcase( op==TK_IS );
77574       testcase( op==TK_ISNOT );
77575       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77576       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77577       op = (op==TK_IS) ? TK_EQ : TK_NE;
77578       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77579                   r1, r2, dest, SQLITE_NULLEQ);
77580       testcase( regFree1==0 );
77581       testcase( regFree2==0 );
77582       break;
77583     }
77584     case TK_ISNULL:
77585     case TK_NOTNULL: {
77586       assert( TK_ISNULL==OP_IsNull );
77587       assert( TK_NOTNULL==OP_NotNull );
77588       testcase( op==TK_ISNULL );
77589       testcase( op==TK_NOTNULL );
77590       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77591       sqlite3VdbeAddOp2(v, op, r1, dest);
77592       testcase( regFree1==0 );
77593       break;
77594     }
77595     case TK_BETWEEN: {
77596       testcase( jumpIfNull==0 );
77597       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77598       break;
77599     }
77600 #ifndef SQLITE_OMIT_SUBQUERY
77601     case TK_IN: {
77602       int destIfFalse = sqlite3VdbeMakeLabel(v);
77603       int destIfNull = jumpIfNull ? dest : destIfFalse;
77604       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77605       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
77606       sqlite3VdbeResolveLabel(v, destIfFalse);
77607       break;
77608     }
77609 #endif
77610     default: {
77611       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77612       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77613       testcase( regFree1==0 );
77614       testcase( jumpIfNull==0 );
77615       break;
77616     }
77617   }
77618   sqlite3ReleaseTempReg(pParse, regFree1);
77619   sqlite3ReleaseTempReg(pParse, regFree2);
77620 }
77621 
77622 /*
77623 ** Generate code for a boolean expression such that a jump is made
77624 ** to the label "dest" if the expression is false but execution
77625 ** continues straight thru if the expression is true.
77626 **
77627 ** If the expression evaluates to NULL (neither true nor false) then
77628 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
77629 ** is 0.
77630 */
77631 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77632   Vdbe *v = pParse->pVdbe;
77633   int op = 0;
77634   int regFree1 = 0;
77635   int regFree2 = 0;
77636   int r1, r2;
77637 
77638   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77639   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
77640   if( pExpr==0 )    return;
77641 
77642   /* The value of pExpr->op and op are related as follows:
77643   **
77644   **       pExpr->op            op
77645   **       ---------          ----------
77646   **       TK_ISNULL          OP_NotNull
77647   **       TK_NOTNULL         OP_IsNull
77648   **       TK_NE              OP_Eq
77649   **       TK_EQ              OP_Ne
77650   **       TK_GT              OP_Le
77651   **       TK_LE              OP_Gt
77652   **       TK_GE              OP_Lt
77653   **       TK_LT              OP_Ge
77654   **
77655   ** For other values of pExpr->op, op is undefined and unused.
77656   ** The value of TK_ and OP_ constants are arranged such that we
77657   ** can compute the mapping above using the following expression.
77658   ** Assert()s verify that the computation is correct.
77659   */
77660   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77661 
77662   /* Verify correct alignment of TK_ and OP_ constants
77663   */
77664   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
77665   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
77666   assert( pExpr->op!=TK_NE || op==OP_Eq );
77667   assert( pExpr->op!=TK_EQ || op==OP_Ne );
77668   assert( pExpr->op!=TK_LT || op==OP_Ge );
77669   assert( pExpr->op!=TK_LE || op==OP_Gt );
77670   assert( pExpr->op!=TK_GT || op==OP_Le );
77671   assert( pExpr->op!=TK_GE || op==OP_Lt );
77672 
77673   switch( pExpr->op ){
77674     case TK_AND: {
77675       testcase( jumpIfNull==0 );
77676       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77677       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77678       break;
77679     }
77680     case TK_OR: {
77681       int d2 = sqlite3VdbeMakeLabel(v);
77682       testcase( jumpIfNull==0 );
77683       sqlite3ExprCachePush(pParse);
77684       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
77685       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
77686       sqlite3VdbeResolveLabel(v, d2);
77687       sqlite3ExprCachePop(pParse, 1);
77688       break;
77689     }
77690     case TK_NOT: {
77691       testcase( jumpIfNull==0 );
77692       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77693       break;
77694     }
77695     case TK_LT:
77696     case TK_LE:
77697     case TK_GT:
77698     case TK_GE:
77699     case TK_NE:
77700     case TK_EQ: {
77701       testcase( op==TK_LT );
77702       testcase( op==TK_LE );
77703       testcase( op==TK_GT );
77704       testcase( op==TK_GE );
77705       testcase( op==TK_EQ );
77706       testcase( op==TK_NE );
77707       testcase( jumpIfNull==0 );
77708       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77709       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77710       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77711                   r1, r2, dest, jumpIfNull);
77712       testcase( regFree1==0 );
77713       testcase( regFree2==0 );
77714       break;
77715     }
77716     case TK_IS:
77717     case TK_ISNOT: {
77718       testcase( pExpr->op==TK_IS );
77719       testcase( pExpr->op==TK_ISNOT );
77720       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77721       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77722       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
77723       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77724                   r1, r2, dest, SQLITE_NULLEQ);
77725       testcase( regFree1==0 );
77726       testcase( regFree2==0 );
77727       break;
77728     }
77729     case TK_ISNULL:
77730     case TK_NOTNULL: {
77731       testcase( op==TK_ISNULL );
77732       testcase( op==TK_NOTNULL );
77733       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77734       sqlite3VdbeAddOp2(v, op, r1, dest);
77735       testcase( regFree1==0 );
77736       break;
77737     }
77738     case TK_BETWEEN: {
77739       testcase( jumpIfNull==0 );
77740       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
77741       break;
77742     }
77743 #ifndef SQLITE_OMIT_SUBQUERY
77744     case TK_IN: {
77745       if( jumpIfNull ){
77746         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
77747       }else{
77748         int destIfNull = sqlite3VdbeMakeLabel(v);
77749         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
77750         sqlite3VdbeResolveLabel(v, destIfNull);
77751       }
77752       break;
77753     }
77754 #endif
77755     default: {
77756       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77757       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
77758       testcase( regFree1==0 );
77759       testcase( jumpIfNull==0 );
77760       break;
77761     }
77762   }
77763   sqlite3ReleaseTempReg(pParse, regFree1);
77764   sqlite3ReleaseTempReg(pParse, regFree2);
77765 }
77766 
77767 /*
77768 ** Do a deep comparison of two expression trees.  Return 0 if the two
77769 ** expressions are completely identical.  Return 1 if they differ only
77770 ** by a COLLATE operator at the top level.  Return 2 if there are differences
77771 ** other than the top-level COLLATE operator.
77772 **
77773 ** Sometimes this routine will return 2 even if the two expressions
77774 ** really are equivalent.  If we cannot prove that the expressions are
77775 ** identical, we return 2 just to be safe.  So if this routine
77776 ** returns 2, then you do not really know for certain if the two
77777 ** expressions are the same.  But if you get a 0 or 1 return, then you
77778 ** can be sure the expressions are the same.  In the places where
77779 ** this routine is used, it does not hurt to get an extra 2 - that
77780 ** just might result in some slightly slower code.  But returning
77781 ** an incorrect 0 or 1 could lead to a malfunction.
77782 */
77783 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
77784   if( pA==0||pB==0 ){
77785     return pB==pA ? 0 : 2;
77786   }
77787   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
77788   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
77789   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
77790     return 2;
77791   }
77792   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
77793   if( pA->op!=pB->op ){
77794     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
77795       return 1;
77796     }
77797     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
77798       return 1;
77799     }
77800     return 2;
77801   }
77802   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
77803   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
77804   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
77805   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
77806   if( ExprHasProperty(pA, EP_IntValue) ){
77807     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
77808       return 2;
77809     }
77810   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
77811     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
77812     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
77813       return pA->op==TK_COLLATE ? 1 : 2;
77814     }
77815   }
77816   return 0;
77817 }
77818 
77819 /*
77820 ** Compare two ExprList objects.  Return 0 if they are identical and
77821 ** non-zero if they differ in any way.
77822 **
77823 ** This routine might return non-zero for equivalent ExprLists.  The
77824 ** only consequence will be disabled optimizations.  But this routine
77825 ** must never return 0 if the two ExprList objects are different, or
77826 ** a malfunction will result.
77827 **
77828 ** Two NULL pointers are considered to be the same.  But a NULL pointer
77829 ** always differs from a non-NULL pointer.
77830 */
77831 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
77832   int i;
77833   if( pA==0 && pB==0 ) return 0;
77834   if( pA==0 || pB==0 ) return 1;
77835   if( pA->nExpr!=pB->nExpr ) return 1;
77836   for(i=0; i<pA->nExpr; i++){
77837     Expr *pExprA = pA->a[i].pExpr;
77838     Expr *pExprB = pB->a[i].pExpr;
77839     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
77840     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
77841   }
77842   return 0;
77843 }
77844 
77845 /*
77846 ** An instance of the following structure is used by the tree walker
77847 ** to count references to table columns in the arguments of an
77848 ** aggregate function, in order to implement the
77849 ** sqlite3FunctionThisSrc() routine.
77850 */
77851 struct SrcCount {
77852   SrcList *pSrc;   /* One particular FROM clause in a nested query */
77853   int nThis;       /* Number of references to columns in pSrcList */
77854   int nOther;      /* Number of references to columns in other FROM clauses */
77855 };
77856 
77857 /*
77858 ** Count the number of references to columns.
77859 */
77860 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
77861   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
77862   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
77863   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
77864   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
77865   ** NEVER() will need to be removed. */
77866   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
77867     int i;
77868     struct SrcCount *p = pWalker->u.pSrcCount;
77869     SrcList *pSrc = p->pSrc;
77870     for(i=0; i<pSrc->nSrc; i++){
77871       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
77872     }
77873     if( i<pSrc->nSrc ){
77874       p->nThis++;
77875     }else{
77876       p->nOther++;
77877     }
77878   }
77879   return WRC_Continue;
77880 }
77881 
77882 /*
77883 ** Determine if any of the arguments to the pExpr Function reference
77884 ** pSrcList.  Return true if they do.  Also return true if the function
77885 ** has no arguments or has only constant arguments.  Return false if pExpr
77886 ** references columns but not columns of tables found in pSrcList.
77887 */
77888 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
77889   Walker w;
77890   struct SrcCount cnt;
77891   assert( pExpr->op==TK_AGG_FUNCTION );
77892   memset(&w, 0, sizeof(w));
77893   w.xExprCallback = exprSrcCount;
77894   w.u.pSrcCount = &cnt;
77895   cnt.pSrc = pSrcList;
77896   cnt.nThis = 0;
77897   cnt.nOther = 0;
77898   sqlite3WalkExprList(&w, pExpr->x.pList);
77899   return cnt.nThis>0 || cnt.nOther==0;
77900 }
77901 
77902 /*
77903 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
77904 ** the new element.  Return a negative number if malloc fails.
77905 */
77906 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
77907   int i;
77908   pInfo->aCol = sqlite3ArrayAllocate(
77909        db,
77910        pInfo->aCol,
77911        sizeof(pInfo->aCol[0]),
77912        &pInfo->nColumn,
77913        &i
77914   );
77915   return i;
77916 }
77917 
77918 /*
77919 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
77920 ** the new element.  Return a negative number if malloc fails.
77921 */
77922 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
77923   int i;
77924   pInfo->aFunc = sqlite3ArrayAllocate(
77925        db,
77926        pInfo->aFunc,
77927        sizeof(pInfo->aFunc[0]),
77928        &pInfo->nFunc,
77929        &i
77930   );
77931   return i;
77932 }
77933 
77934 /*
77935 ** This is the xExprCallback for a tree walker.  It is used to
77936 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
77937 ** for additional information.
77938 */
77939 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
77940   int i;
77941   NameContext *pNC = pWalker->u.pNC;
77942   Parse *pParse = pNC->pParse;
77943   SrcList *pSrcList = pNC->pSrcList;
77944   AggInfo *pAggInfo = pNC->pAggInfo;
77945 
77946   switch( pExpr->op ){
77947     case TK_AGG_COLUMN:
77948     case TK_COLUMN: {
77949       testcase( pExpr->op==TK_AGG_COLUMN );
77950       testcase( pExpr->op==TK_COLUMN );
77951       /* Check to see if the column is in one of the tables in the FROM
77952       ** clause of the aggregate query */
77953       if( ALWAYS(pSrcList!=0) ){
77954         struct SrcList_item *pItem = pSrcList->a;
77955         for(i=0; i<pSrcList->nSrc; i++, pItem++){
77956           struct AggInfo_col *pCol;
77957           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
77958           if( pExpr->iTable==pItem->iCursor ){
77959             /* If we reach this point, it means that pExpr refers to a table
77960             ** that is in the FROM clause of the aggregate query.
77961             **
77962             ** Make an entry for the column in pAggInfo->aCol[] if there
77963             ** is not an entry there already.
77964             */
77965             int k;
77966             pCol = pAggInfo->aCol;
77967             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
77968               if( pCol->iTable==pExpr->iTable &&
77969                   pCol->iColumn==pExpr->iColumn ){
77970                 break;
77971               }
77972             }
77973             if( (k>=pAggInfo->nColumn)
77974              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
77975             ){
77976               pCol = &pAggInfo->aCol[k];
77977               pCol->pTab = pExpr->pTab;
77978               pCol->iTable = pExpr->iTable;
77979               pCol->iColumn = pExpr->iColumn;
77980               pCol->iMem = ++pParse->nMem;
77981               pCol->iSorterColumn = -1;
77982               pCol->pExpr = pExpr;
77983               if( pAggInfo->pGroupBy ){
77984                 int j, n;
77985                 ExprList *pGB = pAggInfo->pGroupBy;
77986                 struct ExprList_item *pTerm = pGB->a;
77987                 n = pGB->nExpr;
77988                 for(j=0; j<n; j++, pTerm++){
77989                   Expr *pE = pTerm->pExpr;
77990                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
77991                       pE->iColumn==pExpr->iColumn ){
77992                     pCol->iSorterColumn = j;
77993                     break;
77994                   }
77995                 }
77996               }
77997               if( pCol->iSorterColumn<0 ){
77998                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
77999               }
78000             }
78001             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
78002             ** because it was there before or because we just created it).
78003             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
78004             ** pAggInfo->aCol[] entry.
78005             */
78006             ExprSetIrreducible(pExpr);
78007             pExpr->pAggInfo = pAggInfo;
78008             pExpr->op = TK_AGG_COLUMN;
78009             pExpr->iAgg = (i16)k;
78010             break;
78011           } /* endif pExpr->iTable==pItem->iCursor */
78012         } /* end loop over pSrcList */
78013       }
78014       return WRC_Prune;
78015     }
78016     case TK_AGG_FUNCTION: {
78017       if( (pNC->ncFlags & NC_InAggFunc)==0
78018        && pWalker->walkerDepth==pExpr->op2
78019       ){
78020         /* Check to see if pExpr is a duplicate of another aggregate
78021         ** function that is already in the pAggInfo structure
78022         */
78023         struct AggInfo_func *pItem = pAggInfo->aFunc;
78024         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
78025           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
78026             break;
78027           }
78028         }
78029         if( i>=pAggInfo->nFunc ){
78030           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
78031           */
78032           u8 enc = ENC(pParse->db);
78033           i = addAggInfoFunc(pParse->db, pAggInfo);
78034           if( i>=0 ){
78035             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78036             pItem = &pAggInfo->aFunc[i];
78037             pItem->pExpr = pExpr;
78038             pItem->iMem = ++pParse->nMem;
78039             assert( !ExprHasProperty(pExpr, EP_IntValue) );
78040             pItem->pFunc = sqlite3FindFunction(pParse->db,
78041                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
78042                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
78043             if( pExpr->flags & EP_Distinct ){
78044               pItem->iDistinct = pParse->nTab++;
78045             }else{
78046               pItem->iDistinct = -1;
78047             }
78048           }
78049         }
78050         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
78051         */
78052         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78053         ExprSetIrreducible(pExpr);
78054         pExpr->iAgg = (i16)i;
78055         pExpr->pAggInfo = pAggInfo;
78056         return WRC_Prune;
78057       }else{
78058         return WRC_Continue;
78059       }
78060     }
78061   }
78062   return WRC_Continue;
78063 }
78064 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
78065   UNUSED_PARAMETER(pWalker);
78066   UNUSED_PARAMETER(pSelect);
78067   return WRC_Continue;
78068 }
78069 
78070 /*
78071 ** Analyze the pExpr expression looking for aggregate functions and
78072 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
78073 ** points to.  Additional entries are made on the AggInfo object as
78074 ** necessary.
78075 **
78076 ** This routine should only be called after the expression has been
78077 ** analyzed by sqlite3ResolveExprNames().
78078 */
78079 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
78080   Walker w;
78081   memset(&w, 0, sizeof(w));
78082   w.xExprCallback = analyzeAggregate;
78083   w.xSelectCallback = analyzeAggregatesInSelect;
78084   w.u.pNC = pNC;
78085   assert( pNC->pSrcList!=0 );
78086   sqlite3WalkExpr(&w, pExpr);
78087 }
78088 
78089 /*
78090 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
78091 ** expression list.  Return the number of errors.
78092 **
78093 ** If an error is found, the analysis is cut short.
78094 */
78095 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
78096   struct ExprList_item *pItem;
78097   int i;
78098   if( pList ){
78099     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78100       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
78101     }
78102   }
78103 }
78104 
78105 /*
78106 ** Allocate a single new register for use to hold some intermediate result.
78107 */
78108 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
78109   if( pParse->nTempReg==0 ){
78110     return ++pParse->nMem;
78111   }
78112   return pParse->aTempReg[--pParse->nTempReg];
78113 }
78114 
78115 /*
78116 ** Deallocate a register, making available for reuse for some other
78117 ** purpose.
78118 **
78119 ** If a register is currently being used by the column cache, then
78120 ** the dallocation is deferred until the column cache line that uses
78121 ** the register becomes stale.
78122 */
78123 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
78124   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78125     int i;
78126     struct yColCache *p;
78127     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78128       if( p->iReg==iReg ){
78129         p->tempReg = 1;
78130         return;
78131       }
78132     }
78133     pParse->aTempReg[pParse->nTempReg++] = iReg;
78134   }
78135 }
78136 
78137 /*
78138 ** Allocate or deallocate a block of nReg consecutive registers
78139 */
78140 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
78141   int i, n;
78142   i = pParse->iRangeReg;
78143   n = pParse->nRangeReg;
78144   if( nReg<=n ){
78145     assert( !usedAsColumnCache(pParse, i, i+n-1) );
78146     pParse->iRangeReg += nReg;
78147     pParse->nRangeReg -= nReg;
78148   }else{
78149     i = pParse->nMem+1;
78150     pParse->nMem += nReg;
78151   }
78152   return i;
78153 }
78154 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
78155   sqlite3ExprCacheRemove(pParse, iReg, nReg);
78156   if( nReg>pParse->nRangeReg ){
78157     pParse->nRangeReg = nReg;
78158     pParse->iRangeReg = iReg;
78159   }
78160 }
78161 
78162 /*
78163 ** Mark all temporary registers as being unavailable for reuse.
78164 */
78165 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
78166   pParse->nTempReg = 0;
78167   pParse->nRangeReg = 0;
78168 }
78169 
78170 /************** End of expr.c ************************************************/
78171 /************** Begin file alter.c *******************************************/
78172 /*
78173 ** 2005 February 15
78174 **
78175 ** The author disclaims copyright to this source code.  In place of
78176 ** a legal notice, here is a blessing:
78177 **
78178 **    May you do good and not evil.
78179 **    May you find forgiveness for yourself and forgive others.
78180 **    May you share freely, never taking more than you give.
78181 **
78182 *************************************************************************
78183 ** This file contains C code routines that used to generate VDBE code
78184 ** that implements the ALTER TABLE command.
78185 */
78186 
78187 /*
78188 ** The code in this file only exists if we are not omitting the
78189 ** ALTER TABLE logic from the build.
78190 */
78191 #ifndef SQLITE_OMIT_ALTERTABLE
78192 
78193 
78194 /*
78195 ** This function is used by SQL generated to implement the
78196 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
78197 ** CREATE INDEX command. The second is a table name. The table name in
78198 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
78199 ** argument and the result returned. Examples:
78200 **
78201 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
78202 **     -> 'CREATE TABLE def(a, b, c)'
78203 **
78204 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
78205 **     -> 'CREATE INDEX i ON def(a, b, c)'
78206 */
78207 static void renameTableFunc(
78208   sqlite3_context *context,
78209   int NotUsed,
78210   sqlite3_value **argv
78211 ){
78212   unsigned char const *zSql = sqlite3_value_text(argv[0]);
78213   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78214 
78215   int token;
78216   Token tname;
78217   unsigned char const *zCsr = zSql;
78218   int len = 0;
78219   char *zRet;
78220 
78221   sqlite3 *db = sqlite3_context_db_handle(context);
78222 
78223   UNUSED_PARAMETER(NotUsed);
78224 
78225   /* The principle used to locate the table name in the CREATE TABLE
78226   ** statement is that the table name is the first non-space token that
78227   ** is immediately followed by a TK_LP or TK_USING token.
78228   */
78229   if( zSql ){
78230     do {
78231       if( !*zCsr ){
78232         /* Ran out of input before finding an opening bracket. Return NULL. */
78233         return;
78234       }
78235 
78236       /* Store the token that zCsr points to in tname. */
78237       tname.z = (char*)zCsr;
78238       tname.n = len;
78239 
78240       /* Advance zCsr to the next token. Store that token type in 'token',
78241       ** and its length in 'len' (to be used next iteration of this loop).
78242       */
78243       do {
78244         zCsr += len;
78245         len = sqlite3GetToken(zCsr, &token);
78246       } while( token==TK_SPACE );
78247       assert( len>0 );
78248     } while( token!=TK_LP && token!=TK_USING );
78249 
78250     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
78251        zTableName, tname.z+tname.n);
78252     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78253   }
78254 }
78255 
78256 /*
78257 ** This C function implements an SQL user function that is used by SQL code
78258 ** generated by the ALTER TABLE ... RENAME command to modify the definition
78259 ** of any foreign key constraints that use the table being renamed as the
78260 ** parent table. It is passed three arguments:
78261 **
78262 **   1) The complete text of the CREATE TABLE statement being modified,
78263 **   2) The old name of the table being renamed, and
78264 **   3) The new name of the table being renamed.
78265 **
78266 ** It returns the new CREATE TABLE statement. For example:
78267 **
78268 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78269 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
78270 */
78271 #ifndef SQLITE_OMIT_FOREIGN_KEY
78272 static void renameParentFunc(
78273   sqlite3_context *context,
78274   int NotUsed,
78275   sqlite3_value **argv
78276 ){
78277   sqlite3 *db = sqlite3_context_db_handle(context);
78278   char *zOutput = 0;
78279   char *zResult;
78280   unsigned char const *zInput = sqlite3_value_text(argv[0]);
78281   unsigned char const *zOld = sqlite3_value_text(argv[1]);
78282   unsigned char const *zNew = sqlite3_value_text(argv[2]);
78283 
78284   unsigned const char *z;         /* Pointer to token */
78285   int n;                          /* Length of token z */
78286   int token;                      /* Type of token */
78287 
78288   UNUSED_PARAMETER(NotUsed);
78289   for(z=zInput; *z; z=z+n){
78290     n = sqlite3GetToken(z, &token);
78291     if( token==TK_REFERENCES ){
78292       char *zParent;
78293       do {
78294         z += n;
78295         n = sqlite3GetToken(z, &token);
78296       }while( token==TK_SPACE );
78297 
78298       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
78299       if( zParent==0 ) break;
78300       sqlite3Dequote(zParent);
78301       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
78302         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
78303             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78304         );
78305         sqlite3DbFree(db, zOutput);
78306         zOutput = zOut;
78307         zInput = &z[n];
78308       }
78309       sqlite3DbFree(db, zParent);
78310     }
78311   }
78312 
78313   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
78314   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
78315   sqlite3DbFree(db, zOutput);
78316 }
78317 #endif
78318 
78319 #ifndef SQLITE_OMIT_TRIGGER
78320 /* This function is used by SQL generated to implement the
78321 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
78322 ** statement. The second is a table name. The table name in the CREATE
78323 ** TRIGGER statement is replaced with the third argument and the result
78324 ** returned. This is analagous to renameTableFunc() above, except for CREATE
78325 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
78326 */
78327 static void renameTriggerFunc(
78328   sqlite3_context *context,
78329   int NotUsed,
78330   sqlite3_value **argv
78331 ){
78332   unsigned char const *zSql = sqlite3_value_text(argv[0]);
78333   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78334 
78335   int token;
78336   Token tname;
78337   int dist = 3;
78338   unsigned char const *zCsr = zSql;
78339   int len = 0;
78340   char *zRet;
78341   sqlite3 *db = sqlite3_context_db_handle(context);
78342 
78343   UNUSED_PARAMETER(NotUsed);
78344 
78345   /* The principle used to locate the table name in the CREATE TRIGGER
78346   ** statement is that the table name is the first token that is immediatedly
78347   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78348   ** of TK_WHEN, TK_BEGIN or TK_FOR.
78349   */
78350   if( zSql ){
78351     do {
78352 
78353       if( !*zCsr ){
78354         /* Ran out of input before finding the table name. Return NULL. */
78355         return;
78356       }
78357 
78358       /* Store the token that zCsr points to in tname. */
78359       tname.z = (char*)zCsr;
78360       tname.n = len;
78361 
78362       /* Advance zCsr to the next token. Store that token type in 'token',
78363       ** and its length in 'len' (to be used next iteration of this loop).
78364       */
78365       do {
78366         zCsr += len;
78367         len = sqlite3GetToken(zCsr, &token);
78368       }while( token==TK_SPACE );
78369       assert( len>0 );
78370 
78371       /* Variable 'dist' stores the number of tokens read since the most
78372       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
78373       ** token is read and 'dist' equals 2, the condition stated above
78374       ** to be met.
78375       **
78376       ** Note that ON cannot be a database, table or column name, so
78377       ** there is no need to worry about syntax like
78378       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78379       */
78380       dist++;
78381       if( token==TK_DOT || token==TK_ON ){
78382         dist = 0;
78383       }
78384     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78385 
78386     /* Variable tname now contains the token that is the old table-name
78387     ** in the CREATE TRIGGER statement.
78388     */
78389     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
78390        zTableName, tname.z+tname.n);
78391     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78392   }
78393 }
78394 #endif   /* !SQLITE_OMIT_TRIGGER */
78395 
78396 /*
78397 ** Register built-in functions used to help implement ALTER TABLE
78398 */
78399 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
78400   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
78401     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
78402 #ifndef SQLITE_OMIT_TRIGGER
78403     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
78404 #endif
78405 #ifndef SQLITE_OMIT_FOREIGN_KEY
78406     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
78407 #endif
78408   };
78409   int i;
78410   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78411   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78412 
78413   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78414     sqlite3FuncDefInsert(pHash, &aFunc[i]);
78415   }
78416 }
78417 
78418 /*
78419 ** This function is used to create the text of expressions of the form:
78420 **
78421 **   name=<constant1> OR name=<constant2> OR ...
78422 **
78423 ** If argument zWhere is NULL, then a pointer string containing the text
78424 ** "name=<constant>" is returned, where <constant> is the quoted version
78425 ** of the string passed as argument zConstant. The returned buffer is
78426 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
78427 ** caller to ensure that it is eventually freed.
78428 **
78429 ** If argument zWhere is not NULL, then the string returned is
78430 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78431 ** In this case zWhere is passed to sqlite3DbFree() before returning.
78432 **
78433 */
78434 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
78435   char *zNew;
78436   if( !zWhere ){
78437     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
78438   }else{
78439     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78440     sqlite3DbFree(db, zWhere);
78441   }
78442   return zNew;
78443 }
78444 
78445 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78446 /*
78447 ** Generate the text of a WHERE expression which can be used to select all
78448 ** tables that have foreign key constraints that refer to table pTab (i.e.
78449 ** constraints for which pTab is the parent table) from the sqlite_master
78450 ** table.
78451 */
78452 static char *whereForeignKeys(Parse *pParse, Table *pTab){
78453   FKey *p;
78454   char *zWhere = 0;
78455   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78456     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78457   }
78458   return zWhere;
78459 }
78460 #endif
78461 
78462 /*
78463 ** Generate the text of a WHERE expression which can be used to select all
78464 ** temporary triggers on table pTab from the sqlite_temp_master table. If
78465 ** table pTab has no temporary triggers, or is itself stored in the
78466 ** temporary database, NULL is returned.
78467 */
78468 static char *whereTempTriggers(Parse *pParse, Table *pTab){
78469   Trigger *pTrig;
78470   char *zWhere = 0;
78471   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78472 
78473   /* If the table is not located in the temp-db (in which case NULL is
78474   ** returned, loop through the tables list of triggers. For each trigger
78475   ** that is not part of the temp-db schema, add a clause to the WHERE
78476   ** expression being built up in zWhere.
78477   */
78478   if( pTab->pSchema!=pTempSchema ){
78479     sqlite3 *db = pParse->db;
78480     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78481       if( pTrig->pSchema==pTempSchema ){
78482         zWhere = whereOrName(db, zWhere, pTrig->zName);
78483       }
78484     }
78485   }
78486   if( zWhere ){
78487     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78488     sqlite3DbFree(pParse->db, zWhere);
78489     zWhere = zNew;
78490   }
78491   return zWhere;
78492 }
78493 
78494 /*
78495 ** Generate code to drop and reload the internal representation of table
78496 ** pTab from the database, including triggers and temporary triggers.
78497 ** Argument zName is the name of the table in the database schema at
78498 ** the time the generated code is executed. This can be different from
78499 ** pTab->zName if this function is being called to code part of an
78500 ** "ALTER TABLE RENAME TO" statement.
78501 */
78502 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78503   Vdbe *v;
78504   char *zWhere;
78505   int iDb;                   /* Index of database containing pTab */
78506 #ifndef SQLITE_OMIT_TRIGGER
78507   Trigger *pTrig;
78508 #endif
78509 
78510   v = sqlite3GetVdbe(pParse);
78511   if( NEVER(v==0) ) return;
78512   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78513   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78514   assert( iDb>=0 );
78515 
78516 #ifndef SQLITE_OMIT_TRIGGER
78517   /* Drop any table triggers from the internal schema. */
78518   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78519     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
78520     assert( iTrigDb==iDb || iTrigDb==1 );
78521     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78522   }
78523 #endif
78524 
78525   /* Drop the table and index from the internal schema.  */
78526   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78527 
78528   /* Reload the table, index and permanent trigger schemas. */
78529   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
78530   if( !zWhere ) return;
78531   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
78532 
78533 #ifndef SQLITE_OMIT_TRIGGER
78534   /* Now, if the table is not stored in the temp database, reload any temp
78535   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
78536   */
78537   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78538     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
78539   }
78540 #endif
78541 }
78542 
78543 /*
78544 ** Parameter zName is the name of a table that is about to be altered
78545 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78546 ** If the table is a system table, this function leaves an error message
78547 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
78548 **
78549 ** Or, if zName is not a system table, zero is returned.
78550 */
78551 static int isSystemTable(Parse *pParse, const char *zName){
78552   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
78553     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
78554     return 1;
78555   }
78556   return 0;
78557 }
78558 
78559 /*
78560 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
78561 ** command.
78562 */
78563 SQLITE_PRIVATE void sqlite3AlterRenameTable(
78564   Parse *pParse,            /* Parser context. */
78565   SrcList *pSrc,            /* The table to rename. */
78566   Token *pName              /* The new table name. */
78567 ){
78568   int iDb;                  /* Database that contains the table */
78569   char *zDb;                /* Name of database iDb */
78570   Table *pTab;              /* Table being renamed */
78571   char *zName = 0;          /* NULL-terminated version of pName */
78572   sqlite3 *db = pParse->db; /* Database connection */
78573   int nTabName;             /* Number of UTF-8 characters in zTabName */
78574   const char *zTabName;     /* Original name of the table */
78575   Vdbe *v;
78576 #ifndef SQLITE_OMIT_TRIGGER
78577   char *zWhere = 0;         /* Where clause to locate temp triggers */
78578 #endif
78579   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78580   int savedDbFlags;         /* Saved value of db->flags */
78581 
78582   savedDbFlags = db->flags;
78583   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78584   assert( pSrc->nSrc==1 );
78585   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78586 
78587   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
78588   if( !pTab ) goto exit_rename_table;
78589   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78590   zDb = db->aDb[iDb].zName;
78591   db->flags |= SQLITE_PreferBuiltin;
78592 
78593   /* Get a NULL terminated version of the new table name. */
78594   zName = sqlite3NameFromToken(db, pName);
78595   if( !zName ) goto exit_rename_table;
78596 
78597   /* Check that a table or index named 'zName' does not already exist
78598   ** in database iDb. If so, this is an error.
78599   */
78600   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
78601     sqlite3ErrorMsg(pParse,
78602         "there is already another table or index with this name: %s", zName);
78603     goto exit_rename_table;
78604   }
78605 
78606   /* Make sure it is not a system table being altered, or a reserved name
78607   ** that the table is being renamed to.
78608   */
78609   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78610     goto exit_rename_table;
78611   }
78612   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
78613     exit_rename_table;
78614   }
78615 
78616 #ifndef SQLITE_OMIT_VIEW
78617   if( pTab->pSelect ){
78618     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78619     goto exit_rename_table;
78620   }
78621 #endif
78622 
78623 #ifndef SQLITE_OMIT_AUTHORIZATION
78624   /* Invoke the authorization callback. */
78625   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78626     goto exit_rename_table;
78627   }
78628 #endif
78629 
78630 #ifndef SQLITE_OMIT_VIRTUALTABLE
78631   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78632     goto exit_rename_table;
78633   }
78634   if( IsVirtual(pTab) ){
78635     pVTab = sqlite3GetVTable(db, pTab);
78636     if( pVTab->pVtab->pModule->xRename==0 ){
78637       pVTab = 0;
78638     }
78639   }
78640 #endif
78641 
78642   /* Begin a transaction and code the VerifyCookie for database iDb.
78643   ** Then modify the schema cookie (since the ALTER TABLE modifies the
78644   ** schema). Open a statement transaction if the table is a virtual
78645   ** table.
78646   */
78647   v = sqlite3GetVdbe(pParse);
78648   if( v==0 ){
78649     goto exit_rename_table;
78650   }
78651   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
78652   sqlite3ChangeCookie(pParse, iDb);
78653 
78654   /* If this is a virtual table, invoke the xRename() function if
78655   ** one is defined. The xRename() callback will modify the names
78656   ** of any resources used by the v-table implementation (including other
78657   ** SQLite tables) that are identified by the name of the virtual table.
78658   */
78659 #ifndef SQLITE_OMIT_VIRTUALTABLE
78660   if( pVTab ){
78661     int i = ++pParse->nMem;
78662     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78663     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78664     sqlite3MayAbort(pParse);
78665   }
78666 #endif
78667 
78668   /* figure out how many UTF-8 characters are in zName */
78669   zTabName = pTab->zName;
78670   nTabName = sqlite3Utf8CharLen(zTabName, -1);
78671 
78672 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78673   if( db->flags&SQLITE_ForeignKeys ){
78674     /* If foreign-key support is enabled, rewrite the CREATE TABLE
78675     ** statements corresponding to all child tables of foreign key constraints
78676     ** for which the renamed table is the parent table.  */
78677     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78678       sqlite3NestedParse(pParse,
78679           "UPDATE \"%w\".%s SET "
78680               "sql = sqlite_rename_parent(sql, %Q, %Q) "
78681               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78682       sqlite3DbFree(db, zWhere);
78683     }
78684   }
78685 #endif
78686 
78687   /* Modify the sqlite_master table to use the new table name. */
78688   sqlite3NestedParse(pParse,
78689       "UPDATE %Q.%s SET "
78690 #ifdef SQLITE_OMIT_TRIGGER
78691           "sql = sqlite_rename_table(sql, %Q), "
78692 #else
78693           "sql = CASE "
78694             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
78695             "ELSE sqlite_rename_table(sql, %Q) END, "
78696 #endif
78697           "tbl_name = %Q, "
78698           "name = CASE "
78699             "WHEN type='table' THEN %Q "
78700             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
78701              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
78702             "ELSE name END "
78703       "WHERE tbl_name=%Q COLLATE nocase AND "
78704           "(type='table' OR type='index' OR type='trigger');",
78705       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
78706 #ifndef SQLITE_OMIT_TRIGGER
78707       zName,
78708 #endif
78709       zName, nTabName, zTabName
78710   );
78711 
78712 #ifndef SQLITE_OMIT_AUTOINCREMENT
78713   /* If the sqlite_sequence table exists in this database, then update
78714   ** it with the new table name.
78715   */
78716   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
78717     sqlite3NestedParse(pParse,
78718         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
78719         zDb, zName, pTab->zName);
78720   }
78721 #endif
78722 
78723 #ifndef SQLITE_OMIT_TRIGGER
78724   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
78725   ** table. Don't do this if the table being ALTERed is itself located in
78726   ** the temp database.
78727   */
78728   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78729     sqlite3NestedParse(pParse,
78730         "UPDATE sqlite_temp_master SET "
78731             "sql = sqlite_rename_trigger(sql, %Q), "
78732             "tbl_name = %Q "
78733             "WHERE %s;", zName, zName, zWhere);
78734     sqlite3DbFree(db, zWhere);
78735   }
78736 #endif
78737 
78738 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78739   if( db->flags&SQLITE_ForeignKeys ){
78740     FKey *p;
78741     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78742       Table *pFrom = p->pFrom;
78743       if( pFrom!=pTab ){
78744         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
78745       }
78746     }
78747   }
78748 #endif
78749 
78750   /* Drop and reload the internal table schema. */
78751   reloadTableSchema(pParse, pTab, zName);
78752 
78753 exit_rename_table:
78754   sqlite3SrcListDelete(db, pSrc);
78755   sqlite3DbFree(db, zName);
78756   db->flags = savedDbFlags;
78757 }
78758 
78759 
78760 /*
78761 ** Generate code to make sure the file format number is at least minFormat.
78762 ** The generated code will increase the file format number if necessary.
78763 */
78764 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
78765   Vdbe *v;
78766   v = sqlite3GetVdbe(pParse);
78767   /* The VDBE should have been allocated before this routine is called.
78768   ** If that allocation failed, we would have quit before reaching this
78769   ** point */
78770   if( ALWAYS(v) ){
78771     int r1 = sqlite3GetTempReg(pParse);
78772     int r2 = sqlite3GetTempReg(pParse);
78773     int j1;
78774     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
78775     sqlite3VdbeUsesBtree(v, iDb);
78776     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
78777     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
78778     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
78779     sqlite3VdbeJumpHere(v, j1);
78780     sqlite3ReleaseTempReg(pParse, r1);
78781     sqlite3ReleaseTempReg(pParse, r2);
78782   }
78783 }
78784 
78785 /*
78786 ** This function is called after an "ALTER TABLE ... ADD" statement
78787 ** has been parsed. Argument pColDef contains the text of the new
78788 ** column definition.
78789 **
78790 ** The Table structure pParse->pNewTable was extended to include
78791 ** the new column during parsing.
78792 */
78793 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
78794   Table *pNew;              /* Copy of pParse->pNewTable */
78795   Table *pTab;              /* Table being altered */
78796   int iDb;                  /* Database number */
78797   const char *zDb;          /* Database name */
78798   const char *zTab;         /* Table name */
78799   char *zCol;               /* Null-terminated column definition */
78800   Column *pCol;             /* The new column */
78801   Expr *pDflt;              /* Default value for the new column */
78802   sqlite3 *db;              /* The database connection; */
78803 
78804   db = pParse->db;
78805   if( pParse->nErr || db->mallocFailed ) return;
78806   pNew = pParse->pNewTable;
78807   assert( pNew );
78808 
78809   assert( sqlite3BtreeHoldsAllMutexes(db) );
78810   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
78811   zDb = db->aDb[iDb].zName;
78812   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
78813   pCol = &pNew->aCol[pNew->nCol-1];
78814   pDflt = pCol->pDflt;
78815   pTab = sqlite3FindTable(db, zTab, zDb);
78816   assert( pTab );
78817 
78818 #ifndef SQLITE_OMIT_AUTHORIZATION
78819   /* Invoke the authorization callback. */
78820   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78821     return;
78822   }
78823 #endif
78824 
78825   /* If the default value for the new column was specified with a
78826   ** literal NULL, then set pDflt to 0. This simplifies checking
78827   ** for an SQL NULL default below.
78828   */
78829   if( pDflt && pDflt->op==TK_NULL ){
78830     pDflt = 0;
78831   }
78832 
78833   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
78834   ** If there is a NOT NULL constraint, then the default value for the
78835   ** column must not be NULL.
78836   */
78837   if( pCol->colFlags & COLFLAG_PRIMKEY ){
78838     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
78839     return;
78840   }
78841   if( pNew->pIndex ){
78842     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
78843     return;
78844   }
78845   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
78846     sqlite3ErrorMsg(pParse,
78847         "Cannot add a REFERENCES column with non-NULL default value");
78848     return;
78849   }
78850   if( pCol->notNull && !pDflt ){
78851     sqlite3ErrorMsg(pParse,
78852         "Cannot add a NOT NULL column with default value NULL");
78853     return;
78854   }
78855 
78856   /* Ensure the default expression is something that sqlite3ValueFromExpr()
78857   ** can handle (i.e. not CURRENT_TIME etc.)
78858   */
78859   if( pDflt ){
78860     sqlite3_value *pVal;
78861     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
78862       db->mallocFailed = 1;
78863       return;
78864     }
78865     if( !pVal ){
78866       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
78867       return;
78868     }
78869     sqlite3ValueFree(pVal);
78870   }
78871 
78872   /* Modify the CREATE TABLE statement. */
78873   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
78874   if( zCol ){
78875     char *zEnd = &zCol[pColDef->n-1];
78876     int savedDbFlags = db->flags;
78877     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
78878       *zEnd-- = '\0';
78879     }
78880     db->flags |= SQLITE_PreferBuiltin;
78881     sqlite3NestedParse(pParse,
78882         "UPDATE \"%w\".%s SET "
78883           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
78884         "WHERE type = 'table' AND name = %Q",
78885       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
78886       zTab
78887     );
78888     sqlite3DbFree(db, zCol);
78889     db->flags = savedDbFlags;
78890   }
78891 
78892   /* If the default value of the new column is NULL, then set the file
78893   ** format to 2. If the default value of the new column is not NULL,
78894   ** the file format becomes 3.
78895   */
78896   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
78897 
78898   /* Reload the schema of the modified table. */
78899   reloadTableSchema(pParse, pTab, pTab->zName);
78900 }
78901 
78902 /*
78903 ** This function is called by the parser after the table-name in
78904 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
78905 ** pSrc is the full-name of the table being altered.
78906 **
78907 ** This routine makes a (partial) copy of the Table structure
78908 ** for the table being altered and sets Parse.pNewTable to point
78909 ** to it. Routines called by the parser as the column definition
78910 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
78911 ** the copy. The copy of the Table structure is deleted by tokenize.c
78912 ** after parsing is finished.
78913 **
78914 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
78915 ** coding the "ALTER TABLE ... ADD" statement.
78916 */
78917 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
78918   Table *pNew;
78919   Table *pTab;
78920   Vdbe *v;
78921   int iDb;
78922   int i;
78923   int nAlloc;
78924   sqlite3 *db = pParse->db;
78925 
78926   /* Look up the table being altered. */
78927   assert( pParse->pNewTable==0 );
78928   assert( sqlite3BtreeHoldsAllMutexes(db) );
78929   if( db->mallocFailed ) goto exit_begin_add_column;
78930   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
78931   if( !pTab ) goto exit_begin_add_column;
78932 
78933 #ifndef SQLITE_OMIT_VIRTUALTABLE
78934   if( IsVirtual(pTab) ){
78935     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
78936     goto exit_begin_add_column;
78937   }
78938 #endif
78939 
78940   /* Make sure this is not an attempt to ALTER a view. */
78941   if( pTab->pSelect ){
78942     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
78943     goto exit_begin_add_column;
78944   }
78945   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78946     goto exit_begin_add_column;
78947   }
78948 
78949   assert( pTab->addColOffset>0 );
78950   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78951 
78952   /* Put a copy of the Table struct in Parse.pNewTable for the
78953   ** sqlite3AddColumn() function and friends to modify.  But modify
78954   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
78955   ** prefix, we insure that the name will not collide with an existing
78956   ** table because user table are not allowed to have the "sqlite_"
78957   ** prefix on their name.
78958   */
78959   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
78960   if( !pNew ) goto exit_begin_add_column;
78961   pParse->pNewTable = pNew;
78962   pNew->nRef = 1;
78963   pNew->nCol = pTab->nCol;
78964   assert( pNew->nCol>0 );
78965   nAlloc = (((pNew->nCol-1)/8)*8)+8;
78966   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
78967   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
78968   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
78969   if( !pNew->aCol || !pNew->zName ){
78970     db->mallocFailed = 1;
78971     goto exit_begin_add_column;
78972   }
78973   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
78974   for(i=0; i<pNew->nCol; i++){
78975     Column *pCol = &pNew->aCol[i];
78976     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
78977     pCol->zColl = 0;
78978     pCol->zType = 0;
78979     pCol->pDflt = 0;
78980     pCol->zDflt = 0;
78981   }
78982   pNew->pSchema = db->aDb[iDb].pSchema;
78983   pNew->addColOffset = pTab->addColOffset;
78984   pNew->nRef = 1;
78985 
78986   /* Begin a transaction and increment the schema cookie.  */
78987   sqlite3BeginWriteOperation(pParse, 0, iDb);
78988   v = sqlite3GetVdbe(pParse);
78989   if( !v ) goto exit_begin_add_column;
78990   sqlite3ChangeCookie(pParse, iDb);
78991 
78992 exit_begin_add_column:
78993   sqlite3SrcListDelete(db, pSrc);
78994   return;
78995 }
78996 #endif  /* SQLITE_ALTER_TABLE */
78997 
78998 /************** End of alter.c ***********************************************/
78999 /************** Begin file analyze.c *****************************************/
79000 /*
79001 ** 2005 July 8
79002 **
79003 ** The author disclaims copyright to this source code.  In place of
79004 ** a legal notice, here is a blessing:
79005 **
79006 **    May you do good and not evil.
79007 **    May you find forgiveness for yourself and forgive others.
79008 **    May you share freely, never taking more than you give.
79009 **
79010 *************************************************************************
79011 ** This file contains code associated with the ANALYZE command.
79012 **
79013 ** The ANALYZE command gather statistics about the content of tables
79014 ** and indices.  These statistics are made available to the query planner
79015 ** to help it make better decisions about how to perform queries.
79016 **
79017 ** The following system tables are or have been supported:
79018 **
79019 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
79020 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
79021 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
79022 **
79023 ** Additional tables might be added in future releases of SQLite.
79024 ** The sqlite_stat2 table is not created or used unless the SQLite version
79025 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
79026 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
79027 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
79028 ** created and used by SQLite versions 3.7.9 and later and with
79029 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
79030 ** is a superset of sqlite_stat2.
79031 **
79032 ** Format of sqlite_stat1:
79033 **
79034 ** There is normally one row per index, with the index identified by the
79035 ** name in the idx column.  The tbl column is the name of the table to
79036 ** which the index belongs.  In each such row, the stat column will be
79037 ** a string consisting of a list of integers.  The first integer in this
79038 ** list is the number of rows in the index and in the table.  The second
79039 ** integer is the average number of rows in the index that have the same
79040 ** value in the first column of the index.  The third integer is the average
79041 ** number of rows in the index that have the same value for the first two
79042 ** columns.  The N-th integer (for N>1) is the average number of rows in
79043 ** the index which have the same value for the first N-1 columns.  For
79044 ** a K-column index, there will be K+1 integers in the stat column.  If
79045 ** the index is unique, then the last integer will be 1.
79046 **
79047 ** The list of integers in the stat column can optionally be followed
79048 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
79049 ** must be separated from the last integer by a single space.  If the
79050 ** "unordered" keyword is present, then the query planner assumes that
79051 ** the index is unordered and will not use the index for a range query.
79052 **
79053 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
79054 ** column contains a single integer which is the (estimated) number of
79055 ** rows in the table identified by sqlite_stat1.tbl.
79056 **
79057 ** Format of sqlite_stat2:
79058 **
79059 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
79060 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
79061 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
79062 ** about the distribution of keys within an index.  The index is identified by
79063 ** the "idx" column and the "tbl" column is the name of the table to which
79064 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
79065 ** table for each index.
79066 **
79067 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
79068 ** inclusive are samples of the left-most key value in the index taken at
79069 ** evenly spaced points along the index.  Let the number of samples be S
79070 ** (10 in the standard build) and let C be the number of rows in the index.
79071 ** Then the sampled rows are given by:
79072 **
79073 **     rownumber = (i*C*2 + C)/(S*2)
79074 **
79075 ** For i between 0 and S-1.  Conceptually, the index space is divided into
79076 ** S uniform buckets and the samples are the middle row from each bucket.
79077 **
79078 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
79079 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
79080 ** writes the sqlite_stat2 table.  This version of SQLite only supports
79081 ** sqlite_stat3.
79082 **
79083 ** Format for sqlite_stat3:
79084 **
79085 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
79086 ** used to avoid compatibility problems.
79087 **
79088 ** The format of the sqlite_stat3 table is similar to the format of
79089 ** the sqlite_stat2 table.  There are multiple entries for each index.
79090 ** The idx column names the index and the tbl column is the table of the
79091 ** index.  If the idx and tbl columns are the same, then the sample is
79092 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
79093 ** the left-most column of the index.  The nEq column is the approximate
79094 ** number of entires in the index whose left-most column exactly matches
79095 ** the sample.  nLt is the approximate number of entires whose left-most
79096 ** column is less than the sample.  The nDLt column is the approximate
79097 ** number of distinct left-most entries in the index that are less than
79098 ** the sample.
79099 **
79100 ** Future versions of SQLite might change to store a string containing
79101 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
79102 ** integer will be the number of prior index entires that are distinct in
79103 ** the left-most column.  The second integer will be the number of prior index
79104 ** entries that are distinct in the first two columns.  The third integer
79105 ** will be the number of prior index entries that are distinct in the first
79106 ** three columns.  And so forth.  With that extension, the nDLt field is
79107 ** similar in function to the sqlite_stat1.stat field.
79108 **
79109 ** There can be an arbitrary number of sqlite_stat3 entries per index.
79110 ** The ANALYZE command will typically generate sqlite_stat3 tables
79111 ** that contain between 10 and 40 samples which are distributed across
79112 ** the key space, though not uniformly, and which include samples with
79113 ** largest possible nEq values.
79114 */
79115 #ifndef SQLITE_OMIT_ANALYZE
79116 
79117 /*
79118 ** This routine generates code that opens the sqlite_stat1 table for
79119 ** writing with cursor iStatCur. If the library was built with the
79120 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
79121 ** opened for writing using cursor (iStatCur+1)
79122 **
79123 ** If the sqlite_stat1 tables does not previously exist, it is created.
79124 ** Similarly, if the sqlite_stat3 table does not exist and the library
79125 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
79126 **
79127 ** Argument zWhere may be a pointer to a buffer containing a table name,
79128 ** or it may be a NULL pointer. If it is not NULL, then all entries in
79129 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
79130 ** with the named table are deleted. If zWhere==0, then code is generated
79131 ** to delete all stat table entries.
79132 */
79133 static void openStatTable(
79134   Parse *pParse,          /* Parsing context */
79135   int iDb,                /* The database we are looking in */
79136   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
79137   const char *zWhere,     /* Delete entries for this table or index */
79138   const char *zWhereType  /* Either "tbl" or "idx" */
79139 ){
79140   static const struct {
79141     const char *zName;
79142     const char *zCols;
79143   } aTable[] = {
79144     { "sqlite_stat1", "tbl,idx,stat" },
79145 #ifdef SQLITE_ENABLE_STAT3
79146     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
79147 #endif
79148   };
79149 
79150   int aRoot[] = {0, 0};
79151   u8 aCreateTbl[] = {0, 0};
79152 
79153   int i;
79154   sqlite3 *db = pParse->db;
79155   Db *pDb;
79156   Vdbe *v = sqlite3GetVdbe(pParse);
79157   if( v==0 ) return;
79158   assert( sqlite3BtreeHoldsAllMutexes(db) );
79159   assert( sqlite3VdbeDb(v)==db );
79160   pDb = &db->aDb[iDb];
79161 
79162   /* Create new statistic tables if they do not exist, or clear them
79163   ** if they do already exist.
79164   */
79165   for(i=0; i<ArraySize(aTable); i++){
79166     const char *zTab = aTable[i].zName;
79167     Table *pStat;
79168     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
79169       /* The sqlite_stat[12] table does not exist. Create it. Note that a
79170       ** side-effect of the CREATE TABLE statement is to leave the rootpage
79171       ** of the new table in register pParse->regRoot. This is important
79172       ** because the OpenWrite opcode below will be needing it. */
79173       sqlite3NestedParse(pParse,
79174           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
79175       );
79176       aRoot[i] = pParse->regRoot;
79177       aCreateTbl[i] = OPFLAG_P2ISREG;
79178     }else{
79179       /* The table already exists. If zWhere is not NULL, delete all entries
79180       ** associated with the table zWhere. If zWhere is NULL, delete the
79181       ** entire contents of the table. */
79182       aRoot[i] = pStat->tnum;
79183       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
79184       if( zWhere ){
79185         sqlite3NestedParse(pParse,
79186            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
79187         );
79188       }else{
79189         /* The sqlite_stat[12] table already exists.  Delete all rows. */
79190         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
79191       }
79192     }
79193   }
79194 
79195   /* Open the sqlite_stat[13] tables for writing. */
79196   for(i=0; i<ArraySize(aTable); i++){
79197     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
79198     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
79199     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
79200   }
79201 }
79202 
79203 /*
79204 ** Recommended number of samples for sqlite_stat3
79205 */
79206 #ifndef SQLITE_STAT3_SAMPLES
79207 # define SQLITE_STAT3_SAMPLES 24
79208 #endif
79209 
79210 /*
79211 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79212 ** share an instance of the following structure to hold their state
79213 ** information.
79214 */
79215 typedef struct Stat3Accum Stat3Accum;
79216 struct Stat3Accum {
79217   tRowcnt nRow;             /* Number of rows in the entire table */
79218   tRowcnt nPSample;         /* How often to do a periodic sample */
79219   int iMin;                 /* Index of entry with minimum nEq and hash */
79220   int mxSample;             /* Maximum number of samples to accumulate */
79221   int nSample;              /* Current number of samples */
79222   u32 iPrn;                 /* Pseudo-random number used for sampling */
79223   struct Stat3Sample {
79224     i64 iRowid;                /* Rowid in main table of the key */
79225     tRowcnt nEq;               /* sqlite_stat3.nEq */
79226     tRowcnt nLt;               /* sqlite_stat3.nLt */
79227     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
79228     u8 isPSample;              /* True if a periodic sample */
79229     u32 iHash;                 /* Tiebreaker hash */
79230   } *a;                     /* An array of samples */
79231 };
79232 
79233 #ifdef SQLITE_ENABLE_STAT3
79234 /*
79235 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79236 ** are the number of rows in the table or index (C) and the number of samples
79237 ** to accumulate (S).
79238 **
79239 ** This routine allocates the Stat3Accum object.
79240 **
79241 ** The return value is the Stat3Accum object (P).
79242 */
79243 static void stat3Init(
79244   sqlite3_context *context,
79245   int argc,
79246   sqlite3_value **argv
79247 ){
79248   Stat3Accum *p;
79249   tRowcnt nRow;
79250   int mxSample;
79251   int n;
79252 
79253   UNUSED_PARAMETER(argc);
79254   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
79255   mxSample = sqlite3_value_int(argv[1]);
79256   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79257   p = sqlite3MallocZero( n );
79258   if( p==0 ){
79259     sqlite3_result_error_nomem(context);
79260     return;
79261   }
79262   p->a = (struct Stat3Sample*)&p[1];
79263   p->nRow = nRow;
79264   p->mxSample = mxSample;
79265   p->nPSample = p->nRow/(mxSample/3+1) + 1;
79266   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
79267   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
79268 }
79269 static const FuncDef stat3InitFuncdef = {
79270   2,                /* nArg */
79271   SQLITE_UTF8,      /* iPrefEnc */
79272   0,                /* flags */
79273   0,                /* pUserData */
79274   0,                /* pNext */
79275   stat3Init,        /* xFunc */
79276   0,                /* xStep */
79277   0,                /* xFinalize */
79278   "stat3_init",     /* zName */
79279   0,                /* pHash */
79280   0                 /* pDestructor */
79281 };
79282 
79283 
79284 /*
79285 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79286 ** arguments describe a single key instance.  This routine makes the
79287 ** decision about whether or not to retain this key for the sqlite_stat3
79288 ** table.
79289 **
79290 ** The return value is NULL.
79291 */
79292 static void stat3Push(
79293   sqlite3_context *context,
79294   int argc,
79295   sqlite3_value **argv
79296 ){
79297   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
79298   tRowcnt nEq = sqlite3_value_int64(argv[0]);
79299   tRowcnt nLt = sqlite3_value_int64(argv[1]);
79300   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
79301   i64 rowid = sqlite3_value_int64(argv[3]);
79302   u8 isPSample = 0;
79303   u8 doInsert = 0;
79304   int iMin = p->iMin;
79305   struct Stat3Sample *pSample;
79306   int i;
79307   u32 h;
79308 
79309   UNUSED_PARAMETER(context);
79310   UNUSED_PARAMETER(argc);
79311   if( nEq==0 ) return;
79312   h = p->iPrn = p->iPrn*1103515245 + 12345;
79313   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79314     doInsert = isPSample = 1;
79315   }else if( p->nSample<p->mxSample ){
79316     doInsert = 1;
79317   }else{
79318     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79319       doInsert = 1;
79320     }
79321   }
79322   if( !doInsert ) return;
79323   if( p->nSample==p->mxSample ){
79324     assert( p->nSample - iMin - 1 >= 0 );
79325     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79326     pSample = &p->a[p->nSample-1];
79327   }else{
79328     pSample = &p->a[p->nSample++];
79329   }
79330   pSample->iRowid = rowid;
79331   pSample->nEq = nEq;
79332   pSample->nLt = nLt;
79333   pSample->nDLt = nDLt;
79334   pSample->iHash = h;
79335   pSample->isPSample = isPSample;
79336 
79337   /* Find the new minimum */
79338   if( p->nSample==p->mxSample ){
79339     pSample = p->a;
79340     i = 0;
79341     while( pSample->isPSample ){
79342       i++;
79343       pSample++;
79344       assert( i<p->nSample );
79345     }
79346     nEq = pSample->nEq;
79347     h = pSample->iHash;
79348     iMin = i;
79349     for(i++, pSample++; i<p->nSample; i++, pSample++){
79350       if( pSample->isPSample ) continue;
79351       if( pSample->nEq<nEq
79352        || (pSample->nEq==nEq && pSample->iHash<h)
79353       ){
79354         iMin = i;
79355         nEq = pSample->nEq;
79356         h = pSample->iHash;
79357       }
79358     }
79359     p->iMin = iMin;
79360   }
79361 }
79362 static const FuncDef stat3PushFuncdef = {
79363   5,                /* nArg */
79364   SQLITE_UTF8,      /* iPrefEnc */
79365   0,                /* flags */
79366   0,                /* pUserData */
79367   0,                /* pNext */
79368   stat3Push,        /* xFunc */
79369   0,                /* xStep */
79370   0,                /* xFinalize */
79371   "stat3_push",     /* zName */
79372   0,                /* pHash */
79373   0                 /* pDestructor */
79374 };
79375 
79376 /*
79377 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79378 ** used to query the results.  Content is returned for the Nth sqlite_stat3
79379 ** row where N is between 0 and S-1 and S is the number of samples.  The
79380 ** value returned depends on the number of arguments.
79381 **
79382 **   argc==2    result:  rowid
79383 **   argc==3    result:  nEq
79384 **   argc==4    result:  nLt
79385 **   argc==5    result:  nDLt
79386 */
79387 static void stat3Get(
79388   sqlite3_context *context,
79389   int argc,
79390   sqlite3_value **argv
79391 ){
79392   int n = sqlite3_value_int(argv[1]);
79393   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
79394 
79395   assert( p!=0 );
79396   if( p->nSample<=n ) return;
79397   switch( argc ){
79398     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
79399     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
79400     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
79401     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
79402   }
79403 }
79404 static const FuncDef stat3GetFuncdef = {
79405   -1,               /* nArg */
79406   SQLITE_UTF8,      /* iPrefEnc */
79407   0,                /* flags */
79408   0,                /* pUserData */
79409   0,                /* pNext */
79410   stat3Get,         /* xFunc */
79411   0,                /* xStep */
79412   0,                /* xFinalize */
79413   "stat3_get",     /* zName */
79414   0,                /* pHash */
79415   0                 /* pDestructor */
79416 };
79417 #endif /* SQLITE_ENABLE_STAT3 */
79418 
79419 
79420 
79421 
79422 /*
79423 ** Generate code to do an analysis of all indices associated with
79424 ** a single table.
79425 */
79426 static void analyzeOneTable(
79427   Parse *pParse,   /* Parser context */
79428   Table *pTab,     /* Table whose indices are to be analyzed */
79429   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79430   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
79431   int iMem         /* Available memory locations begin here */
79432 ){
79433   sqlite3 *db = pParse->db;    /* Database handle */
79434   Index *pIdx;                 /* An index to being analyzed */
79435   int iIdxCur;                 /* Cursor open on index being analyzed */
79436   Vdbe *v;                     /* The virtual machine being built up */
79437   int i;                       /* Loop counter */
79438   int topOfLoop;               /* The top of the loop */
79439   int endOfLoop;               /* The end of the loop */
79440   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79441   int iDb;                     /* Index of database containing pTab */
79442   int regTabname = iMem++;     /* Register containing table name */
79443   int regIdxname = iMem++;     /* Register containing index name */
79444   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
79445 #ifdef SQLITE_ENABLE_STAT3
79446   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79447   int regNumLt = iMem++;       /* Number of keys less than regSample */
79448   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79449   int regSample = iMem++;      /* The next sample value */
79450   int regRowid = regSample;    /* Rowid of a sample */
79451   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79452   int regLoop = iMem++;        /* Loop counter */
79453   int regCount = iMem++;       /* Number of rows in the table or index */
79454   int regTemp1 = iMem++;       /* Intermediate register */
79455   int regTemp2 = iMem++;       /* Intermediate register */
79456   int once = 1;                /* One-time initialization */
79457   int shortJump = 0;           /* Instruction address */
79458   int iTabCur = pParse->nTab++; /* Table cursor */
79459 #endif
79460   int regCol = iMem++;         /* Content of a column in analyzed table */
79461   int regRec = iMem++;         /* Register holding completed record */
79462   int regTemp = iMem++;        /* Temporary use register */
79463   int regNewRowid = iMem++;    /* Rowid for the inserted record */
79464 
79465 
79466   v = sqlite3GetVdbe(pParse);
79467   if( v==0 || NEVER(pTab==0) ){
79468     return;
79469   }
79470   if( pTab->tnum==0 ){
79471     /* Do not gather statistics on views or virtual tables */
79472     return;
79473   }
79474   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
79475     /* Do not gather statistics on system tables */
79476     return;
79477   }
79478   assert( sqlite3BtreeHoldsAllMutexes(db) );
79479   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79480   assert( iDb>=0 );
79481   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79482 #ifndef SQLITE_OMIT_AUTHORIZATION
79483   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
79484       db->aDb[iDb].zName ) ){
79485     return;
79486   }
79487 #endif
79488 
79489   /* Establish a read-lock on the table at the shared-cache level. */
79490   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79491 
79492   iIdxCur = pParse->nTab++;
79493   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79494   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79495     int nCol;
79496     KeyInfo *pKey;
79497     int addrIfNot = 0;           /* address of OP_IfNot */
79498     int *aChngAddr;              /* Array of jump instruction addresses */
79499 
79500     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79501     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79502     nCol = pIdx->nColumn;
79503     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
79504     if( aChngAddr==0 ) continue;
79505     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79506     if( iMem+1+(nCol*2)>pParse->nMem ){
79507       pParse->nMem = iMem+1+(nCol*2);
79508     }
79509 
79510     /* Open a cursor to the index to be analyzed. */
79511     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
79512     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79513         (char *)pKey, P4_KEYINFO_HANDOFF);
79514     VdbeComment((v, "%s", pIdx->zName));
79515 
79516     /* Populate the register containing the index name. */
79517     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79518 
79519 #ifdef SQLITE_ENABLE_STAT3
79520     if( once ){
79521       once = 0;
79522       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79523     }
79524     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79525     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
79526     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79527     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79528     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79529     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
79530     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79531                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
79532     sqlite3VdbeChangeP5(v, 2);
79533 #endif /* SQLITE_ENABLE_STAT3 */
79534 
79535     /* The block of memory cells initialized here is used as follows.
79536     **
79537     **    iMem:
79538     **        The total number of rows in the table.
79539     **
79540     **    iMem+1 .. iMem+nCol:
79541     **        Number of distinct entries in index considering the
79542     **        left-most N columns only, where N is between 1 and nCol,
79543     **        inclusive.
79544     **
79545     **    iMem+nCol+1 .. Mem+2*nCol:
79546     **        Previous value of indexed columns, from left to right.
79547     **
79548     ** Cells iMem through iMem+nCol are initialized to 0. The others are
79549     ** initialized to contain an SQL NULL.
79550     */
79551     for(i=0; i<=nCol; i++){
79552       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79553     }
79554     for(i=0; i<nCol; i++){
79555       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79556     }
79557 
79558     /* Start the analysis loop. This loop runs through all the entries in
79559     ** the index b-tree.  */
79560     endOfLoop = sqlite3VdbeMakeLabel(v);
79561     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79562     topOfLoop = sqlite3VdbeCurrentAddr(v);
79563     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79564 
79565     for(i=0; i<nCol; i++){
79566       CollSeq *pColl;
79567       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79568       if( i==0 ){
79569         /* Always record the very first row */
79570         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
79571       }
79572       assert( pIdx->azColl!=0 );
79573       assert( pIdx->azColl[i]!=0 );
79574       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
79575       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79576                                       (char*)pColl, P4_COLLSEQ);
79577       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
79578       VdbeComment((v, "jump if column %d changed", i));
79579 #ifdef SQLITE_ENABLE_STAT3
79580       if( i==0 ){
79581         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79582         VdbeComment((v, "incr repeat count"));
79583       }
79584 #endif
79585     }
79586     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79587     for(i=0; i<nCol; i++){
79588       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79589       if( i==0 ){
79590         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79591 #ifdef SQLITE_ENABLE_STAT3
79592         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79593                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
79594         sqlite3VdbeChangeP5(v, 5);
79595         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79596         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79597         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79598         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79599 #endif
79600       }
79601       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79602       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79603     }
79604     sqlite3DbFree(db, aChngAddr);
79605 
79606     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79607     sqlite3VdbeResolveLabel(v, endOfLoop);
79608 
79609     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79610     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79611 #ifdef SQLITE_ENABLE_STAT3
79612     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79613                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
79614     sqlite3VdbeChangeP5(v, 5);
79615     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79616     shortJump =
79617     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79618     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79619                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79620     sqlite3VdbeChangeP5(v, 2);
79621     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
79622     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79623     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79624     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79625     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79626                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79627     sqlite3VdbeChangeP5(v, 3);
79628     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79629                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79630     sqlite3VdbeChangeP5(v, 4);
79631     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79632                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
79633     sqlite3VdbeChangeP5(v, 5);
79634     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79635     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79636     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79637     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79638     sqlite3VdbeJumpHere(v, shortJump+2);
79639 #endif
79640 
79641     /* Store the results in sqlite_stat1.
79642     **
79643     ** The result is a single row of the sqlite_stat1 table.  The first
79644     ** two columns are the names of the table and index.  The third column
79645     ** is a string composed of a list of integer statistics about the
79646     ** index.  The first integer in the list is the total number of entries
79647     ** in the index.  There is one additional integer in the list for each
79648     ** column of the table.  This additional integer is a guess of how many
79649     ** rows of the table the index will select.  If D is the count of distinct
79650     ** values and K is the total number of rows, then the integer is computed
79651     ** as:
79652     **
79653     **        I = (K+D-1)/D
79654     **
79655     ** If K==0 then no entry is made into the sqlite_stat1 table.
79656     ** If K>0 then it is always the case the D>0 so division by zero
79657     ** is never possible.
79658     */
79659     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79660     if( jZeroRows<0 ){
79661       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
79662     }
79663     for(i=0; i<nCol; i++){
79664       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79665       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79666       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79667       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79668       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79669       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
79670       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79671     }
79672     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79673     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79674     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79675     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79676   }
79677 
79678   /* If the table has no indices, create a single sqlite_stat1 entry
79679   ** containing NULL as the index name and the row count as the content.
79680   */
79681   if( pTab->pIndex==0 ){
79682     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79683     VdbeComment((v, "%s", pTab->zName));
79684     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79685     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79686     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
79687   }else{
79688     sqlite3VdbeJumpHere(v, jZeroRows);
79689     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
79690   }
79691   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79692   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79693   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79694   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79695   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79696   if( pParse->nMem<regRec ) pParse->nMem = regRec;
79697   sqlite3VdbeJumpHere(v, jZeroRows);
79698 }
79699 
79700 
79701 /*
79702 ** Generate code that will cause the most recent index analysis to
79703 ** be loaded into internal hash tables where is can be used.
79704 */
79705 static void loadAnalysis(Parse *pParse, int iDb){
79706   Vdbe *v = sqlite3GetVdbe(pParse);
79707   if( v ){
79708     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79709   }
79710 }
79711 
79712 /*
79713 ** Generate code that will do an analysis of an entire database
79714 */
79715 static void analyzeDatabase(Parse *pParse, int iDb){
79716   sqlite3 *db = pParse->db;
79717   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79718   HashElem *k;
79719   int iStatCur;
79720   int iMem;
79721 
79722   sqlite3BeginWriteOperation(pParse, 0, iDb);
79723   iStatCur = pParse->nTab;
79724   pParse->nTab += 3;
79725   openStatTable(pParse, iDb, iStatCur, 0, 0);
79726   iMem = pParse->nMem+1;
79727   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79728   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
79729     Table *pTab = (Table*)sqliteHashData(k);
79730     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
79731   }
79732   loadAnalysis(pParse, iDb);
79733 }
79734 
79735 /*
79736 ** Generate code that will do an analysis of a single table in
79737 ** a database.  If pOnlyIdx is not NULL then it is a single index
79738 ** in pTab that should be analyzed.
79739 */
79740 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
79741   int iDb;
79742   int iStatCur;
79743 
79744   assert( pTab!=0 );
79745   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79746   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79747   sqlite3BeginWriteOperation(pParse, 0, iDb);
79748   iStatCur = pParse->nTab;
79749   pParse->nTab += 3;
79750   if( pOnlyIdx ){
79751     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
79752   }else{
79753     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
79754   }
79755   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
79756   loadAnalysis(pParse, iDb);
79757 }
79758 
79759 /*
79760 ** Generate code for the ANALYZE command.  The parser calls this routine
79761 ** when it recognizes an ANALYZE command.
79762 **
79763 **        ANALYZE                            -- 1
79764 **        ANALYZE  <database>                -- 2
79765 **        ANALYZE  ?<database>.?<tablename>  -- 3
79766 **
79767 ** Form 1 causes all indices in all attached databases to be analyzed.
79768 ** Form 2 analyzes all indices the single database named.
79769 ** Form 3 analyzes all indices associated with the named table.
79770 */
79771 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
79772   sqlite3 *db = pParse->db;
79773   int iDb;
79774   int i;
79775   char *z, *zDb;
79776   Table *pTab;
79777   Index *pIdx;
79778   Token *pTableName;
79779 
79780   /* Read the database schema. If an error occurs, leave an error message
79781   ** and code in pParse and return NULL. */
79782   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79783   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79784     return;
79785   }
79786 
79787   assert( pName2!=0 || pName1==0 );
79788   if( pName1==0 ){
79789     /* Form 1:  Analyze everything */
79790     for(i=0; i<db->nDb; i++){
79791       if( i==1 ) continue;  /* Do not analyze the TEMP database */
79792       analyzeDatabase(pParse, i);
79793     }
79794   }else if( pName2->n==0 ){
79795     /* Form 2:  Analyze the database or table named */
79796     iDb = sqlite3FindDb(db, pName1);
79797     if( iDb>=0 ){
79798       analyzeDatabase(pParse, iDb);
79799     }else{
79800       z = sqlite3NameFromToken(db, pName1);
79801       if( z ){
79802         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
79803           analyzeTable(pParse, pIdx->pTable, pIdx);
79804         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
79805           analyzeTable(pParse, pTab, 0);
79806         }
79807         sqlite3DbFree(db, z);
79808       }
79809     }
79810   }else{
79811     /* Form 3: Analyze the fully qualified table name */
79812     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
79813     if( iDb>=0 ){
79814       zDb = db->aDb[iDb].zName;
79815       z = sqlite3NameFromToken(db, pTableName);
79816       if( z ){
79817         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
79818           analyzeTable(pParse, pIdx->pTable, pIdx);
79819         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
79820           analyzeTable(pParse, pTab, 0);
79821         }
79822         sqlite3DbFree(db, z);
79823       }
79824     }
79825   }
79826 }
79827 
79828 /*
79829 ** Used to pass information from the analyzer reader through to the
79830 ** callback routine.
79831 */
79832 typedef struct analysisInfo analysisInfo;
79833 struct analysisInfo {
79834   sqlite3 *db;
79835   const char *zDatabase;
79836 };
79837 
79838 /*
79839 ** This callback is invoked once for each index when reading the
79840 ** sqlite_stat1 table.
79841 **
79842 **     argv[0] = name of the table
79843 **     argv[1] = name of the index (might be NULL)
79844 **     argv[2] = results of analysis - on integer for each column
79845 **
79846 ** Entries for which argv[1]==NULL simply record the number of rows in
79847 ** the table.
79848 */
79849 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
79850   analysisInfo *pInfo = (analysisInfo*)pData;
79851   Index *pIndex;
79852   Table *pTable;
79853   int i, c, n;
79854   tRowcnt v;
79855   const char *z;
79856 
79857   assert( argc==3 );
79858   UNUSED_PARAMETER2(NotUsed, argc);
79859 
79860   if( argv==0 || argv[0]==0 || argv[2]==0 ){
79861     return 0;
79862   }
79863   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
79864   if( pTable==0 ){
79865     return 0;
79866   }
79867   if( argv[1] ){
79868     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
79869   }else{
79870     pIndex = 0;
79871   }
79872   n = pIndex ? pIndex->nColumn : 0;
79873   z = argv[2];
79874   for(i=0; *z && i<=n; i++){
79875     v = 0;
79876     while( (c=z[0])>='0' && c<='9' ){
79877       v = v*10 + c - '0';
79878       z++;
79879     }
79880     if( i==0 ) pTable->nRowEst = v;
79881     if( pIndex==0 ) break;
79882     pIndex->aiRowEst[i] = v;
79883     if( *z==' ' ) z++;
79884     if( strcmp(z, "unordered")==0 ){
79885       pIndex->bUnordered = 1;
79886       break;
79887     }
79888   }
79889   return 0;
79890 }
79891 
79892 /*
79893 ** If the Index.aSample variable is not NULL, delete the aSample[] array
79894 ** and its contents.
79895 */
79896 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
79897 #ifdef SQLITE_ENABLE_STAT3
79898   if( pIdx->aSample ){
79899     int j;
79900     for(j=0; j<pIdx->nSample; j++){
79901       IndexSample *p = &pIdx->aSample[j];
79902       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
79903         sqlite3DbFree(db, p->u.z);
79904       }
79905     }
79906     sqlite3DbFree(db, pIdx->aSample);
79907   }
79908   if( db && db->pnBytesFreed==0 ){
79909     pIdx->nSample = 0;
79910     pIdx->aSample = 0;
79911   }
79912 #else
79913   UNUSED_PARAMETER(db);
79914   UNUSED_PARAMETER(pIdx);
79915 #endif
79916 }
79917 
79918 #ifdef SQLITE_ENABLE_STAT3
79919 /*
79920 ** Load content from the sqlite_stat3 table into the Index.aSample[]
79921 ** arrays of all indices.
79922 */
79923 static int loadStat3(sqlite3 *db, const char *zDb){
79924   int rc;                       /* Result codes from subroutines */
79925   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
79926   char *zSql;                   /* Text of the SQL statement */
79927   Index *pPrevIdx = 0;          /* Previous index in the loop */
79928   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
79929   int eType;                    /* Datatype of a sample */
79930   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
79931 
79932   assert( db->lookaside.bEnabled==0 );
79933   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
79934     return SQLITE_OK;
79935   }
79936 
79937   zSql = sqlite3MPrintf(db,
79938       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
79939       " GROUP BY idx", zDb);
79940   if( !zSql ){
79941     return SQLITE_NOMEM;
79942   }
79943   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79944   sqlite3DbFree(db, zSql);
79945   if( rc ) return rc;
79946 
79947   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79948     char *zIndex;   /* Index name */
79949     Index *pIdx;    /* Pointer to the index object */
79950     int nSample;    /* Number of samples */
79951 
79952     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79953     if( zIndex==0 ) continue;
79954     nSample = sqlite3_column_int(pStmt, 1);
79955     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79956     if( pIdx==0 ) continue;
79957     assert( pIdx->nSample==0 );
79958     pIdx->nSample = nSample;
79959     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
79960     pIdx->avgEq = pIdx->aiRowEst[1];
79961     if( pIdx->aSample==0 ){
79962       db->mallocFailed = 1;
79963       sqlite3_finalize(pStmt);
79964       return SQLITE_NOMEM;
79965     }
79966   }
79967   rc = sqlite3_finalize(pStmt);
79968   if( rc ) return rc;
79969 
79970   zSql = sqlite3MPrintf(db,
79971       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
79972   if( !zSql ){
79973     return SQLITE_NOMEM;
79974   }
79975   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
79976   sqlite3DbFree(db, zSql);
79977   if( rc ) return rc;
79978 
79979   while( sqlite3_step(pStmt)==SQLITE_ROW ){
79980     char *zIndex;   /* Index name */
79981     Index *pIdx;    /* Pointer to the index object */
79982     int i;          /* Loop counter */
79983     tRowcnt sumEq;  /* Sum of the nEq values */
79984 
79985     zIndex = (char *)sqlite3_column_text(pStmt, 0);
79986     if( zIndex==0 ) continue;
79987     pIdx = sqlite3FindIndex(db, zIndex, zDb);
79988     if( pIdx==0 ) continue;
79989     if( pIdx==pPrevIdx ){
79990       idx++;
79991     }else{
79992       pPrevIdx = pIdx;
79993       idx = 0;
79994     }
79995     assert( idx<pIdx->nSample );
79996     pSample = &pIdx->aSample[idx];
79997     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
79998     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
79999     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
80000     if( idx==pIdx->nSample-1 ){
80001       if( pSample->nDLt>0 ){
80002         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
80003         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
80004       }
80005       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
80006     }
80007     eType = sqlite3_column_type(pStmt, 4);
80008     pSample->eType = (u8)eType;
80009     switch( eType ){
80010       case SQLITE_INTEGER: {
80011         pSample->u.i = sqlite3_column_int64(pStmt, 4);
80012         break;
80013       }
80014       case SQLITE_FLOAT: {
80015         pSample->u.r = sqlite3_column_double(pStmt, 4);
80016         break;
80017       }
80018       case SQLITE_NULL: {
80019         break;
80020       }
80021       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
80022         const char *z = (const char *)(
80023               (eType==SQLITE_BLOB) ?
80024               sqlite3_column_blob(pStmt, 4):
80025               sqlite3_column_text(pStmt, 4)
80026            );
80027         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
80028         pSample->nByte = n;
80029         if( n < 1){
80030           pSample->u.z = 0;
80031         }else{
80032           pSample->u.z = sqlite3DbMallocRaw(db, n);
80033           if( pSample->u.z==0 ){
80034             db->mallocFailed = 1;
80035             sqlite3_finalize(pStmt);
80036             return SQLITE_NOMEM;
80037           }
80038           memcpy(pSample->u.z, z, n);
80039         }
80040       }
80041     }
80042   }
80043   return sqlite3_finalize(pStmt);
80044 }
80045 #endif /* SQLITE_ENABLE_STAT3 */
80046 
80047 /*
80048 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
80049 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
80050 ** arrays. The contents of sqlite_stat3 are used to populate the
80051 ** Index.aSample[] arrays.
80052 **
80053 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
80054 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
80055 ** during compilation and the sqlite_stat3 table is present, no data is
80056 ** read from it.
80057 **
80058 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
80059 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
80060 ** returned. However, in this case, data is read from the sqlite_stat1
80061 ** table (if it is present) before returning.
80062 **
80063 ** If an OOM error occurs, this function always sets db->mallocFailed.
80064 ** This means if the caller does not care about other errors, the return
80065 ** code may be ignored.
80066 */
80067 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
80068   analysisInfo sInfo;
80069   HashElem *i;
80070   char *zSql;
80071   int rc;
80072 
80073   assert( iDb>=0 && iDb<db->nDb );
80074   assert( db->aDb[iDb].pBt!=0 );
80075 
80076   /* Clear any prior statistics */
80077   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80078   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
80079     Index *pIdx = sqliteHashData(i);
80080     sqlite3DefaultRowEst(pIdx);
80081 #ifdef SQLITE_ENABLE_STAT3
80082     sqlite3DeleteIndexSamples(db, pIdx);
80083     pIdx->aSample = 0;
80084 #endif
80085   }
80086 
80087   /* Check to make sure the sqlite_stat1 table exists */
80088   sInfo.db = db;
80089   sInfo.zDatabase = db->aDb[iDb].zName;
80090   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
80091     return SQLITE_ERROR;
80092   }
80093 
80094   /* Load new statistics out of the sqlite_stat1 table */
80095   zSql = sqlite3MPrintf(db,
80096       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
80097   if( zSql==0 ){
80098     rc = SQLITE_NOMEM;
80099   }else{
80100     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
80101     sqlite3DbFree(db, zSql);
80102   }
80103 
80104 
80105   /* Load the statistics from the sqlite_stat3 table. */
80106 #ifdef SQLITE_ENABLE_STAT3
80107   if( rc==SQLITE_OK ){
80108     int lookasideEnabled = db->lookaside.bEnabled;
80109     db->lookaside.bEnabled = 0;
80110     rc = loadStat3(db, sInfo.zDatabase);
80111     db->lookaside.bEnabled = lookasideEnabled;
80112   }
80113 #endif
80114 
80115   if( rc==SQLITE_NOMEM ){
80116     db->mallocFailed = 1;
80117   }
80118   return rc;
80119 }
80120 
80121 
80122 #endif /* SQLITE_OMIT_ANALYZE */
80123 
80124 /************** End of analyze.c *********************************************/
80125 /************** Begin file attach.c ******************************************/
80126 /*
80127 ** 2003 April 6
80128 **
80129 ** The author disclaims copyright to this source code.  In place of
80130 ** a legal notice, here is a blessing:
80131 **
80132 **    May you do good and not evil.
80133 **    May you find forgiveness for yourself and forgive others.
80134 **    May you share freely, never taking more than you give.
80135 **
80136 *************************************************************************
80137 ** This file contains code used to implement the ATTACH and DETACH commands.
80138 */
80139 
80140 #ifndef SQLITE_OMIT_ATTACH
80141 /*
80142 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
80143 ** is slightly different from resolving a normal SQL expression, because simple
80144 ** identifiers are treated as strings, not possible column names or aliases.
80145 **
80146 ** i.e. if the parser sees:
80147 **
80148 **     ATTACH DATABASE abc AS def
80149 **
80150 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
80151 ** looking for columns of the same name.
80152 **
80153 ** This only applies to the root node of pExpr, so the statement:
80154 **
80155 **     ATTACH DATABASE abc||def AS 'db2'
80156 **
80157 ** will fail because neither abc or def can be resolved.
80158 */
80159 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
80160 {
80161   int rc = SQLITE_OK;
80162   if( pExpr ){
80163     if( pExpr->op!=TK_ID ){
80164       rc = sqlite3ResolveExprNames(pName, pExpr);
80165       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
80166         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
80167         return SQLITE_ERROR;
80168       }
80169     }else{
80170       pExpr->op = TK_STRING;
80171     }
80172   }
80173   return rc;
80174 }
80175 
80176 /*
80177 ** An SQL user-function registered to do the work of an ATTACH statement. The
80178 ** three arguments to the function come directly from an attach statement:
80179 **
80180 **     ATTACH DATABASE x AS y KEY z
80181 **
80182 **     SELECT sqlite_attach(x, y, z)
80183 **
80184 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
80185 ** third argument.
80186 */
80187 static void attachFunc(
80188   sqlite3_context *context,
80189   int NotUsed,
80190   sqlite3_value **argv
80191 ){
80192   int i;
80193   int rc = 0;
80194   sqlite3 *db = sqlite3_context_db_handle(context);
80195   const char *zName;
80196   const char *zFile;
80197   char *zPath = 0;
80198   char *zErr = 0;
80199   unsigned int flags;
80200   Db *aNew;
80201   char *zErrDyn = 0;
80202   sqlite3_vfs *pVfs;
80203 
80204   UNUSED_PARAMETER(NotUsed);
80205 
80206   zFile = (const char *)sqlite3_value_text(argv[0]);
80207   zName = (const char *)sqlite3_value_text(argv[1]);
80208   if( zFile==0 ) zFile = "";
80209   if( zName==0 ) zName = "";
80210 
80211   /* Check for the following errors:
80212   **
80213   **     * Too many attached databases,
80214   **     * Transaction currently open
80215   **     * Specified database name already being used.
80216   */
80217   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
80218     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
80219       db->aLimit[SQLITE_LIMIT_ATTACHED]
80220     );
80221     goto attach_error;
80222   }
80223   if( !db->autoCommit ){
80224     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
80225     goto attach_error;
80226   }
80227   for(i=0; i<db->nDb; i++){
80228     char *z = db->aDb[i].zName;
80229     assert( z && zName );
80230     if( sqlite3StrICmp(z, zName)==0 ){
80231       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
80232       goto attach_error;
80233     }
80234   }
80235 
80236   /* Allocate the new entry in the db->aDb[] array and initialize the schema
80237   ** hash tables.
80238   */
80239   if( db->aDb==db->aDbStatic ){
80240     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80241     if( aNew==0 ) return;
80242     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80243   }else{
80244     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80245     if( aNew==0 ) return;
80246   }
80247   db->aDb = aNew;
80248   aNew = &db->aDb[db->nDb];
80249   memset(aNew, 0, sizeof(*aNew));
80250 
80251   /* Open the database file. If the btree is successfully opened, use
80252   ** it to obtain the database schema. At this point the schema may
80253   ** or may not be initialized.
80254   */
80255   flags = db->openFlags;
80256   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80257   if( rc!=SQLITE_OK ){
80258     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
80259     sqlite3_result_error(context, zErr, -1);
80260     sqlite3_free(zErr);
80261     return;
80262   }
80263   assert( pVfs );
80264   flags |= SQLITE_OPEN_MAIN_DB;
80265   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80266   sqlite3_free( zPath );
80267   db->nDb++;
80268   if( rc==SQLITE_CONSTRAINT ){
80269     rc = SQLITE_ERROR;
80270     zErrDyn = sqlite3MPrintf(db, "database is already attached");
80271   }else if( rc==SQLITE_OK ){
80272     Pager *pPager;
80273     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
80274     if( !aNew->pSchema ){
80275       rc = SQLITE_NOMEM;
80276     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80277       zErrDyn = sqlite3MPrintf(db,
80278         "attached databases must use the same text encoding as main database");
80279       rc = SQLITE_ERROR;
80280     }
80281     pPager = sqlite3BtreePager(aNew->pBt);
80282     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
80283     sqlite3BtreeSecureDelete(aNew->pBt,
80284                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80285   }
80286   aNew->safety_level = 3;
80287   aNew->zName = sqlite3DbStrDup(db, zName);
80288   if( rc==SQLITE_OK && aNew->zName==0 ){
80289     rc = SQLITE_NOMEM;
80290   }
80291 
80292 
80293 #ifdef SQLITE_HAS_CODEC
80294   if( rc==SQLITE_OK ){
80295     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
80296     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
80297     int nKey;
80298     char *zKey;
80299     int t = sqlite3_value_type(argv[2]);
80300     switch( t ){
80301       case SQLITE_INTEGER:
80302       case SQLITE_FLOAT:
80303         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
80304         rc = SQLITE_ERROR;
80305         break;
80306 
80307       case SQLITE_TEXT:
80308       case SQLITE_BLOB:
80309         nKey = sqlite3_value_bytes(argv[2]);
80310         zKey = (char *)sqlite3_value_blob(argv[2]);
80311         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80312         break;
80313 
80314       case SQLITE_NULL:
80315         /* No key specified.  Use the key from the main database */
80316         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80317         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80318           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80319         }
80320         break;
80321     }
80322   }
80323 #endif
80324 
80325   /* If the file was opened successfully, read the schema for the new database.
80326   ** If this fails, or if opening the file failed, then close the file and
80327   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80328   ** we found it.
80329   */
80330   if( rc==SQLITE_OK ){
80331     sqlite3BtreeEnterAll(db);
80332     rc = sqlite3Init(db, &zErrDyn);
80333     sqlite3BtreeLeaveAll(db);
80334   }
80335   if( rc ){
80336     int iDb = db->nDb - 1;
80337     assert( iDb>=2 );
80338     if( db->aDb[iDb].pBt ){
80339       sqlite3BtreeClose(db->aDb[iDb].pBt);
80340       db->aDb[iDb].pBt = 0;
80341       db->aDb[iDb].pSchema = 0;
80342     }
80343     sqlite3ResetAllSchemasOfConnection(db);
80344     db->nDb = iDb;
80345     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
80346       db->mallocFailed = 1;
80347       sqlite3DbFree(db, zErrDyn);
80348       zErrDyn = sqlite3MPrintf(db, "out of memory");
80349     }else if( zErrDyn==0 ){
80350       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
80351     }
80352     goto attach_error;
80353   }
80354 
80355   return;
80356 
80357 attach_error:
80358   /* Return an error if we get here */
80359   if( zErrDyn ){
80360     sqlite3_result_error(context, zErrDyn, -1);
80361     sqlite3DbFree(db, zErrDyn);
80362   }
80363   if( rc ) sqlite3_result_error_code(context, rc);
80364 }
80365 
80366 /*
80367 ** An SQL user-function registered to do the work of an DETACH statement. The
80368 ** three arguments to the function come directly from a detach statement:
80369 **
80370 **     DETACH DATABASE x
80371 **
80372 **     SELECT sqlite_detach(x)
80373 */
80374 static void detachFunc(
80375   sqlite3_context *context,
80376   int NotUsed,
80377   sqlite3_value **argv
80378 ){
80379   const char *zName = (const char *)sqlite3_value_text(argv[0]);
80380   sqlite3 *db = sqlite3_context_db_handle(context);
80381   int i;
80382   Db *pDb = 0;
80383   char zErr[128];
80384 
80385   UNUSED_PARAMETER(NotUsed);
80386 
80387   if( zName==0 ) zName = "";
80388   for(i=0; i<db->nDb; i++){
80389     pDb = &db->aDb[i];
80390     if( pDb->pBt==0 ) continue;
80391     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
80392   }
80393 
80394   if( i>=db->nDb ){
80395     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80396     goto detach_error;
80397   }
80398   if( i<2 ){
80399     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80400     goto detach_error;
80401   }
80402   if( !db->autoCommit ){
80403     sqlite3_snprintf(sizeof(zErr), zErr,
80404                      "cannot DETACH database within transaction");
80405     goto detach_error;
80406   }
80407   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
80408     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80409     goto detach_error;
80410   }
80411 
80412   sqlite3BtreeClose(pDb->pBt);
80413   pDb->pBt = 0;
80414   pDb->pSchema = 0;
80415   sqlite3ResetAllSchemasOfConnection(db);
80416   return;
80417 
80418 detach_error:
80419   sqlite3_result_error(context, zErr, -1);
80420 }
80421 
80422 /*
80423 ** This procedure generates VDBE code for a single invocation of either the
80424 ** sqlite_detach() or sqlite_attach() SQL user functions.
80425 */
80426 static void codeAttach(
80427   Parse *pParse,       /* The parser context */
80428   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
80429   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80430   Expr *pAuthArg,      /* Expression to pass to authorization callback */
80431   Expr *pFilename,     /* Name of database file */
80432   Expr *pDbname,       /* Name of the database to use internally */
80433   Expr *pKey           /* Database key for encryption extension */
80434 ){
80435   int rc;
80436   NameContext sName;
80437   Vdbe *v;
80438   sqlite3* db = pParse->db;
80439   int regArgs;
80440 
80441   memset(&sName, 0, sizeof(NameContext));
80442   sName.pParse = pParse;
80443 
80444   if(
80445       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80446       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80447       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
80448   ){
80449     pParse->nErr++;
80450     goto attach_end;
80451   }
80452 
80453 #ifndef SQLITE_OMIT_AUTHORIZATION
80454   if( pAuthArg ){
80455     char *zAuthArg;
80456     if( pAuthArg->op==TK_STRING ){
80457       zAuthArg = pAuthArg->u.zToken;
80458     }else{
80459       zAuthArg = 0;
80460     }
80461     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
80462     if(rc!=SQLITE_OK ){
80463       goto attach_end;
80464     }
80465   }
80466 #endif /* SQLITE_OMIT_AUTHORIZATION */
80467 
80468 
80469   v = sqlite3GetVdbe(pParse);
80470   regArgs = sqlite3GetTempRange(pParse, 4);
80471   sqlite3ExprCode(pParse, pFilename, regArgs);
80472   sqlite3ExprCode(pParse, pDbname, regArgs+1);
80473   sqlite3ExprCode(pParse, pKey, regArgs+2);
80474 
80475   assert( v || db->mallocFailed );
80476   if( v ){
80477     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80478     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80479     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
80480     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80481 
80482     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80483     ** statement only). For DETACH, set it to false (expire all existing
80484     ** statements).
80485     */
80486     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
80487   }
80488 
80489 attach_end:
80490   sqlite3ExprDelete(db, pFilename);
80491   sqlite3ExprDelete(db, pDbname);
80492   sqlite3ExprDelete(db, pKey);
80493 }
80494 
80495 /*
80496 ** Called by the parser to compile a DETACH statement.
80497 **
80498 **     DETACH pDbname
80499 */
80500 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
80501   static const FuncDef detach_func = {
80502     1,                /* nArg */
80503     SQLITE_UTF8,      /* iPrefEnc */
80504     0,                /* flags */
80505     0,                /* pUserData */
80506     0,                /* pNext */
80507     detachFunc,       /* xFunc */
80508     0,                /* xStep */
80509     0,                /* xFinalize */
80510     "sqlite_detach",  /* zName */
80511     0,                /* pHash */
80512     0                 /* pDestructor */
80513   };
80514   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80515 }
80516 
80517 /*
80518 ** Called by the parser to compile an ATTACH statement.
80519 **
80520 **     ATTACH p AS pDbname KEY pKey
80521 */
80522 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80523   static const FuncDef attach_func = {
80524     3,                /* nArg */
80525     SQLITE_UTF8,      /* iPrefEnc */
80526     0,                /* flags */
80527     0,                /* pUserData */
80528     0,                /* pNext */
80529     attachFunc,       /* xFunc */
80530     0,                /* xStep */
80531     0,                /* xFinalize */
80532     "sqlite_attach",  /* zName */
80533     0,                /* pHash */
80534     0                 /* pDestructor */
80535   };
80536   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
80537 }
80538 #endif /* SQLITE_OMIT_ATTACH */
80539 
80540 /*
80541 ** Initialize a DbFixer structure.  This routine must be called prior
80542 ** to passing the structure to one of the sqliteFixAAAA() routines below.
80543 **
80544 ** The return value indicates whether or not fixation is required.  TRUE
80545 ** means we do need to fix the database references, FALSE means we do not.
80546 */
80547 SQLITE_PRIVATE int sqlite3FixInit(
80548   DbFixer *pFix,      /* The fixer to be initialized */
80549   Parse *pParse,      /* Error messages will be written here */
80550   int iDb,            /* This is the database that must be used */
80551   const char *zType,  /* "view", "trigger", or "index" */
80552   const Token *pName  /* Name of the view, trigger, or index */
80553 ){
80554   sqlite3 *db;
80555 
80556   if( NEVER(iDb<0) || iDb==1 ) return 0;
80557   db = pParse->db;
80558   assert( db->nDb>iDb );
80559   pFix->pParse = pParse;
80560   pFix->zDb = db->aDb[iDb].zName;
80561   pFix->pSchema = db->aDb[iDb].pSchema;
80562   pFix->zType = zType;
80563   pFix->pName = pName;
80564   return 1;
80565 }
80566 
80567 /*
80568 ** The following set of routines walk through the parse tree and assign
80569 ** a specific database to all table references where the database name
80570 ** was left unspecified in the original SQL statement.  The pFix structure
80571 ** must have been initialized by a prior call to sqlite3FixInit().
80572 **
80573 ** These routines are used to make sure that an index, trigger, or
80574 ** view in one database does not refer to objects in a different database.
80575 ** (Exception: indices, triggers, and views in the TEMP database are
80576 ** allowed to refer to anything.)  If a reference is explicitly made
80577 ** to an object in a different database, an error message is added to
80578 ** pParse->zErrMsg and these routines return non-zero.  If everything
80579 ** checks out, these routines return 0.
80580 */
80581 SQLITE_PRIVATE int sqlite3FixSrcList(
80582   DbFixer *pFix,       /* Context of the fixation */
80583   SrcList *pList       /* The Source list to check and modify */
80584 ){
80585   int i;
80586   const char *zDb;
80587   struct SrcList_item *pItem;
80588 
80589   if( NEVER(pList==0) ) return 0;
80590   zDb = pFix->zDb;
80591   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80592     if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
80593       sqlite3ErrorMsg(pFix->pParse,
80594          "%s %T cannot reference objects in database %s",
80595          pFix->zType, pFix->pName, pItem->zDatabase);
80596       return 1;
80597     }
80598     sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
80599     pItem->zDatabase = 0;
80600     pItem->pSchema = pFix->pSchema;
80601 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80602     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
80603     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
80604 #endif
80605   }
80606   return 0;
80607 }
80608 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80609 SQLITE_PRIVATE int sqlite3FixSelect(
80610   DbFixer *pFix,       /* Context of the fixation */
80611   Select *pSelect      /* The SELECT statement to be fixed to one database */
80612 ){
80613   while( pSelect ){
80614     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
80615       return 1;
80616     }
80617     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
80618       return 1;
80619     }
80620     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
80621       return 1;
80622     }
80623     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
80624       return 1;
80625     }
80626     pSelect = pSelect->pPrior;
80627   }
80628   return 0;
80629 }
80630 SQLITE_PRIVATE int sqlite3FixExpr(
80631   DbFixer *pFix,     /* Context of the fixation */
80632   Expr *pExpr        /* The expression to be fixed to one database */
80633 ){
80634   while( pExpr ){
80635     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80636     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80637       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80638     }else{
80639       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
80640     }
80641     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
80642       return 1;
80643     }
80644     pExpr = pExpr->pLeft;
80645   }
80646   return 0;
80647 }
80648 SQLITE_PRIVATE int sqlite3FixExprList(
80649   DbFixer *pFix,     /* Context of the fixation */
80650   ExprList *pList    /* The expression to be fixed to one database */
80651 ){
80652   int i;
80653   struct ExprList_item *pItem;
80654   if( pList==0 ) return 0;
80655   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80656     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
80657       return 1;
80658     }
80659   }
80660   return 0;
80661 }
80662 #endif
80663 
80664 #ifndef SQLITE_OMIT_TRIGGER
80665 SQLITE_PRIVATE int sqlite3FixTriggerStep(
80666   DbFixer *pFix,     /* Context of the fixation */
80667   TriggerStep *pStep /* The trigger step be fixed to one database */
80668 ){
80669   while( pStep ){
80670     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
80671       return 1;
80672     }
80673     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
80674       return 1;
80675     }
80676     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
80677       return 1;
80678     }
80679     pStep = pStep->pNext;
80680   }
80681   return 0;
80682 }
80683 #endif
80684 
80685 /************** End of attach.c **********************************************/
80686 /************** Begin file auth.c ********************************************/
80687 /*
80688 ** 2003 January 11
80689 **
80690 ** The author disclaims copyright to this source code.  In place of
80691 ** a legal notice, here is a blessing:
80692 **
80693 **    May you do good and not evil.
80694 **    May you find forgiveness for yourself and forgive others.
80695 **    May you share freely, never taking more than you give.
80696 **
80697 *************************************************************************
80698 ** This file contains code used to implement the sqlite3_set_authorizer()
80699 ** API.  This facility is an optional feature of the library.  Embedded
80700 ** systems that do not need this facility may omit it by recompiling
80701 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
80702 */
80703 
80704 /*
80705 ** All of the code in this file may be omitted by defining a single
80706 ** macro.
80707 */
80708 #ifndef SQLITE_OMIT_AUTHORIZATION
80709 
80710 /*
80711 ** Set or clear the access authorization function.
80712 **
80713 ** The access authorization function is be called during the compilation
80714 ** phase to verify that the user has read and/or write access permission on
80715 ** various fields of the database.  The first argument to the auth function
80716 ** is a copy of the 3rd argument to this routine.  The second argument
80717 ** to the auth function is one of these constants:
80718 **
80719 **       SQLITE_CREATE_INDEX
80720 **       SQLITE_CREATE_TABLE
80721 **       SQLITE_CREATE_TEMP_INDEX
80722 **       SQLITE_CREATE_TEMP_TABLE
80723 **       SQLITE_CREATE_TEMP_TRIGGER
80724 **       SQLITE_CREATE_TEMP_VIEW
80725 **       SQLITE_CREATE_TRIGGER
80726 **       SQLITE_CREATE_VIEW
80727 **       SQLITE_DELETE
80728 **       SQLITE_DROP_INDEX
80729 **       SQLITE_DROP_TABLE
80730 **       SQLITE_DROP_TEMP_INDEX
80731 **       SQLITE_DROP_TEMP_TABLE
80732 **       SQLITE_DROP_TEMP_TRIGGER
80733 **       SQLITE_DROP_TEMP_VIEW
80734 **       SQLITE_DROP_TRIGGER
80735 **       SQLITE_DROP_VIEW
80736 **       SQLITE_INSERT
80737 **       SQLITE_PRAGMA
80738 **       SQLITE_READ
80739 **       SQLITE_SELECT
80740 **       SQLITE_TRANSACTION
80741 **       SQLITE_UPDATE
80742 **
80743 ** The third and fourth arguments to the auth function are the name of
80744 ** the table and the column that are being accessed.  The auth function
80745 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
80746 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
80747 ** means that the SQL statement will never-run - the sqlite3_exec() call
80748 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
80749 ** should run but attempts to read the specified column will return NULL
80750 ** and attempts to write the column will be ignored.
80751 **
80752 ** Setting the auth function to NULL disables this hook.  The default
80753 ** setting of the auth function is NULL.
80754 */
80755 SQLITE_API int sqlite3_set_authorizer(
80756   sqlite3 *db,
80757   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
80758   void *pArg
80759 ){
80760   sqlite3_mutex_enter(db->mutex);
80761   db->xAuth = xAuth;
80762   db->pAuthArg = pArg;
80763   sqlite3ExpirePreparedStatements(db);
80764   sqlite3_mutex_leave(db->mutex);
80765   return SQLITE_OK;
80766 }
80767 
80768 /*
80769 ** Write an error message into pParse->zErrMsg that explains that the
80770 ** user-supplied authorization function returned an illegal value.
80771 */
80772 static void sqliteAuthBadReturnCode(Parse *pParse){
80773   sqlite3ErrorMsg(pParse, "authorizer malfunction");
80774   pParse->rc = SQLITE_ERROR;
80775 }
80776 
80777 /*
80778 ** Invoke the authorization callback for permission to read column zCol from
80779 ** table zTab in database zDb. This function assumes that an authorization
80780 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
80781 **
80782 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
80783 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
80784 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
80785 */
80786 SQLITE_PRIVATE int sqlite3AuthReadCol(
80787   Parse *pParse,                  /* The parser context */
80788   const char *zTab,               /* Table name */
80789   const char *zCol,               /* Column name */
80790   int iDb                         /* Index of containing database. */
80791 ){
80792   sqlite3 *db = pParse->db;       /* Database handle */
80793   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
80794   int rc;                         /* Auth callback return code */
80795 
80796   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
80797   if( rc==SQLITE_DENY ){
80798     if( db->nDb>2 || iDb!=0 ){
80799       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
80800     }else{
80801       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
80802     }
80803     pParse->rc = SQLITE_AUTH;
80804   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
80805     sqliteAuthBadReturnCode(pParse);
80806   }
80807   return rc;
80808 }
80809 
80810 /*
80811 ** The pExpr should be a TK_COLUMN expression.  The table referred to
80812 ** is in pTabList or else it is the NEW or OLD table of a trigger.
80813 ** Check to see if it is OK to read this particular column.
80814 **
80815 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
80816 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
80817 ** then generate an error.
80818 */
80819 SQLITE_PRIVATE void sqlite3AuthRead(
80820   Parse *pParse,        /* The parser context */
80821   Expr *pExpr,          /* The expression to check authorization on */
80822   Schema *pSchema,      /* The schema of the expression */
80823   SrcList *pTabList     /* All table that pExpr might refer to */
80824 ){
80825   sqlite3 *db = pParse->db;
80826   Table *pTab = 0;      /* The table being read */
80827   const char *zCol;     /* Name of the column of the table */
80828   int iSrc;             /* Index in pTabList->a[] of table being read */
80829   int iDb;              /* The index of the database the expression refers to */
80830   int iCol;             /* Index of column in table */
80831 
80832   if( db->xAuth==0 ) return;
80833   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
80834   if( iDb<0 ){
80835     /* An attempt to read a column out of a subquery or other
80836     ** temporary table. */
80837     return;
80838   }
80839 
80840   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
80841   if( pExpr->op==TK_TRIGGER ){
80842     pTab = pParse->pTriggerTab;
80843   }else{
80844     assert( pTabList );
80845     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
80846       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
80847         pTab = pTabList->a[iSrc].pTab;
80848         break;
80849       }
80850     }
80851   }
80852   iCol = pExpr->iColumn;
80853   if( NEVER(pTab==0) ) return;
80854 
80855   if( iCol>=0 ){
80856     assert( iCol<pTab->nCol );
80857     zCol = pTab->aCol[iCol].zName;
80858   }else if( pTab->iPKey>=0 ){
80859     assert( pTab->iPKey<pTab->nCol );
80860     zCol = pTab->aCol[pTab->iPKey].zName;
80861   }else{
80862     zCol = "ROWID";
80863   }
80864   assert( iDb>=0 && iDb<db->nDb );
80865   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
80866     pExpr->op = TK_NULL;
80867   }
80868 }
80869 
80870 /*
80871 ** Do an authorization check using the code and arguments given.  Return
80872 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
80873 ** is returned, then the error count and error message in pParse are
80874 ** modified appropriately.
80875 */
80876 SQLITE_PRIVATE int sqlite3AuthCheck(
80877   Parse *pParse,
80878   int code,
80879   const char *zArg1,
80880   const char *zArg2,
80881   const char *zArg3
80882 ){
80883   sqlite3 *db = pParse->db;
80884   int rc;
80885 
80886   /* Don't do any authorization checks if the database is initialising
80887   ** or if the parser is being invoked from within sqlite3_declare_vtab.
80888   */
80889   if( db->init.busy || IN_DECLARE_VTAB ){
80890     return SQLITE_OK;
80891   }
80892 
80893   if( db->xAuth==0 ){
80894     return SQLITE_OK;
80895   }
80896   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
80897   if( rc==SQLITE_DENY ){
80898     sqlite3ErrorMsg(pParse, "not authorized");
80899     pParse->rc = SQLITE_AUTH;
80900   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
80901     rc = SQLITE_DENY;
80902     sqliteAuthBadReturnCode(pParse);
80903   }
80904   return rc;
80905 }
80906 
80907 /*
80908 ** Push an authorization context.  After this routine is called, the
80909 ** zArg3 argument to authorization callbacks will be zContext until
80910 ** popped.  Or if pParse==0, this routine is a no-op.
80911 */
80912 SQLITE_PRIVATE void sqlite3AuthContextPush(
80913   Parse *pParse,
80914   AuthContext *pContext,
80915   const char *zContext
80916 ){
80917   assert( pParse );
80918   pContext->pParse = pParse;
80919   pContext->zAuthContext = pParse->zAuthContext;
80920   pParse->zAuthContext = zContext;
80921 }
80922 
80923 /*
80924 ** Pop an authorization context that was previously pushed
80925 ** by sqlite3AuthContextPush
80926 */
80927 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
80928   if( pContext->pParse ){
80929     pContext->pParse->zAuthContext = pContext->zAuthContext;
80930     pContext->pParse = 0;
80931   }
80932 }
80933 
80934 #endif /* SQLITE_OMIT_AUTHORIZATION */
80935 
80936 /************** End of auth.c ************************************************/
80937 /************** Begin file build.c *******************************************/
80938 /*
80939 ** 2001 September 15
80940 **
80941 ** The author disclaims copyright to this source code.  In place of
80942 ** a legal notice, here is a blessing:
80943 **
80944 **    May you do good and not evil.
80945 **    May you find forgiveness for yourself and forgive others.
80946 **    May you share freely, never taking more than you give.
80947 **
80948 *************************************************************************
80949 ** This file contains C code routines that are called by the SQLite parser
80950 ** when syntax rules are reduced.  The routines in this file handle the
80951 ** following kinds of SQL syntax:
80952 **
80953 **     CREATE TABLE
80954 **     DROP TABLE
80955 **     CREATE INDEX
80956 **     DROP INDEX
80957 **     creating ID lists
80958 **     BEGIN TRANSACTION
80959 **     COMMIT
80960 **     ROLLBACK
80961 */
80962 
80963 /*
80964 ** This routine is called when a new SQL statement is beginning to
80965 ** be parsed.  Initialize the pParse structure as needed.
80966 */
80967 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
80968   pParse->explain = (u8)explainFlag;
80969   pParse->nVar = 0;
80970 }
80971 
80972 #ifndef SQLITE_OMIT_SHARED_CACHE
80973 /*
80974 ** The TableLock structure is only used by the sqlite3TableLock() and
80975 ** codeTableLocks() functions.
80976 */
80977 struct TableLock {
80978   int iDb;             /* The database containing the table to be locked */
80979   int iTab;            /* The root page of the table to be locked */
80980   u8 isWriteLock;      /* True for write lock.  False for a read lock */
80981   const char *zName;   /* Name of the table */
80982 };
80983 
80984 /*
80985 ** Record the fact that we want to lock a table at run-time.
80986 **
80987 ** The table to be locked has root page iTab and is found in database iDb.
80988 ** A read or a write lock can be taken depending on isWritelock.
80989 **
80990 ** This routine just records the fact that the lock is desired.  The
80991 ** code to make the lock occur is generated by a later call to
80992 ** codeTableLocks() which occurs during sqlite3FinishCoding().
80993 */
80994 SQLITE_PRIVATE void sqlite3TableLock(
80995   Parse *pParse,     /* Parsing context */
80996   int iDb,           /* Index of the database containing the table to lock */
80997   int iTab,          /* Root page number of the table to be locked */
80998   u8 isWriteLock,    /* True for a write lock */
80999   const char *zName  /* Name of the table to be locked */
81000 ){
81001   Parse *pToplevel = sqlite3ParseToplevel(pParse);
81002   int i;
81003   int nBytes;
81004   TableLock *p;
81005   assert( iDb>=0 );
81006 
81007   for(i=0; i<pToplevel->nTableLock; i++){
81008     p = &pToplevel->aTableLock[i];
81009     if( p->iDb==iDb && p->iTab==iTab ){
81010       p->isWriteLock = (p->isWriteLock || isWriteLock);
81011       return;
81012     }
81013   }
81014 
81015   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
81016   pToplevel->aTableLock =
81017       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
81018   if( pToplevel->aTableLock ){
81019     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
81020     p->iDb = iDb;
81021     p->iTab = iTab;
81022     p->isWriteLock = isWriteLock;
81023     p->zName = zName;
81024   }else{
81025     pToplevel->nTableLock = 0;
81026     pToplevel->db->mallocFailed = 1;
81027   }
81028 }
81029 
81030 /*
81031 ** Code an OP_TableLock instruction for each table locked by the
81032 ** statement (configured by calls to sqlite3TableLock()).
81033 */
81034 static void codeTableLocks(Parse *pParse){
81035   int i;
81036   Vdbe *pVdbe;
81037 
81038   pVdbe = sqlite3GetVdbe(pParse);
81039   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
81040 
81041   for(i=0; i<pParse->nTableLock; i++){
81042     TableLock *p = &pParse->aTableLock[i];
81043     int p1 = p->iDb;
81044     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
81045                       p->zName, P4_STATIC);
81046   }
81047 }
81048 #else
81049   #define codeTableLocks(x)
81050 #endif
81051 
81052 /*
81053 ** This routine is called after a single SQL statement has been
81054 ** parsed and a VDBE program to execute that statement has been
81055 ** prepared.  This routine puts the finishing touches on the
81056 ** VDBE program and resets the pParse structure for the next
81057 ** parse.
81058 **
81059 ** Note that if an error occurred, it might be the case that
81060 ** no VDBE code was generated.
81061 */
81062 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
81063   sqlite3 *db;
81064   Vdbe *v;
81065 
81066   assert( pParse->pToplevel==0 );
81067   db = pParse->db;
81068   if( db->mallocFailed ) return;
81069   if( pParse->nested ) return;
81070   if( pParse->nErr ) return;
81071 
81072   /* Begin by generating some termination code at the end of the
81073   ** vdbe program
81074   */
81075   v = sqlite3GetVdbe(pParse);
81076   assert( !pParse->isMultiWrite
81077        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
81078   if( v ){
81079     sqlite3VdbeAddOp0(v, OP_Halt);
81080 
81081     /* The cookie mask contains one bit for each database file open.
81082     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
81083     ** set for each database that is used.  Generate code to start a
81084     ** transaction on each used database and to verify the schema cookie
81085     ** on each used database.
81086     */
81087     if( pParse->cookieGoto>0 ){
81088       yDbMask mask;
81089       int iDb;
81090       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
81091       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81092         if( (mask & pParse->cookieMask)==0 ) continue;
81093         sqlite3VdbeUsesBtree(v, iDb);
81094         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
81095         if( db->init.busy==0 ){
81096           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81097           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
81098                             iDb, pParse->cookieValue[iDb],
81099                             db->aDb[iDb].pSchema->iGeneration);
81100         }
81101       }
81102 #ifndef SQLITE_OMIT_VIRTUALTABLE
81103       {
81104         int i;
81105         for(i=0; i<pParse->nVtabLock; i++){
81106           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
81107           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
81108         }
81109         pParse->nVtabLock = 0;
81110       }
81111 #endif
81112 
81113       /* Once all the cookies have been verified and transactions opened,
81114       ** obtain the required table-locks. This is a no-op unless the
81115       ** shared-cache feature is enabled.
81116       */
81117       codeTableLocks(pParse);
81118 
81119       /* Initialize any AUTOINCREMENT data structures required.
81120       */
81121       sqlite3AutoincrementBegin(pParse);
81122 
81123       /* Finally, jump back to the beginning of the executable code. */
81124       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
81125     }
81126   }
81127 
81128 
81129   /* Get the VDBE program ready for execution
81130   */
81131   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
81132 #ifdef SQLITE_DEBUG
81133     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
81134     sqlite3VdbeTrace(v, trace);
81135 #endif
81136     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
81137     /* A minimum of one cursor is required if autoincrement is used
81138     *  See ticket [a696379c1f08866] */
81139     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
81140     sqlite3VdbeMakeReady(v, pParse);
81141     pParse->rc = SQLITE_DONE;
81142     pParse->colNamesSet = 0;
81143   }else{
81144     pParse->rc = SQLITE_ERROR;
81145   }
81146   pParse->nTab = 0;
81147   pParse->nMem = 0;
81148   pParse->nSet = 0;
81149   pParse->nVar = 0;
81150   pParse->cookieMask = 0;
81151   pParse->cookieGoto = 0;
81152 }
81153 
81154 /*
81155 ** Run the parser and code generator recursively in order to generate
81156 ** code for the SQL statement given onto the end of the pParse context
81157 ** currently under construction.  When the parser is run recursively
81158 ** this way, the final OP_Halt is not appended and other initialization
81159 ** and finalization steps are omitted because those are handling by the
81160 ** outermost parser.
81161 **
81162 ** Not everything is nestable.  This facility is designed to permit
81163 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
81164 ** care if you decide to try to use this routine for some other purposes.
81165 */
81166 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
81167   va_list ap;
81168   char *zSql;
81169   char *zErrMsg = 0;
81170   sqlite3 *db = pParse->db;
81171 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
81172   char saveBuf[SAVE_SZ];
81173 
81174   if( pParse->nErr ) return;
81175   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
81176   va_start(ap, zFormat);
81177   zSql = sqlite3VMPrintf(db, zFormat, ap);
81178   va_end(ap);
81179   if( zSql==0 ){
81180     return;   /* A malloc must have failed */
81181   }
81182   pParse->nested++;
81183   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
81184   memset(&pParse->nVar, 0, SAVE_SZ);
81185   sqlite3RunParser(pParse, zSql, &zErrMsg);
81186   sqlite3DbFree(db, zErrMsg);
81187   sqlite3DbFree(db, zSql);
81188   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
81189   pParse->nested--;
81190 }
81191 
81192 /*
81193 ** Locate the in-memory structure that describes a particular database
81194 ** table given the name of that table and (optionally) the name of the
81195 ** database containing the table.  Return NULL if not found.
81196 **
81197 ** If zDatabase is 0, all databases are searched for the table and the
81198 ** first matching table is returned.  (No checking for duplicate table
81199 ** names is done.)  The search order is TEMP first, then MAIN, then any
81200 ** auxiliary databases added using the ATTACH command.
81201 **
81202 ** See also sqlite3LocateTable().
81203 */
81204 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
81205   Table *p = 0;
81206   int i;
81207   int nName;
81208   assert( zName!=0 );
81209   nName = sqlite3Strlen30(zName);
81210   /* All mutexes are required for schema access.  Make sure we hold them. */
81211   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81212   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81213     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81214     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81215     assert( sqlite3SchemaMutexHeld(db, j, 0) );
81216     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81217     if( p ) break;
81218   }
81219   return p;
81220 }
81221 
81222 /*
81223 ** Locate the in-memory structure that describes a particular database
81224 ** table given the name of that table and (optionally) the name of the
81225 ** database containing the table.  Return NULL if not found.  Also leave an
81226 ** error message in pParse->zErrMsg.
81227 **
81228 ** The difference between this routine and sqlite3FindTable() is that this
81229 ** routine leaves an error message in pParse->zErrMsg where
81230 ** sqlite3FindTable() does not.
81231 */
81232 SQLITE_PRIVATE Table *sqlite3LocateTable(
81233   Parse *pParse,         /* context in which to report errors */
81234   int isView,            /* True if looking for a VIEW rather than a TABLE */
81235   const char *zName,     /* Name of the table we are looking for */
81236   const char *zDbase     /* Name of the database.  Might be NULL */
81237 ){
81238   Table *p;
81239 
81240   /* Read the database schema. If an error occurs, leave an error message
81241   ** and code in pParse and return NULL. */
81242   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81243     return 0;
81244   }
81245 
81246   p = sqlite3FindTable(pParse->db, zName, zDbase);
81247   if( p==0 ){
81248     const char *zMsg = isView ? "no such view" : "no such table";
81249     if( zDbase ){
81250       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81251     }else{
81252       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81253     }
81254     pParse->checkSchema = 1;
81255   }
81256   return p;
81257 }
81258 
81259 /*
81260 ** Locate the table identified by *p.
81261 **
81262 ** This is a wrapper around sqlite3LocateTable(). The difference between
81263 ** sqlite3LocateTable() and this function is that this function restricts
81264 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
81265 ** non-NULL if it is part of a view or trigger program definition. See
81266 ** sqlite3FixSrcList() for details.
81267 */
81268 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
81269   Parse *pParse,
81270   int isView,
81271   struct SrcList_item *p
81272 ){
81273   const char *zDb;
81274   assert( p->pSchema==0 || p->zDatabase==0 );
81275   if( p->pSchema ){
81276     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
81277     zDb = pParse->db->aDb[iDb].zName;
81278   }else{
81279     zDb = p->zDatabase;
81280   }
81281   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
81282 }
81283 
81284 /*
81285 ** Locate the in-memory structure that describes
81286 ** a particular index given the name of that index
81287 ** and the name of the database that contains the index.
81288 ** Return NULL if not found.
81289 **
81290 ** If zDatabase is 0, all databases are searched for the
81291 ** table and the first matching index is returned.  (No checking
81292 ** for duplicate index names is done.)  The search order is
81293 ** TEMP first, then MAIN, then any auxiliary databases added
81294 ** using the ATTACH command.
81295 */
81296 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
81297   Index *p = 0;
81298   int i;
81299   int nName = sqlite3Strlen30(zName);
81300   /* All mutexes are required for schema access.  Make sure we hold them. */
81301   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81302   for(i=OMIT_TEMPDB; i<db->nDb; i++){
81303     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81304     Schema *pSchema = db->aDb[j].pSchema;
81305     assert( pSchema );
81306     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
81307     assert( sqlite3SchemaMutexHeld(db, j, 0) );
81308     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
81309     if( p ) break;
81310   }
81311   return p;
81312 }
81313 
81314 /*
81315 ** Reclaim the memory used by an index
81316 */
81317 static void freeIndex(sqlite3 *db, Index *p){
81318 #ifndef SQLITE_OMIT_ANALYZE
81319   sqlite3DeleteIndexSamples(db, p);
81320 #endif
81321   sqlite3DbFree(db, p->zColAff);
81322   sqlite3DbFree(db, p);
81323 }
81324 
81325 /*
81326 ** For the index called zIdxName which is found in the database iDb,
81327 ** unlike that index from its Table then remove the index from
81328 ** the index hash table and free all memory structures associated
81329 ** with the index.
81330 */
81331 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
81332   Index *pIndex;
81333   int len;
81334   Hash *pHash;
81335 
81336   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81337   pHash = &db->aDb[iDb].pSchema->idxHash;
81338   len = sqlite3Strlen30(zIdxName);
81339   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
81340   if( ALWAYS(pIndex) ){
81341     if( pIndex->pTable->pIndex==pIndex ){
81342       pIndex->pTable->pIndex = pIndex->pNext;
81343     }else{
81344       Index *p;
81345       /* Justification of ALWAYS();  The index must be on the list of
81346       ** indices. */
81347       p = pIndex->pTable->pIndex;
81348       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81349       if( ALWAYS(p && p->pNext==pIndex) ){
81350         p->pNext = pIndex->pNext;
81351       }
81352     }
81353     freeIndex(db, pIndex);
81354   }
81355   db->flags |= SQLITE_InternChanges;
81356 }
81357 
81358 /*
81359 ** Look through the list of open database files in db->aDb[] and if
81360 ** any have been closed, remove them from the list.  Reallocate the
81361 ** db->aDb[] structure to a smaller size, if possible.
81362 **
81363 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
81364 ** are never candidates for being collapsed.
81365 */
81366 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
81367   int i, j;
81368   for(i=j=2; i<db->nDb; i++){
81369     struct Db *pDb = &db->aDb[i];
81370     if( pDb->pBt==0 ){
81371       sqlite3DbFree(db, pDb->zName);
81372       pDb->zName = 0;
81373       continue;
81374     }
81375     if( j<i ){
81376       db->aDb[j] = db->aDb[i];
81377     }
81378     j++;
81379   }
81380   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81381   db->nDb = j;
81382   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81383     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81384     sqlite3DbFree(db, db->aDb);
81385     db->aDb = db->aDbStatic;
81386   }
81387 }
81388 
81389 /*
81390 ** Reset the schema for the database at index iDb.  Also reset the
81391 ** TEMP schema.
81392 */
81393 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
81394   Db *pDb;
81395   assert( iDb<db->nDb );
81396 
81397   /* Case 1:  Reset the single schema identified by iDb */
81398   pDb = &db->aDb[iDb];
81399   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81400   assert( pDb->pSchema!=0 );
81401   sqlite3SchemaClear(pDb->pSchema);
81402 
81403   /* If any database other than TEMP is reset, then also reset TEMP
81404   ** since TEMP might be holding triggers that reference tables in the
81405   ** other database.
81406   */
81407   if( iDb!=1 ){
81408     pDb = &db->aDb[1];
81409     assert( pDb->pSchema!=0 );
81410     sqlite3SchemaClear(pDb->pSchema);
81411   }
81412   return;
81413 }
81414 
81415 /*
81416 ** Erase all schema information from all attached databases (including
81417 ** "main" and "temp") for a single database connection.
81418 */
81419 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
81420   int i;
81421   sqlite3BtreeEnterAll(db);
81422   for(i=0; i<db->nDb; i++){
81423     Db *pDb = &db->aDb[i];
81424     if( pDb->pSchema ){
81425       sqlite3SchemaClear(pDb->pSchema);
81426     }
81427   }
81428   db->flags &= ~SQLITE_InternChanges;
81429   sqlite3VtabUnlockList(db);
81430   sqlite3BtreeLeaveAll(db);
81431   sqlite3CollapseDatabaseArray(db);
81432 }
81433 
81434 /*
81435 ** This routine is called when a commit occurs.
81436 */
81437 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
81438   db->flags &= ~SQLITE_InternChanges;
81439 }
81440 
81441 /*
81442 ** Delete memory allocated for the column names of a table or view (the
81443 ** Table.aCol[] array).
81444 */
81445 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
81446   int i;
81447   Column *pCol;
81448   assert( pTable!=0 );
81449   if( (pCol = pTable->aCol)!=0 ){
81450     for(i=0; i<pTable->nCol; i++, pCol++){
81451       sqlite3DbFree(db, pCol->zName);
81452       sqlite3ExprDelete(db, pCol->pDflt);
81453       sqlite3DbFree(db, pCol->zDflt);
81454       sqlite3DbFree(db, pCol->zType);
81455       sqlite3DbFree(db, pCol->zColl);
81456     }
81457     sqlite3DbFree(db, pTable->aCol);
81458   }
81459 }
81460 
81461 /*
81462 ** Remove the memory data structures associated with the given
81463 ** Table.  No changes are made to disk by this routine.
81464 **
81465 ** This routine just deletes the data structure.  It does not unlink
81466 ** the table data structure from the hash table.  But it does destroy
81467 ** memory structures of the indices and foreign keys associated with
81468 ** the table.
81469 **
81470 ** The db parameter is optional.  It is needed if the Table object
81471 ** contains lookaside memory.  (Table objects in the schema do not use
81472 ** lookaside memory, but some ephemeral Table objects do.)  Or the
81473 ** db parameter can be used with db->pnBytesFreed to measure the memory
81474 ** used by the Table object.
81475 */
81476 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
81477   Index *pIndex, *pNext;
81478   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
81479 
81480   assert( !pTable || pTable->nRef>0 );
81481 
81482   /* Do not delete the table until the reference count reaches zero. */
81483   if( !pTable ) return;
81484   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81485 
81486   /* Record the number of outstanding lookaside allocations in schema Tables
81487   ** prior to doing any free() operations.  Since schema Tables do not use
81488   ** lookaside, this number should not change. */
81489   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
81490                          db->lookaside.nOut : 0 );
81491 
81492   /* Delete all indices associated with this table. */
81493   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81494     pNext = pIndex->pNext;
81495     assert( pIndex->pSchema==pTable->pSchema );
81496     if( !db || db->pnBytesFreed==0 ){
81497       char *zName = pIndex->zName;
81498       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
81499          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
81500       );
81501       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81502       assert( pOld==pIndex || pOld==0 );
81503     }
81504     freeIndex(db, pIndex);
81505   }
81506 
81507   /* Delete any foreign keys attached to this table. */
81508   sqlite3FkDelete(db, pTable);
81509 
81510   /* Delete the Table structure itself.
81511   */
81512   sqliteDeleteColumnNames(db, pTable);
81513   sqlite3DbFree(db, pTable->zName);
81514   sqlite3DbFree(db, pTable->zColAff);
81515   sqlite3SelectDelete(db, pTable->pSelect);
81516 #ifndef SQLITE_OMIT_CHECK
81517   sqlite3ExprListDelete(db, pTable->pCheck);
81518 #endif
81519 #ifndef SQLITE_OMIT_VIRTUALTABLE
81520   sqlite3VtabClear(db, pTable);
81521 #endif
81522   sqlite3DbFree(db, pTable);
81523 
81524   /* Verify that no lookaside memory was used by schema tables */
81525   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
81526 }
81527 
81528 /*
81529 ** Unlink the given table from the hash tables and the delete the
81530 ** table structure with all its indices and foreign keys.
81531 */
81532 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
81533   Table *p;
81534   Db *pDb;
81535 
81536   assert( db!=0 );
81537   assert( iDb>=0 && iDb<db->nDb );
81538   assert( zTabName );
81539   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81540   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81541   pDb = &db->aDb[iDb];
81542   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
81543                         sqlite3Strlen30(zTabName),0);
81544   sqlite3DeleteTable(db, p);
81545   db->flags |= SQLITE_InternChanges;
81546 }
81547 
81548 /*
81549 ** Given a token, return a string that consists of the text of that
81550 ** token.  Space to hold the returned string
81551 ** is obtained from sqliteMalloc() and must be freed by the calling
81552 ** function.
81553 **
81554 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81555 ** surround the body of the token are removed.
81556 **
81557 ** Tokens are often just pointers into the original SQL text and so
81558 ** are not \000 terminated and are not persistent.  The returned string
81559 ** is \000 terminated and is persistent.
81560 */
81561 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
81562   char *zName;
81563   if( pName ){
81564     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
81565     sqlite3Dequote(zName);
81566   }else{
81567     zName = 0;
81568   }
81569   return zName;
81570 }
81571 
81572 /*
81573 ** Open the sqlite_master table stored in database number iDb for
81574 ** writing. The table is opened using cursor 0.
81575 */
81576 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
81577   Vdbe *v = sqlite3GetVdbe(p);
81578   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81579   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81580   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81581   if( p->nTab==0 ){
81582     p->nTab = 1;
81583   }
81584 }
81585 
81586 /*
81587 ** Parameter zName points to a nul-terminated buffer containing the name
81588 ** of a database ("main", "temp" or the name of an attached db). This
81589 ** function returns the index of the named database in db->aDb[], or
81590 ** -1 if the named db cannot be found.
81591 */
81592 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
81593   int i = -1;         /* Database number */
81594   if( zName ){
81595     Db *pDb;
81596     int n = sqlite3Strlen30(zName);
81597     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81598       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
81599           0==sqlite3StrICmp(pDb->zName, zName) ){
81600         break;
81601       }
81602     }
81603   }
81604   return i;
81605 }
81606 
81607 /*
81608 ** The token *pName contains the name of a database (either "main" or
81609 ** "temp" or the name of an attached db). This routine returns the
81610 ** index of the named database in db->aDb[], or -1 if the named db
81611 ** does not exist.
81612 */
81613 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
81614   int i;                               /* Database number */
81615   char *zName;                         /* Name we are searching for */
81616   zName = sqlite3NameFromToken(db, pName);
81617   i = sqlite3FindDbName(db, zName);
81618   sqlite3DbFree(db, zName);
81619   return i;
81620 }
81621 
81622 /* The table or view or trigger name is passed to this routine via tokens
81623 ** pName1 and pName2. If the table name was fully qualified, for example:
81624 **
81625 ** CREATE TABLE xxx.yyy (...);
81626 **
81627 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81628 ** the table name is not fully qualified, i.e.:
81629 **
81630 ** CREATE TABLE yyy(...);
81631 **
81632 ** Then pName1 is set to "yyy" and pName2 is "".
81633 **
81634 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81635 ** pName2) that stores the unqualified table name.  The index of the
81636 ** database "xxx" is returned.
81637 */
81638 SQLITE_PRIVATE int sqlite3TwoPartName(
81639   Parse *pParse,      /* Parsing and code generating context */
81640   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81641   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81642   Token **pUnqual     /* Write the unqualified object name here */
81643 ){
81644   int iDb;                    /* Database holding the object */
81645   sqlite3 *db = pParse->db;
81646 
81647   if( ALWAYS(pName2!=0) && pName2->n>0 ){
81648     if( db->init.busy ) {
81649       sqlite3ErrorMsg(pParse, "corrupt database");
81650       pParse->nErr++;
81651       return -1;
81652     }
81653     *pUnqual = pName2;
81654     iDb = sqlite3FindDb(db, pName1);
81655     if( iDb<0 ){
81656       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
81657       pParse->nErr++;
81658       return -1;
81659     }
81660   }else{
81661     assert( db->init.iDb==0 || db->init.busy );
81662     iDb = db->init.iDb;
81663     *pUnqual = pName1;
81664   }
81665   return iDb;
81666 }
81667 
81668 /*
81669 ** This routine is used to check if the UTF-8 string zName is a legal
81670 ** unqualified name for a new schema object (table, index, view or
81671 ** trigger). All names are legal except those that begin with the string
81672 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
81673 ** is reserved for internal use.
81674 */
81675 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
81676   if( !pParse->db->init.busy && pParse->nested==0
81677           && (pParse->db->flags & SQLITE_WriteSchema)==0
81678           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
81679     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81680     return SQLITE_ERROR;
81681   }
81682   return SQLITE_OK;
81683 }
81684 
81685 /*
81686 ** Begin constructing a new table representation in memory.  This is
81687 ** the first of several action routines that get called in response
81688 ** to a CREATE TABLE statement.  In particular, this routine is called
81689 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81690 ** flag is true if the table should be stored in the auxiliary database
81691 ** file instead of in the main database file.  This is normally the case
81692 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
81693 ** CREATE and TABLE.
81694 **
81695 ** The new table record is initialized and put in pParse->pNewTable.
81696 ** As more of the CREATE TABLE statement is parsed, additional action
81697 ** routines will be called to add more information to this record.
81698 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
81699 ** is called to complete the construction of the new table record.
81700 */
81701 SQLITE_PRIVATE void sqlite3StartTable(
81702   Parse *pParse,   /* Parser context */
81703   Token *pName1,   /* First part of the name of the table or view */
81704   Token *pName2,   /* Second part of the name of the table or view */
81705   int isTemp,      /* True if this is a TEMP table */
81706   int isView,      /* True if this is a VIEW */
81707   int isVirtual,   /* True if this is a VIRTUAL table */
81708   int noErr        /* Do nothing if table already exists */
81709 ){
81710   Table *pTable;
81711   char *zName = 0; /* The name of the new table */
81712   sqlite3 *db = pParse->db;
81713   Vdbe *v;
81714   int iDb;         /* Database number to create the table in */
81715   Token *pName;    /* Unqualified name of the table to create */
81716 
81717   /* The table or view name to create is passed to this routine via tokens
81718   ** pName1 and pName2. If the table name was fully qualified, for example:
81719   **
81720   ** CREATE TABLE xxx.yyy (...);
81721   **
81722   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81723   ** the table name is not fully qualified, i.e.:
81724   **
81725   ** CREATE TABLE yyy(...);
81726   **
81727   ** Then pName1 is set to "yyy" and pName2 is "".
81728   **
81729   ** The call below sets the pName pointer to point at the token (pName1 or
81730   ** pName2) that stores the unqualified table name. The variable iDb is
81731   ** set to the index of the database that the table or view is to be
81732   ** created in.
81733   */
81734   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81735   if( iDb<0 ) return;
81736   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81737     /* If creating a temp table, the name may not be qualified. Unless
81738     ** the database name is "temp" anyway.  */
81739     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
81740     return;
81741   }
81742   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81743 
81744   pParse->sNameToken = *pName;
81745   zName = sqlite3NameFromToken(db, pName);
81746   if( zName==0 ) return;
81747   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
81748     goto begin_table_error;
81749   }
81750   if( db->init.iDb==1 ) isTemp = 1;
81751 #ifndef SQLITE_OMIT_AUTHORIZATION
81752   assert( (isTemp & 1)==isTemp );
81753   {
81754     int code;
81755     char *zDb = db->aDb[iDb].zName;
81756     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81757       goto begin_table_error;
81758     }
81759     if( isView ){
81760       if( !OMIT_TEMPDB && isTemp ){
81761         code = SQLITE_CREATE_TEMP_VIEW;
81762       }else{
81763         code = SQLITE_CREATE_VIEW;
81764       }
81765     }else{
81766       if( !OMIT_TEMPDB && isTemp ){
81767         code = SQLITE_CREATE_TEMP_TABLE;
81768       }else{
81769         code = SQLITE_CREATE_TABLE;
81770       }
81771     }
81772     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
81773       goto begin_table_error;
81774     }
81775   }
81776 #endif
81777 
81778   /* Make sure the new table name does not collide with an existing
81779   ** index or table name in the same database.  Issue an error message if
81780   ** it does. The exception is if the statement being parsed was passed
81781   ** to an sqlite3_declare_vtab() call. In that case only the column names
81782   ** and types will be used, so there is no need to test for namespace
81783   ** collisions.
81784   */
81785   if( !IN_DECLARE_VTAB ){
81786     char *zDb = db->aDb[iDb].zName;
81787     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81788       goto begin_table_error;
81789     }
81790     pTable = sqlite3FindTable(db, zName, zDb);
81791     if( pTable ){
81792       if( !noErr ){
81793         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
81794       }else{
81795         assert( !db->init.busy );
81796         sqlite3CodeVerifySchema(pParse, iDb);
81797       }
81798       goto begin_table_error;
81799     }
81800     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
81801       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
81802       goto begin_table_error;
81803     }
81804   }
81805 
81806   pTable = sqlite3DbMallocZero(db, sizeof(Table));
81807   if( pTable==0 ){
81808     db->mallocFailed = 1;
81809     pParse->rc = SQLITE_NOMEM;
81810     pParse->nErr++;
81811     goto begin_table_error;
81812   }
81813   pTable->zName = zName;
81814   pTable->iPKey = -1;
81815   pTable->pSchema = db->aDb[iDb].pSchema;
81816   pTable->nRef = 1;
81817   pTable->nRowEst = 1000000;
81818   assert( pParse->pNewTable==0 );
81819   pParse->pNewTable = pTable;
81820 
81821   /* If this is the magic sqlite_sequence table used by autoincrement,
81822   ** then record a pointer to this table in the main database structure
81823   ** so that INSERT can find the table easily.
81824   */
81825 #ifndef SQLITE_OMIT_AUTOINCREMENT
81826   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
81827     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81828     pTable->pSchema->pSeqTab = pTable;
81829   }
81830 #endif
81831 
81832   /* Begin generating the code that will insert the table record into
81833   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
81834   ** and allocate the record number for the table entry now.  Before any
81835   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
81836   ** indices to be created and the table record must come before the
81837   ** indices.  Hence, the record number for the table must be allocated
81838   ** now.
81839   */
81840   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
81841     int j1;
81842     int fileFormat;
81843     int reg1, reg2, reg3;
81844     sqlite3BeginWriteOperation(pParse, 0, iDb);
81845 
81846 #ifndef SQLITE_OMIT_VIRTUALTABLE
81847     if( isVirtual ){
81848       sqlite3VdbeAddOp0(v, OP_VBegin);
81849     }
81850 #endif
81851 
81852     /* If the file format and encoding in the database have not been set,
81853     ** set them now.
81854     */
81855     reg1 = pParse->regRowid = ++pParse->nMem;
81856     reg2 = pParse->regRoot = ++pParse->nMem;
81857     reg3 = ++pParse->nMem;
81858     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
81859     sqlite3VdbeUsesBtree(v, iDb);
81860     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
81861     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
81862                   1 : SQLITE_MAX_FILE_FORMAT;
81863     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
81864     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
81865     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
81866     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
81867     sqlite3VdbeJumpHere(v, j1);
81868 
81869     /* This just creates a place-holder record in the sqlite_master table.
81870     ** The record created does not contain anything yet.  It will be replaced
81871     ** by the real entry in code generated at sqlite3EndTable().
81872     **
81873     ** The rowid for the new entry is left in register pParse->regRowid.
81874     ** The root page number of the new table is left in reg pParse->regRoot.
81875     ** The rowid and root page number values are needed by the code that
81876     ** sqlite3EndTable will generate.
81877     */
81878 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
81879     if( isView || isVirtual ){
81880       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
81881     }else
81882 #endif
81883     {
81884       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
81885     }
81886     sqlite3OpenMasterTable(pParse, iDb);
81887     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
81888     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
81889     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
81890     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81891     sqlite3VdbeAddOp0(v, OP_Close);
81892   }
81893 
81894   /* Normal (non-error) return. */
81895   return;
81896 
81897   /* If an error occurs, we jump here */
81898 begin_table_error:
81899   sqlite3DbFree(db, zName);
81900   return;
81901 }
81902 
81903 /*
81904 ** This macro is used to compare two strings in a case-insensitive manner.
81905 ** It is slightly faster than calling sqlite3StrICmp() directly, but
81906 ** produces larger code.
81907 **
81908 ** WARNING: This macro is not compatible with the strcmp() family. It
81909 ** returns true if the two strings are equal, otherwise false.
81910 */
81911 #define STRICMP(x, y) (\
81912 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
81913 sqlite3UpperToLower[*(unsigned char *)(y)]     \
81914 && sqlite3StrICmp((x)+1,(y)+1)==0 )
81915 
81916 /*
81917 ** Add a new column to the table currently being constructed.
81918 **
81919 ** The parser calls this routine once for each column declaration
81920 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
81921 ** first to get things going.  Then this routine is called for each
81922 ** column.
81923 */
81924 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
81925   Table *p;
81926   int i;
81927   char *z;
81928   Column *pCol;
81929   sqlite3 *db = pParse->db;
81930   if( (p = pParse->pNewTable)==0 ) return;
81931 #if SQLITE_MAX_COLUMN
81932   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
81933     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
81934     return;
81935   }
81936 #endif
81937   z = sqlite3NameFromToken(db, pName);
81938   if( z==0 ) return;
81939   for(i=0; i<p->nCol; i++){
81940     if( STRICMP(z, p->aCol[i].zName) ){
81941       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
81942       sqlite3DbFree(db, z);
81943       return;
81944     }
81945   }
81946   if( (p->nCol & 0x7)==0 ){
81947     Column *aNew;
81948     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
81949     if( aNew==0 ){
81950       sqlite3DbFree(db, z);
81951       return;
81952     }
81953     p->aCol = aNew;
81954   }
81955   pCol = &p->aCol[p->nCol];
81956   memset(pCol, 0, sizeof(p->aCol[0]));
81957   pCol->zName = z;
81958 
81959   /* If there is no type specified, columns have the default affinity
81960   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
81961   ** be called next to set pCol->affinity correctly.
81962   */
81963   pCol->affinity = SQLITE_AFF_NONE;
81964   p->nCol++;
81965 }
81966 
81967 /*
81968 ** This routine is called by the parser while in the middle of
81969 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
81970 ** been seen on a column.  This routine sets the notNull flag on
81971 ** the column currently under construction.
81972 */
81973 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
81974   Table *p;
81975   p = pParse->pNewTable;
81976   if( p==0 || NEVER(p->nCol<1) ) return;
81977   p->aCol[p->nCol-1].notNull = (u8)onError;
81978 }
81979 
81980 /*
81981 ** Scan the column type name zType (length nType) and return the
81982 ** associated affinity type.
81983 **
81984 ** This routine does a case-independent search of zType for the
81985 ** substrings in the following table. If one of the substrings is
81986 ** found, the corresponding affinity is returned. If zType contains
81987 ** more than one of the substrings, entries toward the top of
81988 ** the table take priority. For example, if zType is 'BLOBINT',
81989 ** SQLITE_AFF_INTEGER is returned.
81990 **
81991 ** Substring     | Affinity
81992 ** --------------------------------
81993 ** 'INT'         | SQLITE_AFF_INTEGER
81994 ** 'CHAR'        | SQLITE_AFF_TEXT
81995 ** 'CLOB'        | SQLITE_AFF_TEXT
81996 ** 'TEXT'        | SQLITE_AFF_TEXT
81997 ** 'BLOB'        | SQLITE_AFF_NONE
81998 ** 'REAL'        | SQLITE_AFF_REAL
81999 ** 'FLOA'        | SQLITE_AFF_REAL
82000 ** 'DOUB'        | SQLITE_AFF_REAL
82001 **
82002 ** If none of the substrings in the above table are found,
82003 ** SQLITE_AFF_NUMERIC is returned.
82004 */
82005 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
82006   u32 h = 0;
82007   char aff = SQLITE_AFF_NUMERIC;
82008 
82009   if( zIn ) while( zIn[0] ){
82010     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
82011     zIn++;
82012     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
82013       aff = SQLITE_AFF_TEXT;
82014     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
82015       aff = SQLITE_AFF_TEXT;
82016     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
82017       aff = SQLITE_AFF_TEXT;
82018     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
82019         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
82020       aff = SQLITE_AFF_NONE;
82021 #ifndef SQLITE_OMIT_FLOATING_POINT
82022     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
82023         && aff==SQLITE_AFF_NUMERIC ){
82024       aff = SQLITE_AFF_REAL;
82025     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
82026         && aff==SQLITE_AFF_NUMERIC ){
82027       aff = SQLITE_AFF_REAL;
82028     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
82029         && aff==SQLITE_AFF_NUMERIC ){
82030       aff = SQLITE_AFF_REAL;
82031 #endif
82032     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
82033       aff = SQLITE_AFF_INTEGER;
82034       break;
82035     }
82036   }
82037 
82038   return aff;
82039 }
82040 
82041 /*
82042 ** This routine is called by the parser while in the middle of
82043 ** parsing a CREATE TABLE statement.  The pFirst token is the first
82044 ** token in the sequence of tokens that describe the type of the
82045 ** column currently under construction.   pLast is the last token
82046 ** in the sequence.  Use this information to construct a string
82047 ** that contains the typename of the column and store that string
82048 ** in zType.
82049 */
82050 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
82051   Table *p;
82052   Column *pCol;
82053 
82054   p = pParse->pNewTable;
82055   if( p==0 || NEVER(p->nCol<1) ) return;
82056   pCol = &p->aCol[p->nCol-1];
82057   assert( pCol->zType==0 );
82058   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
82059   pCol->affinity = sqlite3AffinityType(pCol->zType);
82060 }
82061 
82062 /*
82063 ** The expression is the default value for the most recently added column
82064 ** of the table currently under construction.
82065 **
82066 ** Default value expressions must be constant.  Raise an exception if this
82067 ** is not the case.
82068 **
82069 ** This routine is called by the parser while in the middle of
82070 ** parsing a CREATE TABLE statement.
82071 */
82072 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
82073   Table *p;
82074   Column *pCol;
82075   sqlite3 *db = pParse->db;
82076   p = pParse->pNewTable;
82077   if( p!=0 ){
82078     pCol = &(p->aCol[p->nCol-1]);
82079     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
82080       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
82081           pCol->zName);
82082     }else{
82083       /* A copy of pExpr is used instead of the original, as pExpr contains
82084       ** tokens that point to volatile memory. The 'span' of the expression
82085       ** is required by pragma table_info.
82086       */
82087       sqlite3ExprDelete(db, pCol->pDflt);
82088       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
82089       sqlite3DbFree(db, pCol->zDflt);
82090       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
82091                                      (int)(pSpan->zEnd - pSpan->zStart));
82092     }
82093   }
82094   sqlite3ExprDelete(db, pSpan->pExpr);
82095 }
82096 
82097 /*
82098 ** Designate the PRIMARY KEY for the table.  pList is a list of names
82099 ** of columns that form the primary key.  If pList is NULL, then the
82100 ** most recently added column of the table is the primary key.
82101 **
82102 ** A table can have at most one primary key.  If the table already has
82103 ** a primary key (and this is the second primary key) then create an
82104 ** error.
82105 **
82106 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
82107 ** then we will try to use that column as the rowid.  Set the Table.iPKey
82108 ** field of the table under construction to be the index of the
82109 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
82110 ** no INTEGER PRIMARY KEY.
82111 **
82112 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
82113 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
82114 */
82115 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
82116   Parse *pParse,    /* Parsing context */
82117   ExprList *pList,  /* List of field names to be indexed */
82118   int onError,      /* What to do with a uniqueness conflict */
82119   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
82120   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
82121 ){
82122   Table *pTab = pParse->pNewTable;
82123   char *zType = 0;
82124   int iCol = -1, i;
82125   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
82126   if( pTab->tabFlags & TF_HasPrimaryKey ){
82127     sqlite3ErrorMsg(pParse,
82128       "table \"%s\" has more than one primary key", pTab->zName);
82129     goto primary_key_exit;
82130   }
82131   pTab->tabFlags |= TF_HasPrimaryKey;
82132   if( pList==0 ){
82133     iCol = pTab->nCol - 1;
82134     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
82135   }else{
82136     for(i=0; i<pList->nExpr; i++){
82137       for(iCol=0; iCol<pTab->nCol; iCol++){
82138         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
82139           break;
82140         }
82141       }
82142       if( iCol<pTab->nCol ){
82143         pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
82144       }
82145     }
82146     if( pList->nExpr>1 ) iCol = -1;
82147   }
82148   if( iCol>=0 && iCol<pTab->nCol ){
82149     zType = pTab->aCol[iCol].zType;
82150   }
82151   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
82152         && sortOrder==SQLITE_SO_ASC ){
82153     pTab->iPKey = iCol;
82154     pTab->keyConf = (u8)onError;
82155     assert( autoInc==0 || autoInc==1 );
82156     pTab->tabFlags |= autoInc*TF_Autoincrement;
82157   }else if( autoInc ){
82158 #ifndef SQLITE_OMIT_AUTOINCREMENT
82159     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
82160        "INTEGER PRIMARY KEY");
82161 #endif
82162   }else{
82163     Index *p;
82164     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
82165     if( p ){
82166       p->autoIndex = 2;
82167     }
82168     pList = 0;
82169   }
82170 
82171 primary_key_exit:
82172   sqlite3ExprListDelete(pParse->db, pList);
82173   return;
82174 }
82175 
82176 /*
82177 ** Add a new CHECK constraint to the table currently under construction.
82178 */
82179 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
82180   Parse *pParse,    /* Parsing context */
82181   Expr *pCheckExpr  /* The check expression */
82182 ){
82183 #ifndef SQLITE_OMIT_CHECK
82184   Table *pTab = pParse->pNewTable;
82185   if( pTab && !IN_DECLARE_VTAB ){
82186     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
82187     if( pParse->constraintName.n ){
82188       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
82189     }
82190   }else
82191 #endif
82192   {
82193     sqlite3ExprDelete(pParse->db, pCheckExpr);
82194   }
82195 }
82196 
82197 /*
82198 ** Set the collation function of the most recently parsed table column
82199 ** to the CollSeq given.
82200 */
82201 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
82202   Table *p;
82203   int i;
82204   char *zColl;              /* Dequoted name of collation sequence */
82205   sqlite3 *db;
82206 
82207   if( (p = pParse->pNewTable)==0 ) return;
82208   i = p->nCol-1;
82209   db = pParse->db;
82210   zColl = sqlite3NameFromToken(db, pToken);
82211   if( !zColl ) return;
82212 
82213   if( sqlite3LocateCollSeq(pParse, zColl) ){
82214     Index *pIdx;
82215     p->aCol[i].zColl = zColl;
82216 
82217     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82218     ** then an index may have been created on this column before the
82219     ** collation type was added. Correct this if it is the case.
82220     */
82221     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82222       assert( pIdx->nColumn==1 );
82223       if( pIdx->aiColumn[0]==i ){
82224         pIdx->azColl[0] = p->aCol[i].zColl;
82225       }
82226     }
82227   }else{
82228     sqlite3DbFree(db, zColl);
82229   }
82230 }
82231 
82232 /*
82233 ** This function returns the collation sequence for database native text
82234 ** encoding identified by the string zName, length nName.
82235 **
82236 ** If the requested collation sequence is not available, or not available
82237 ** in the database native encoding, the collation factory is invoked to
82238 ** request it. If the collation factory does not supply such a sequence,
82239 ** and the sequence is available in another text encoding, then that is
82240 ** returned instead.
82241 **
82242 ** If no versions of the requested collations sequence are available, or
82243 ** another error occurs, NULL is returned and an error message written into
82244 ** pParse.
82245 **
82246 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
82247 ** invokes the collation factory if the named collation cannot be found
82248 ** and generates an error message.
82249 **
82250 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
82251 */
82252 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
82253   sqlite3 *db = pParse->db;
82254   u8 enc = ENC(db);
82255   u8 initbusy = db->init.busy;
82256   CollSeq *pColl;
82257 
82258   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
82259   if( !initbusy && (!pColl || !pColl->xCmp) ){
82260     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
82261   }
82262 
82263   return pColl;
82264 }
82265 
82266 
82267 /*
82268 ** Generate code that will increment the schema cookie.
82269 **
82270 ** The schema cookie is used to determine when the schema for the
82271 ** database changes.  After each schema change, the cookie value
82272 ** changes.  When a process first reads the schema it records the
82273 ** cookie.  Thereafter, whenever it goes to access the database,
82274 ** it checks the cookie to make sure the schema has not changed
82275 ** since it was last read.
82276 **
82277 ** This plan is not completely bullet-proof.  It is possible for
82278 ** the schema to change multiple times and for the cookie to be
82279 ** set back to prior value.  But schema changes are infrequent
82280 ** and the probability of hitting the same cookie value is only
82281 ** 1 chance in 2^32.  So we're safe enough.
82282 */
82283 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
82284   int r1 = sqlite3GetTempReg(pParse);
82285   sqlite3 *db = pParse->db;
82286   Vdbe *v = pParse->pVdbe;
82287   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82288   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82289   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82290   sqlite3ReleaseTempReg(pParse, r1);
82291 }
82292 
82293 /*
82294 ** Measure the number of characters needed to output the given
82295 ** identifier.  The number returned includes any quotes used
82296 ** but does not include the null terminator.
82297 **
82298 ** The estimate is conservative.  It might be larger that what is
82299 ** really needed.
82300 */
82301 static int identLength(const char *z){
82302   int n;
82303   for(n=0; *z; n++, z++){
82304     if( *z=='"' ){ n++; }
82305   }
82306   return n + 2;
82307 }
82308 
82309 /*
82310 ** The first parameter is a pointer to an output buffer. The second
82311 ** parameter is a pointer to an integer that contains the offset at
82312 ** which to write into the output buffer. This function copies the
82313 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
82314 ** to the specified offset in the buffer and updates *pIdx to refer
82315 ** to the first byte after the last byte written before returning.
82316 **
82317 ** If the string zSignedIdent consists entirely of alpha-numeric
82318 ** characters, does not begin with a digit and is not an SQL keyword,
82319 ** then it is copied to the output buffer exactly as it is. Otherwise,
82320 ** it is quoted using double-quotes.
82321 */
82322 static void identPut(char *z, int *pIdx, char *zSignedIdent){
82323   unsigned char *zIdent = (unsigned char*)zSignedIdent;
82324   int i, j, needQuote;
82325   i = *pIdx;
82326 
82327   for(j=0; zIdent[j]; j++){
82328     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82329   }
82330   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
82331   if( !needQuote ){
82332     needQuote = zIdent[j];
82333   }
82334 
82335   if( needQuote ) z[i++] = '"';
82336   for(j=0; zIdent[j]; j++){
82337     z[i++] = zIdent[j];
82338     if( zIdent[j]=='"' ) z[i++] = '"';
82339   }
82340   if( needQuote ) z[i++] = '"';
82341   z[i] = 0;
82342   *pIdx = i;
82343 }
82344 
82345 /*
82346 ** Generate a CREATE TABLE statement appropriate for the given
82347 ** table.  Memory to hold the text of the statement is obtained
82348 ** from sqliteMalloc() and must be freed by the calling function.
82349 */
82350 static char *createTableStmt(sqlite3 *db, Table *p){
82351   int i, k, n;
82352   char *zStmt;
82353   char *zSep, *zSep2, *zEnd;
82354   Column *pCol;
82355   n = 0;
82356   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82357     n += identLength(pCol->zName) + 5;
82358   }
82359   n += identLength(p->zName);
82360   if( n<50 ){
82361     zSep = "";
82362     zSep2 = ",";
82363     zEnd = ")";
82364   }else{
82365     zSep = "\n  ";
82366     zSep2 = ",\n  ";
82367     zEnd = "\n)";
82368   }
82369   n += 35 + 6*p->nCol;
82370   zStmt = sqlite3DbMallocRaw(0, n);
82371   if( zStmt==0 ){
82372     db->mallocFailed = 1;
82373     return 0;
82374   }
82375   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
82376   k = sqlite3Strlen30(zStmt);
82377   identPut(zStmt, &k, p->zName);
82378   zStmt[k++] = '(';
82379   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82380     static const char * const azType[] = {
82381         /* SQLITE_AFF_TEXT    */ " TEXT",
82382         /* SQLITE_AFF_NONE    */ "",
82383         /* SQLITE_AFF_NUMERIC */ " NUM",
82384         /* SQLITE_AFF_INTEGER */ " INT",
82385         /* SQLITE_AFF_REAL    */ " REAL"
82386     };
82387     int len;
82388     const char *zType;
82389 
82390     sqlite3_snprintf(n-k, &zStmt[k], zSep);
82391     k += sqlite3Strlen30(&zStmt[k]);
82392     zSep = zSep2;
82393     identPut(zStmt, &k, pCol->zName);
82394     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
82395     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
82396     testcase( pCol->affinity==SQLITE_AFF_TEXT );
82397     testcase( pCol->affinity==SQLITE_AFF_NONE );
82398     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
82399     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
82400     testcase( pCol->affinity==SQLITE_AFF_REAL );
82401 
82402     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
82403     len = sqlite3Strlen30(zType);
82404     assert( pCol->affinity==SQLITE_AFF_NONE
82405             || pCol->affinity==sqlite3AffinityType(zType) );
82406     memcpy(&zStmt[k], zType, len);
82407     k += len;
82408     assert( k<=n );
82409   }
82410   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82411   return zStmt;
82412 }
82413 
82414 /*
82415 ** This routine is called to report the final ")" that terminates
82416 ** a CREATE TABLE statement.
82417 **
82418 ** The table structure that other action routines have been building
82419 ** is added to the internal hash tables, assuming no errors have
82420 ** occurred.
82421 **
82422 ** An entry for the table is made in the master table on disk, unless
82423 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82424 ** it means we are reading the sqlite_master table because we just
82425 ** connected to the database or because the sqlite_master table has
82426 ** recently changed, so the entry for this table already exists in
82427 ** the sqlite_master table.  We do not want to create it again.
82428 **
82429 ** If the pSelect argument is not NULL, it means that this routine
82430 ** was called to create a table generated from a
82431 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82432 ** the new table will match the result set of the SELECT.
82433 */
82434 SQLITE_PRIVATE void sqlite3EndTable(
82435   Parse *pParse,          /* Parse context */
82436   Token *pCons,           /* The ',' token after the last column defn. */
82437   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82438   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82439 ){
82440   Table *p;
82441   sqlite3 *db = pParse->db;
82442   int iDb;
82443 
82444   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82445     return;
82446   }
82447   p = pParse->pNewTable;
82448   if( p==0 ) return;
82449 
82450   assert( !db->init.busy || !pSelect );
82451 
82452   iDb = sqlite3SchemaToIndex(db, p->pSchema);
82453 
82454 #ifndef SQLITE_OMIT_CHECK
82455   /* Resolve names in all CHECK constraint expressions.
82456   */
82457   if( p->pCheck ){
82458     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82459     NameContext sNC;                /* Name context for pParse->pNewTable */
82460     ExprList *pList;                /* List of all CHECK constraints */
82461     int i;                          /* Loop counter */
82462 
82463     memset(&sNC, 0, sizeof(sNC));
82464     memset(&sSrc, 0, sizeof(sSrc));
82465     sSrc.nSrc = 1;
82466     sSrc.a[0].zName = p->zName;
82467     sSrc.a[0].pTab = p;
82468     sSrc.a[0].iCursor = -1;
82469     sNC.pParse = pParse;
82470     sNC.pSrcList = &sSrc;
82471     sNC.ncFlags = NC_IsCheck;
82472     pList = p->pCheck;
82473     for(i=0; i<pList->nExpr; i++){
82474       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82475         return;
82476       }
82477     }
82478   }
82479 #endif /* !defined(SQLITE_OMIT_CHECK) */
82480 
82481   /* If the db->init.busy is 1 it means we are reading the SQL off the
82482   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
82483   ** So do not write to the disk again.  Extract the root page number
82484   ** for the table from the db->init.newTnum field.  (The page number
82485   ** should have been put there by the sqliteOpenCb routine.)
82486   */
82487   if( db->init.busy ){
82488     p->tnum = db->init.newTnum;
82489   }
82490 
82491   /* If not initializing, then create a record for the new table
82492   ** in the SQLITE_MASTER table of the database.
82493   **
82494   ** If this is a TEMPORARY table, write the entry into the auxiliary
82495   ** file instead of into the main database file.
82496   */
82497   if( !db->init.busy ){
82498     int n;
82499     Vdbe *v;
82500     char *zType;    /* "view" or "table" */
82501     char *zType2;   /* "VIEW" or "TABLE" */
82502     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82503 
82504     v = sqlite3GetVdbe(pParse);
82505     if( NEVER(v==0) ) return;
82506 
82507     sqlite3VdbeAddOp1(v, OP_Close, 0);
82508 
82509     /*
82510     ** Initialize zType for the new view or table.
82511     */
82512     if( p->pSelect==0 ){
82513       /* A regular table */
82514       zType = "table";
82515       zType2 = "TABLE";
82516 #ifndef SQLITE_OMIT_VIEW
82517     }else{
82518       /* A view */
82519       zType = "view";
82520       zType2 = "VIEW";
82521 #endif
82522     }
82523 
82524     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82525     ** statement to populate the new table. The root-page number for the
82526     ** new table is in register pParse->regRoot.
82527     **
82528     ** Once the SELECT has been coded by sqlite3Select(), it is in a
82529     ** suitable state to query for the column names and types to be used
82530     ** by the new table.
82531     **
82532     ** A shared-cache write-lock is not required to write to the new table,
82533     ** as a schema-lock must have already been obtained to create it. Since
82534     ** a schema-lock excludes all other database users, the write-lock would
82535     ** be redundant.
82536     */
82537     if( pSelect ){
82538       SelectDest dest;
82539       Table *pSelTab;
82540 
82541       assert(pParse->nTab==1);
82542       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82543       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
82544       pParse->nTab = 2;
82545       sqlite3SelectDestInit(&dest, SRT_Table, 1);
82546       sqlite3Select(pParse, pSelect, &dest);
82547       sqlite3VdbeAddOp1(v, OP_Close, 1);
82548       if( pParse->nErr==0 ){
82549         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
82550         if( pSelTab==0 ) return;
82551         assert( p->aCol==0 );
82552         p->nCol = pSelTab->nCol;
82553         p->aCol = pSelTab->aCol;
82554         pSelTab->nCol = 0;
82555         pSelTab->aCol = 0;
82556         sqlite3DeleteTable(db, pSelTab);
82557       }
82558     }
82559 
82560     /* Compute the complete text of the CREATE statement */
82561     if( pSelect ){
82562       zStmt = createTableStmt(db, p);
82563     }else{
82564       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82565       zStmt = sqlite3MPrintf(db,
82566           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82567       );
82568     }
82569 
82570     /* A slot for the record has already been allocated in the
82571     ** SQLITE_MASTER table.  We just need to update that slot with all
82572     ** the information we've collected.
82573     */
82574     sqlite3NestedParse(pParse,
82575       "UPDATE %Q.%s "
82576          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82577        "WHERE rowid=#%d",
82578       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82579       zType,
82580       p->zName,
82581       p->zName,
82582       pParse->regRoot,
82583       zStmt,
82584       pParse->regRowid
82585     );
82586     sqlite3DbFree(db, zStmt);
82587     sqlite3ChangeCookie(pParse, iDb);
82588 
82589 #ifndef SQLITE_OMIT_AUTOINCREMENT
82590     /* Check to see if we need to create an sqlite_sequence table for
82591     ** keeping track of autoincrement keys.
82592     */
82593     if( p->tabFlags & TF_Autoincrement ){
82594       Db *pDb = &db->aDb[iDb];
82595       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82596       if( pDb->pSchema->pSeqTab==0 ){
82597         sqlite3NestedParse(pParse,
82598           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
82599           pDb->zName
82600         );
82601       }
82602     }
82603 #endif
82604 
82605     /* Reparse everything to update our internal data structures */
82606     sqlite3VdbeAddParseSchemaOp(v, iDb,
82607                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
82608   }
82609 
82610 
82611   /* Add the table to the in-memory representation of the database.
82612   */
82613   if( db->init.busy ){
82614     Table *pOld;
82615     Schema *pSchema = p->pSchema;
82616     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82617     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
82618                              sqlite3Strlen30(p->zName),p);
82619     if( pOld ){
82620       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82621       db->mallocFailed = 1;
82622       return;
82623     }
82624     pParse->pNewTable = 0;
82625     db->flags |= SQLITE_InternChanges;
82626 
82627 #ifndef SQLITE_OMIT_ALTERTABLE
82628     if( !p->pSelect ){
82629       const char *zName = (const char *)pParse->sNameToken.z;
82630       int nName;
82631       assert( !pSelect && pCons && pEnd );
82632       if( pCons->z==0 ){
82633         pCons = pEnd;
82634       }
82635       nName = (int)((const char *)pCons->z - zName);
82636       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
82637     }
82638 #endif
82639   }
82640 }
82641 
82642 #ifndef SQLITE_OMIT_VIEW
82643 /*
82644 ** The parser calls this routine in order to create a new VIEW
82645 */
82646 SQLITE_PRIVATE void sqlite3CreateView(
82647   Parse *pParse,     /* The parsing context */
82648   Token *pBegin,     /* The CREATE token that begins the statement */
82649   Token *pName1,     /* The token that holds the name of the view */
82650   Token *pName2,     /* The token that holds the name of the view */
82651   Select *pSelect,   /* A SELECT statement that will become the new view */
82652   int isTemp,        /* TRUE for a TEMPORARY view */
82653   int noErr          /* Suppress error messages if VIEW already exists */
82654 ){
82655   Table *p;
82656   int n;
82657   const char *z;
82658   Token sEnd;
82659   DbFixer sFix;
82660   Token *pName = 0;
82661   int iDb;
82662   sqlite3 *db = pParse->db;
82663 
82664   if( pParse->nVar>0 ){
82665     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
82666     sqlite3SelectDelete(db, pSelect);
82667     return;
82668   }
82669   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82670   p = pParse->pNewTable;
82671   if( p==0 || pParse->nErr ){
82672     sqlite3SelectDelete(db, pSelect);
82673     return;
82674   }
82675   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82676   iDb = sqlite3SchemaToIndex(db, p->pSchema);
82677   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
82678     && sqlite3FixSelect(&sFix, pSelect)
82679   ){
82680     sqlite3SelectDelete(db, pSelect);
82681     return;
82682   }
82683 
82684   /* Make a copy of the entire SELECT statement that defines the view.
82685   ** This will force all the Expr.token.z values to be dynamically
82686   ** allocated rather than point to the input string - which means that
82687   ** they will persist after the current sqlite3_exec() call returns.
82688   */
82689   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82690   sqlite3SelectDelete(db, pSelect);
82691   if( db->mallocFailed ){
82692     return;
82693   }
82694   if( !db->init.busy ){
82695     sqlite3ViewGetColumnNames(pParse, p);
82696   }
82697 
82698   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82699   ** the end.
82700   */
82701   sEnd = pParse->sLastToken;
82702   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82703     sEnd.z += sEnd.n;
82704   }
82705   sEnd.n = 0;
82706   n = (int)(sEnd.z - pBegin->z);
82707   z = pBegin->z;
82708   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
82709   sEnd.z = &z[n-1];
82710   sEnd.n = 1;
82711 
82712   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
82713   sqlite3EndTable(pParse, 0, &sEnd, 0);
82714   return;
82715 }
82716 #endif /* SQLITE_OMIT_VIEW */
82717 
82718 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82719 /*
82720 ** The Table structure pTable is really a VIEW.  Fill in the names of
82721 ** the columns of the view in the pTable structure.  Return the number
82722 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82723 */
82724 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
82725   Table *pSelTab;   /* A fake table from which we get the result set */
82726   Select *pSel;     /* Copy of the SELECT that implements the view */
82727   int nErr = 0;     /* Number of errors encountered */
82728   int n;            /* Temporarily holds the number of cursors assigned */
82729   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
82730   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82731 
82732   assert( pTable );
82733 
82734 #ifndef SQLITE_OMIT_VIRTUALTABLE
82735   if( sqlite3VtabCallConnect(pParse, pTable) ){
82736     return SQLITE_ERROR;
82737   }
82738   if( IsVirtual(pTable) ) return 0;
82739 #endif
82740 
82741 #ifndef SQLITE_OMIT_VIEW
82742   /* A positive nCol means the columns names for this view are
82743   ** already known.
82744   */
82745   if( pTable->nCol>0 ) return 0;
82746 
82747   /* A negative nCol is a special marker meaning that we are currently
82748   ** trying to compute the column names.  If we enter this routine with
82749   ** a negative nCol, it means two or more views form a loop, like this:
82750   **
82751   **     CREATE VIEW one AS SELECT * FROM two;
82752   **     CREATE VIEW two AS SELECT * FROM one;
82753   **
82754   ** Actually, the error above is now caught prior to reaching this point.
82755   ** But the following test is still important as it does come up
82756   ** in the following:
82757   **
82758   **     CREATE TABLE main.ex1(a);
82759   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82760   **     SELECT * FROM temp.ex1;
82761   */
82762   if( pTable->nCol<0 ){
82763     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82764     return 1;
82765   }
82766   assert( pTable->nCol>=0 );
82767 
82768   /* If we get this far, it means we need to compute the table names.
82769   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
82770   ** "*" elements in the results set of the view and will assign cursors
82771   ** to the elements of the FROM clause.  But we do not want these changes
82772   ** to be permanent.  So the computation is done on a copy of the SELECT
82773   ** statement that defines the view.
82774   */
82775   assert( pTable->pSelect );
82776   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
82777   if( pSel ){
82778     u8 enableLookaside = db->lookaside.bEnabled;
82779     n = pParse->nTab;
82780     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
82781     pTable->nCol = -1;
82782     db->lookaside.bEnabled = 0;
82783 #ifndef SQLITE_OMIT_AUTHORIZATION
82784     xAuth = db->xAuth;
82785     db->xAuth = 0;
82786     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82787     db->xAuth = xAuth;
82788 #else
82789     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82790 #endif
82791     db->lookaside.bEnabled = enableLookaside;
82792     pParse->nTab = n;
82793     if( pSelTab ){
82794       assert( pTable->aCol==0 );
82795       pTable->nCol = pSelTab->nCol;
82796       pTable->aCol = pSelTab->aCol;
82797       pSelTab->nCol = 0;
82798       pSelTab->aCol = 0;
82799       sqlite3DeleteTable(db, pSelTab);
82800       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
82801       pTable->pSchema->flags |= DB_UnresetViews;
82802     }else{
82803       pTable->nCol = 0;
82804       nErr++;
82805     }
82806     sqlite3SelectDelete(db, pSel);
82807   } else {
82808     nErr++;
82809   }
82810 #endif /* SQLITE_OMIT_VIEW */
82811   return nErr;
82812 }
82813 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
82814 
82815 #ifndef SQLITE_OMIT_VIEW
82816 /*
82817 ** Clear the column names from every VIEW in database idx.
82818 */
82819 static void sqliteViewResetAll(sqlite3 *db, int idx){
82820   HashElem *i;
82821   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
82822   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
82823   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
82824     Table *pTab = sqliteHashData(i);
82825     if( pTab->pSelect ){
82826       sqliteDeleteColumnNames(db, pTab);
82827       pTab->aCol = 0;
82828       pTab->nCol = 0;
82829     }
82830   }
82831   DbClearProperty(db, idx, DB_UnresetViews);
82832 }
82833 #else
82834 # define sqliteViewResetAll(A,B)
82835 #endif /* SQLITE_OMIT_VIEW */
82836 
82837 /*
82838 ** This function is called by the VDBE to adjust the internal schema
82839 ** used by SQLite when the btree layer moves a table root page. The
82840 ** root-page of a table or index in database iDb has changed from iFrom
82841 ** to iTo.
82842 **
82843 ** Ticket #1728:  The symbol table might still contain information
82844 ** on tables and/or indices that are the process of being deleted.
82845 ** If you are unlucky, one of those deleted indices or tables might
82846 ** have the same rootpage number as the real table or index that is
82847 ** being moved.  So we cannot stop searching after the first match
82848 ** because the first match might be for one of the deleted indices
82849 ** or tables and not the table/index that is actually being moved.
82850 ** We must continue looping until all tables and indices with
82851 ** rootpage==iFrom have been converted to have a rootpage of iTo
82852 ** in order to be certain that we got the right one.
82853 */
82854 #ifndef SQLITE_OMIT_AUTOVACUUM
82855 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
82856   HashElem *pElem;
82857   Hash *pHash;
82858   Db *pDb;
82859 
82860   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82861   pDb = &db->aDb[iDb];
82862   pHash = &pDb->pSchema->tblHash;
82863   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82864     Table *pTab = sqliteHashData(pElem);
82865     if( pTab->tnum==iFrom ){
82866       pTab->tnum = iTo;
82867     }
82868   }
82869   pHash = &pDb->pSchema->idxHash;
82870   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
82871     Index *pIdx = sqliteHashData(pElem);
82872     if( pIdx->tnum==iFrom ){
82873       pIdx->tnum = iTo;
82874     }
82875   }
82876 }
82877 #endif
82878 
82879 /*
82880 ** Write code to erase the table with root-page iTable from database iDb.
82881 ** Also write code to modify the sqlite_master table and internal schema
82882 ** if a root-page of another table is moved by the btree-layer whilst
82883 ** erasing iTable (this can happen with an auto-vacuum database).
82884 */
82885 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
82886   Vdbe *v = sqlite3GetVdbe(pParse);
82887   int r1 = sqlite3GetTempReg(pParse);
82888   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
82889   sqlite3MayAbort(pParse);
82890 #ifndef SQLITE_OMIT_AUTOVACUUM
82891   /* OP_Destroy stores an in integer r1. If this integer
82892   ** is non-zero, then it is the root page number of a table moved to
82893   ** location iTable. The following code modifies the sqlite_master table to
82894   ** reflect this.
82895   **
82896   ** The "#NNN" in the SQL is a special constant that means whatever value
82897   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
82898   ** token for additional information.
82899   */
82900   sqlite3NestedParse(pParse,
82901      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
82902      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
82903 #endif
82904   sqlite3ReleaseTempReg(pParse, r1);
82905 }
82906 
82907 /*
82908 ** Write VDBE code to erase table pTab and all associated indices on disk.
82909 ** Code to update the sqlite_master tables and internal schema definitions
82910 ** in case a root-page belonging to another table is moved by the btree layer
82911 ** is also added (this can happen with an auto-vacuum database).
82912 */
82913 static void destroyTable(Parse *pParse, Table *pTab){
82914 #ifdef SQLITE_OMIT_AUTOVACUUM
82915   Index *pIdx;
82916   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82917   destroyRootPage(pParse, pTab->tnum, iDb);
82918   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82919     destroyRootPage(pParse, pIdx->tnum, iDb);
82920   }
82921 #else
82922   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
82923   ** is not defined), then it is important to call OP_Destroy on the
82924   ** table and index root-pages in order, starting with the numerically
82925   ** largest root-page number. This guarantees that none of the root-pages
82926   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
82927   ** following were coded:
82928   **
82929   ** OP_Destroy 4 0
82930   ** ...
82931   ** OP_Destroy 5 0
82932   **
82933   ** and root page 5 happened to be the largest root-page number in the
82934   ** database, then root page 5 would be moved to page 4 by the
82935   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
82936   ** a free-list page.
82937   */
82938   int iTab = pTab->tnum;
82939   int iDestroyed = 0;
82940 
82941   while( 1 ){
82942     Index *pIdx;
82943     int iLargest = 0;
82944 
82945     if( iDestroyed==0 || iTab<iDestroyed ){
82946       iLargest = iTab;
82947     }
82948     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82949       int iIdx = pIdx->tnum;
82950       assert( pIdx->pSchema==pTab->pSchema );
82951       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
82952         iLargest = iIdx;
82953       }
82954     }
82955     if( iLargest==0 ){
82956       return;
82957     }else{
82958       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82959       assert( iDb>=0 && iDb<pParse->db->nDb );
82960       destroyRootPage(pParse, iLargest, iDb);
82961       iDestroyed = iLargest;
82962     }
82963   }
82964 #endif
82965 }
82966 
82967 /*
82968 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
82969 ** after a DROP INDEX or DROP TABLE command.
82970 */
82971 static void sqlite3ClearStatTables(
82972   Parse *pParse,         /* The parsing context */
82973   int iDb,               /* The database number */
82974   const char *zType,     /* "idx" or "tbl" */
82975   const char *zName      /* Name of index or table */
82976 ){
82977   int i;
82978   const char *zDbName = pParse->db->aDb[iDb].zName;
82979   for(i=1; i<=3; i++){
82980     char zTab[24];
82981     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
82982     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
82983       sqlite3NestedParse(pParse,
82984         "DELETE FROM %Q.%s WHERE %s=%Q",
82985         zDbName, zTab, zType, zName
82986       );
82987     }
82988   }
82989 }
82990 
82991 /*
82992 ** Generate code to drop a table.
82993 */
82994 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
82995   Vdbe *v;
82996   sqlite3 *db = pParse->db;
82997   Trigger *pTrigger;
82998   Db *pDb = &db->aDb[iDb];
82999 
83000   v = sqlite3GetVdbe(pParse);
83001   assert( v!=0 );
83002   sqlite3BeginWriteOperation(pParse, 1, iDb);
83003 
83004 #ifndef SQLITE_OMIT_VIRTUALTABLE
83005   if( IsVirtual(pTab) ){
83006     sqlite3VdbeAddOp0(v, OP_VBegin);
83007   }
83008 #endif
83009 
83010   /* Drop all triggers associated with the table being dropped. Code
83011   ** is generated to remove entries from sqlite_master and/or
83012   ** sqlite_temp_master if required.
83013   */
83014   pTrigger = sqlite3TriggerList(pParse, pTab);
83015   while( pTrigger ){
83016     assert( pTrigger->pSchema==pTab->pSchema ||
83017         pTrigger->pSchema==db->aDb[1].pSchema );
83018     sqlite3DropTriggerPtr(pParse, pTrigger);
83019     pTrigger = pTrigger->pNext;
83020   }
83021 
83022 #ifndef SQLITE_OMIT_AUTOINCREMENT
83023   /* Remove any entries of the sqlite_sequence table associated with
83024   ** the table being dropped. This is done before the table is dropped
83025   ** at the btree level, in case the sqlite_sequence table needs to
83026   ** move as a result of the drop (can happen in auto-vacuum mode).
83027   */
83028   if( pTab->tabFlags & TF_Autoincrement ){
83029     sqlite3NestedParse(pParse,
83030       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
83031       pDb->zName, pTab->zName
83032     );
83033   }
83034 #endif
83035 
83036   /* Drop all SQLITE_MASTER table and index entries that refer to the
83037   ** table. The program name loops through the master table and deletes
83038   ** every row that refers to a table of the same name as the one being
83039   ** dropped. Triggers are handled separately because a trigger can be
83040   ** created in the temp database that refers to a table in another
83041   ** database.
83042   */
83043   sqlite3NestedParse(pParse,
83044       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
83045       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
83046   if( !isView && !IsVirtual(pTab) ){
83047     destroyTable(pParse, pTab);
83048   }
83049 
83050   /* Remove the table entry from SQLite's internal schema and modify
83051   ** the schema cookie.
83052   */
83053   if( IsVirtual(pTab) ){
83054     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
83055   }
83056   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
83057   sqlite3ChangeCookie(pParse, iDb);
83058   sqliteViewResetAll(db, iDb);
83059 }
83060 
83061 /*
83062 ** This routine is called to do the work of a DROP TABLE statement.
83063 ** pName is the name of the table to be dropped.
83064 */
83065 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
83066   Table *pTab;
83067   Vdbe *v;
83068   sqlite3 *db = pParse->db;
83069   int iDb;
83070 
83071   if( db->mallocFailed ){
83072     goto exit_drop_table;
83073   }
83074   assert( pParse->nErr==0 );
83075   assert( pName->nSrc==1 );
83076   if( noErr ) db->suppressErr++;
83077   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
83078   if( noErr ) db->suppressErr--;
83079 
83080   if( pTab==0 ){
83081     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83082     goto exit_drop_table;
83083   }
83084   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83085   assert( iDb>=0 && iDb<db->nDb );
83086 
83087   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
83088   ** it is initialized.
83089   */
83090   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
83091     goto exit_drop_table;
83092   }
83093 #ifndef SQLITE_OMIT_AUTHORIZATION
83094   {
83095     int code;
83096     const char *zTab = SCHEMA_TABLE(iDb);
83097     const char *zDb = db->aDb[iDb].zName;
83098     const char *zArg2 = 0;
83099     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
83100       goto exit_drop_table;
83101     }
83102     if( isView ){
83103       if( !OMIT_TEMPDB && iDb==1 ){
83104         code = SQLITE_DROP_TEMP_VIEW;
83105       }else{
83106         code = SQLITE_DROP_VIEW;
83107       }
83108 #ifndef SQLITE_OMIT_VIRTUALTABLE
83109     }else if( IsVirtual(pTab) ){
83110       code = SQLITE_DROP_VTABLE;
83111       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
83112 #endif
83113     }else{
83114       if( !OMIT_TEMPDB && iDb==1 ){
83115         code = SQLITE_DROP_TEMP_TABLE;
83116       }else{
83117         code = SQLITE_DROP_TABLE;
83118       }
83119     }
83120     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
83121       goto exit_drop_table;
83122     }
83123     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
83124       goto exit_drop_table;
83125     }
83126   }
83127 #endif
83128   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
83129     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
83130     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
83131     goto exit_drop_table;
83132   }
83133 
83134 #ifndef SQLITE_OMIT_VIEW
83135   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
83136   ** on a table.
83137   */
83138   if( isView && pTab->pSelect==0 ){
83139     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
83140     goto exit_drop_table;
83141   }
83142   if( !isView && pTab->pSelect ){
83143     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
83144     goto exit_drop_table;
83145   }
83146 #endif
83147 
83148   /* Generate code to remove the table from the master table
83149   ** on disk.
83150   */
83151   v = sqlite3GetVdbe(pParse);
83152   if( v ){
83153     sqlite3BeginWriteOperation(pParse, 1, iDb);
83154     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
83155     sqlite3FkDropTable(pParse, pName, pTab);
83156     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
83157   }
83158 
83159 exit_drop_table:
83160   sqlite3SrcListDelete(db, pName);
83161 }
83162 
83163 /*
83164 ** This routine is called to create a new foreign key on the table
83165 ** currently under construction.  pFromCol determines which columns
83166 ** in the current table point to the foreign key.  If pFromCol==0 then
83167 ** connect the key to the last column inserted.  pTo is the name of
83168 ** the table referred to.  pToCol is a list of tables in the other
83169 ** pTo table that the foreign key points to.  flags contains all
83170 ** information about the conflict resolution algorithms specified
83171 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
83172 **
83173 ** An FKey structure is created and added to the table currently
83174 ** under construction in the pParse->pNewTable field.
83175 **
83176 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
83177 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
83178 */
83179 SQLITE_PRIVATE void sqlite3CreateForeignKey(
83180   Parse *pParse,       /* Parsing context */
83181   ExprList *pFromCol,  /* Columns in this table that point to other table */
83182   Token *pTo,          /* Name of the other table */
83183   ExprList *pToCol,    /* Columns in the other table */
83184   int flags            /* Conflict resolution algorithms. */
83185 ){
83186   sqlite3 *db = pParse->db;
83187 #ifndef SQLITE_OMIT_FOREIGN_KEY
83188   FKey *pFKey = 0;
83189   FKey *pNextTo;
83190   Table *p = pParse->pNewTable;
83191   int nByte;
83192   int i;
83193   int nCol;
83194   char *z;
83195 
83196   assert( pTo!=0 );
83197   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
83198   if( pFromCol==0 ){
83199     int iCol = p->nCol-1;
83200     if( NEVER(iCol<0) ) goto fk_end;
83201     if( pToCol && pToCol->nExpr!=1 ){
83202       sqlite3ErrorMsg(pParse, "foreign key on %s"
83203          " should reference only one column of table %T",
83204          p->aCol[iCol].zName, pTo);
83205       goto fk_end;
83206     }
83207     nCol = 1;
83208   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
83209     sqlite3ErrorMsg(pParse,
83210         "number of columns in foreign key does not match the number of "
83211         "columns in the referenced table");
83212     goto fk_end;
83213   }else{
83214     nCol = pFromCol->nExpr;
83215   }
83216   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83217   if( pToCol ){
83218     for(i=0; i<pToCol->nExpr; i++){
83219       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
83220     }
83221   }
83222   pFKey = sqlite3DbMallocZero(db, nByte );
83223   if( pFKey==0 ){
83224     goto fk_end;
83225   }
83226   pFKey->pFrom = p;
83227   pFKey->pNextFrom = p->pFKey;
83228   z = (char*)&pFKey->aCol[nCol];
83229   pFKey->zTo = z;
83230   memcpy(z, pTo->z, pTo->n);
83231   z[pTo->n] = 0;
83232   sqlite3Dequote(z);
83233   z += pTo->n+1;
83234   pFKey->nCol = nCol;
83235   if( pFromCol==0 ){
83236     pFKey->aCol[0].iFrom = p->nCol-1;
83237   }else{
83238     for(i=0; i<nCol; i++){
83239       int j;
83240       for(j=0; j<p->nCol; j++){
83241         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83242           pFKey->aCol[i].iFrom = j;
83243           break;
83244         }
83245       }
83246       if( j>=p->nCol ){
83247         sqlite3ErrorMsg(pParse,
83248           "unknown column \"%s\" in foreign key definition",
83249           pFromCol->a[i].zName);
83250         goto fk_end;
83251       }
83252     }
83253   }
83254   if( pToCol ){
83255     for(i=0; i<nCol; i++){
83256       int n = sqlite3Strlen30(pToCol->a[i].zName);
83257       pFKey->aCol[i].zCol = z;
83258       memcpy(z, pToCol->a[i].zName, n);
83259       z[n] = 0;
83260       z += n+1;
83261     }
83262   }
83263   pFKey->isDeferred = 0;
83264   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83265   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83266 
83267   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
83268   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
83269       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
83270   );
83271   if( pNextTo==pFKey ){
83272     db->mallocFailed = 1;
83273     goto fk_end;
83274   }
83275   if( pNextTo ){
83276     assert( pNextTo->pPrevTo==0 );
83277     pFKey->pNextTo = pNextTo;
83278     pNextTo->pPrevTo = pFKey;
83279   }
83280 
83281   /* Link the foreign key to the table as the last step.
83282   */
83283   p->pFKey = pFKey;
83284   pFKey = 0;
83285 
83286 fk_end:
83287   sqlite3DbFree(db, pFKey);
83288 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
83289   sqlite3ExprListDelete(db, pFromCol);
83290   sqlite3ExprListDelete(db, pToCol);
83291 }
83292 
83293 /*
83294 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83295 ** clause is seen as part of a foreign key definition.  The isDeferred
83296 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83297 ** The behavior of the most recently created foreign key is adjusted
83298 ** accordingly.
83299 */
83300 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
83301 #ifndef SQLITE_OMIT_FOREIGN_KEY
83302   Table *pTab;
83303   FKey *pFKey;
83304   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83305   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83306   pFKey->isDeferred = (u8)isDeferred;
83307 #endif
83308 }
83309 
83310 /*
83311 ** Generate code that will erase and refill index *pIdx.  This is
83312 ** used to initialize a newly created index or to recompute the
83313 ** content of an index in response to a REINDEX command.
83314 **
83315 ** if memRootPage is not negative, it means that the index is newly
83316 ** created.  The register specified by memRootPage contains the
83317 ** root page number of the index.  If memRootPage is negative, then
83318 ** the index already exists and must be cleared before being refilled and
83319 ** the root page number of the index is taken from pIndex->tnum.
83320 */
83321 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83322   Table *pTab = pIndex->pTable;  /* The table that is indexed */
83323   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83324   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83325   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83326   int addr1;                     /* Address of top of loop */
83327   int addr2;                     /* Address to jump to for next iteration */
83328   int tnum;                      /* Root page of index */
83329   Vdbe *v;                       /* Generate code into this virtual machine */
83330   KeyInfo *pKey;                 /* KeyInfo for index */
83331   int regRecord;                 /* Register holding assemblied index record */
83332   sqlite3 *db = pParse->db;      /* The database connection */
83333   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83334 
83335 #ifndef SQLITE_OMIT_AUTHORIZATION
83336   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
83337       db->aDb[iDb].zName ) ){
83338     return;
83339   }
83340 #endif
83341 
83342   /* Require a write-lock on the table to perform this operation */
83343   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83344 
83345   v = sqlite3GetVdbe(pParse);
83346   if( v==0 ) return;
83347   if( memRootPage>=0 ){
83348     tnum = memRootPage;
83349   }else{
83350     tnum = pIndex->tnum;
83351     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83352   }
83353   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
83354   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
83355                     (char *)pKey, P4_KEYINFO_HANDOFF);
83356   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
83357 
83358   /* Open the sorter cursor if we are to use one. */
83359   iSorter = pParse->nTab++;
83360   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83361 
83362   /* Open the table. Loop through all rows of the table, inserting index
83363   ** records into the sorter. */
83364   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83365   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83366   regRecord = sqlite3GetTempReg(pParse);
83367 
83368   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83369   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83370   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83371   sqlite3VdbeJumpHere(v, addr1);
83372   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83373   if( pIndex->onError!=OE_None ){
83374     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
83375     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
83376     addr2 = sqlite3VdbeCurrentAddr(v);
83377     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83378     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
83379         OE_Abort, "indexed columns are not unique", P4_STATIC
83380     );
83381   }else{
83382     addr2 = sqlite3VdbeCurrentAddr(v);
83383   }
83384   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83385   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83386   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83387   sqlite3ReleaseTempReg(pParse, regRecord);
83388   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83389   sqlite3VdbeJumpHere(v, addr1);
83390 
83391   sqlite3VdbeAddOp1(v, OP_Close, iTab);
83392   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
83393   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
83394 }
83395 
83396 /*
83397 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
83398 ** and pTblList is the name of the table that is to be indexed.  Both will
83399 ** be NULL for a primary key or an index that is created to satisfy a
83400 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83401 ** as the table to be indexed.  pParse->pNewTable is a table that is
83402 ** currently being constructed by a CREATE TABLE statement.
83403 **
83404 ** pList is a list of columns to be indexed.  pList will be NULL if this
83405 ** is a primary key or unique-constraint on the most recent column added
83406 ** to the table currently under construction.
83407 **
83408 ** If the index is created successfully, return a pointer to the new Index
83409 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
83410 ** as the tables primary key (Index.autoIndex==2).
83411 */
83412 SQLITE_PRIVATE Index *sqlite3CreateIndex(
83413   Parse *pParse,     /* All information about this parse */
83414   Token *pName1,     /* First part of index name. May be NULL */
83415   Token *pName2,     /* Second part of index name. May be NULL */
83416   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83417   ExprList *pList,   /* A list of columns to be indexed */
83418   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83419   Token *pStart,     /* The CREATE token that begins this statement */
83420   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83421   int sortOrder,     /* Sort order of primary key when pList==NULL */
83422   int ifNotExist     /* Omit error if index already exists */
83423 ){
83424   Index *pRet = 0;     /* Pointer to return */
83425   Table *pTab = 0;     /* Table to be indexed */
83426   Index *pIndex = 0;   /* The index to be created */
83427   char *zName = 0;     /* Name of the index */
83428   int nName;           /* Number of characters in zName */
83429   int i, j;
83430   Token nullId;        /* Fake token for an empty ID list */
83431   DbFixer sFix;        /* For assigning database names to pTable */
83432   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83433   sqlite3 *db = pParse->db;
83434   Db *pDb;             /* The specific table containing the indexed database */
83435   int iDb;             /* Index of the database that is being written */
83436   Token *pName = 0;    /* Unqualified name of the index to create */
83437   struct ExprList_item *pListItem; /* For looping over pList */
83438   int nCol;
83439   int nExtra = 0;
83440   char *zExtra;
83441 
83442   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83443   assert( pParse->nErr==0 );      /* Never called with prior errors */
83444   if( db->mallocFailed || IN_DECLARE_VTAB ){
83445     goto exit_create_index;
83446   }
83447   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83448     goto exit_create_index;
83449   }
83450 
83451   /*
83452   ** Find the table that is to be indexed.  Return early if not found.
83453   */
83454   if( pTblName!=0 ){
83455 
83456     /* Use the two-part index name to determine the database
83457     ** to search for the table. 'Fix' the table name to this db
83458     ** before looking up the table.
83459     */
83460     assert( pName1 && pName2 );
83461     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83462     if( iDb<0 ) goto exit_create_index;
83463     assert( pName && pName->z );
83464 
83465 #ifndef SQLITE_OMIT_TEMPDB
83466     /* If the index name was unqualified, check if the table
83467     ** is a temp table. If so, set the database to 1. Do not do this
83468     ** if initialising a database schema.
83469     */
83470     if( !db->init.busy ){
83471       pTab = sqlite3SrcListLookup(pParse, pTblName);
83472       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83473         iDb = 1;
83474       }
83475     }
83476 #endif
83477 
83478     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
83479         sqlite3FixSrcList(&sFix, pTblName)
83480     ){
83481       /* Because the parser constructs pTblName from a single identifier,
83482       ** sqlite3FixSrcList can never fail. */
83483       assert(0);
83484     }
83485     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
83486     assert( db->mallocFailed==0 || pTab==0 );
83487     if( pTab==0 ) goto exit_create_index;
83488     assert( db->aDb[iDb].pSchema==pTab->pSchema );
83489   }else{
83490     assert( pName==0 );
83491     assert( pStart==0 );
83492     pTab = pParse->pNewTable;
83493     if( !pTab ) goto exit_create_index;
83494     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83495   }
83496   pDb = &db->aDb[iDb];
83497 
83498   assert( pTab!=0 );
83499   assert( pParse->nErr==0 );
83500   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
83501        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
83502     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83503     goto exit_create_index;
83504   }
83505 #ifndef SQLITE_OMIT_VIEW
83506   if( pTab->pSelect ){
83507     sqlite3ErrorMsg(pParse, "views may not be indexed");
83508     goto exit_create_index;
83509   }
83510 #endif
83511 #ifndef SQLITE_OMIT_VIRTUALTABLE
83512   if( IsVirtual(pTab) ){
83513     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
83514     goto exit_create_index;
83515   }
83516 #endif
83517 
83518   /*
83519   ** Find the name of the index.  Make sure there is not already another
83520   ** index or table with the same name.
83521   **
83522   ** Exception:  If we are reading the names of permanent indices from the
83523   ** sqlite_master table (because some other process changed the schema) and
83524   ** one of the index names collides with the name of a temporary table or
83525   ** index, then we will continue to process this index.
83526   **
83527   ** If pName==0 it means that we are
83528   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83529   ** own name.
83530   */
83531   if( pName ){
83532     zName = sqlite3NameFromToken(db, pName);
83533     if( zName==0 ) goto exit_create_index;
83534     assert( pName->z!=0 );
83535     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83536       goto exit_create_index;
83537     }
83538     if( !db->init.busy ){
83539       if( sqlite3FindTable(db, zName, 0)!=0 ){
83540         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
83541         goto exit_create_index;
83542       }
83543     }
83544     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
83545       if( !ifNotExist ){
83546         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
83547       }else{
83548         assert( !db->init.busy );
83549         sqlite3CodeVerifySchema(pParse, iDb);
83550       }
83551       goto exit_create_index;
83552     }
83553   }else{
83554     int n;
83555     Index *pLoop;
83556     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83557     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
83558     if( zName==0 ){
83559       goto exit_create_index;
83560     }
83561   }
83562 
83563   /* Check for authorization to create an index.
83564   */
83565 #ifndef SQLITE_OMIT_AUTHORIZATION
83566   {
83567     const char *zDb = pDb->zName;
83568     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83569       goto exit_create_index;
83570     }
83571     i = SQLITE_CREATE_INDEX;
83572     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
83573     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83574       goto exit_create_index;
83575     }
83576   }
83577 #endif
83578 
83579   /* If pList==0, it means this routine was called to make a primary
83580   ** key out of the last column added to the table under construction.
83581   ** So create a fake list to simulate this.
83582   */
83583   if( pList==0 ){
83584     nullId.z = pTab->aCol[pTab->nCol-1].zName;
83585     nullId.n = sqlite3Strlen30((char*)nullId.z);
83586     pList = sqlite3ExprListAppend(pParse, 0, 0);
83587     if( pList==0 ) goto exit_create_index;
83588     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
83589     pList->a[0].sortOrder = (u8)sortOrder;
83590   }
83591 
83592   /* Figure out how many bytes of space are required to store explicitly
83593   ** specified collation sequence names.
83594   */
83595   for(i=0; i<pList->nExpr; i++){
83596     Expr *pExpr = pList->a[i].pExpr;
83597     if( pExpr ){
83598       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
83599       if( pColl ){
83600         nExtra += (1 + sqlite3Strlen30(pColl->zName));
83601       }
83602     }
83603   }
83604 
83605   /*
83606   ** Allocate the index structure.
83607   */
83608   nName = sqlite3Strlen30(zName);
83609   nCol = pList->nExpr;
83610   pIndex = sqlite3DbMallocZero(db,
83611       ROUND8(sizeof(Index)) +              /* Index structure  */
83612       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
83613       sizeof(char *)*nCol +                /* Index.azColl     */
83614       sizeof(int)*nCol +                   /* Index.aiColumn   */
83615       sizeof(u8)*nCol +                    /* Index.aSortOrder */
83616       nName + 1 +                          /* Index.zName      */
83617       nExtra                               /* Collation sequence names */
83618   );
83619   if( db->mallocFailed ){
83620     goto exit_create_index;
83621   }
83622   zExtra = (char*)pIndex;
83623   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
83624   pIndex->azColl = (char**)
83625      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
83626   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
83627   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
83628   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83629   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83630   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83631   zExtra = (char *)(&pIndex->zName[nName+1]);
83632   memcpy(pIndex->zName, zName, nName+1);
83633   pIndex->pTable = pTab;
83634   pIndex->nColumn = pList->nExpr;
83635   pIndex->onError = (u8)onError;
83636   pIndex->autoIndex = (u8)(pName==0);
83637   pIndex->pSchema = db->aDb[iDb].pSchema;
83638   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83639 
83640   /* Check to see if we should honor DESC requests on index columns
83641   */
83642   if( pDb->pSchema->file_format>=4 ){
83643     sortOrderMask = -1;   /* Honor DESC */
83644   }else{
83645     sortOrderMask = 0;    /* Ignore DESC */
83646   }
83647 
83648   /* Scan the names of the columns of the table to be indexed and
83649   ** load the column indices into the Index structure.  Report an error
83650   ** if any column is not found.
83651   **
83652   ** TODO:  Add a test to make sure that the same column is not named
83653   ** more than once within the same index.  Only the first instance of
83654   ** the column will ever be used by the optimizer.  Note that using the
83655   ** same column more than once cannot be an error because that would
83656   ** break backwards compatibility - it needs to be a warning.
83657   */
83658   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83659     const char *zColName = pListItem->zName;
83660     Column *pTabCol;
83661     int requestedSortOrder;
83662     CollSeq *pColl;                /* Collating sequence */
83663     char *zColl;                   /* Collation sequence name */
83664 
83665     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83666       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
83667     }
83668     if( j>=pTab->nCol ){
83669       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
83670         pTab->zName, zColName);
83671       pParse->checkSchema = 1;
83672       goto exit_create_index;
83673     }
83674     pIndex->aiColumn[i] = j;
83675     if( pListItem->pExpr
83676      && (pColl = sqlite3ExprCollSeq(pParse, pListItem->pExpr))!=0
83677     ){
83678       int nColl;
83679       zColl = pColl->zName;
83680       nColl = sqlite3Strlen30(zColl) + 1;
83681       assert( nExtra>=nColl );
83682       memcpy(zExtra, zColl, nColl);
83683       zColl = zExtra;
83684       zExtra += nColl;
83685       nExtra -= nColl;
83686     }else{
83687       zColl = pTab->aCol[j].zColl;
83688       if( !zColl ){
83689         zColl = "BINARY";
83690       }
83691     }
83692     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
83693       goto exit_create_index;
83694     }
83695     pIndex->azColl[i] = zColl;
83696     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83697     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83698   }
83699   sqlite3DefaultRowEst(pIndex);
83700 
83701   if( pTab==pParse->pNewTable ){
83702     /* This routine has been called to create an automatic index as a
83703     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83704     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83705     ** i.e. one of:
83706     **
83707     ** CREATE TABLE t(x PRIMARY KEY, y);
83708     ** CREATE TABLE t(x, y, UNIQUE(x, y));
83709     **
83710     ** Either way, check to see if the table already has such an index. If
83711     ** so, don't bother creating this one. This only applies to
83712     ** automatically created indices. Users can do as they wish with
83713     ** explicit indices.
83714     **
83715     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83716     ** (and thus suppressing the second one) even if they have different
83717     ** sort orders.
83718     **
83719     ** If there are different collating sequences or if the columns of
83720     ** the constraint occur in different orders, then the constraints are
83721     ** considered distinct and both result in separate indices.
83722     */
83723     Index *pIdx;
83724     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83725       int k;
83726       assert( pIdx->onError!=OE_None );
83727       assert( pIdx->autoIndex );
83728       assert( pIndex->onError!=OE_None );
83729 
83730       if( pIdx->nColumn!=pIndex->nColumn ) continue;
83731       for(k=0; k<pIdx->nColumn; k++){
83732         const char *z1;
83733         const char *z2;
83734         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83735         z1 = pIdx->azColl[k];
83736         z2 = pIndex->azColl[k];
83737         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
83738       }
83739       if( k==pIdx->nColumn ){
83740         if( pIdx->onError!=pIndex->onError ){
83741           /* This constraint creates the same index as a previous
83742           ** constraint specified somewhere in the CREATE TABLE statement.
83743           ** However the ON CONFLICT clauses are different. If both this
83744           ** constraint and the previous equivalent constraint have explicit
83745           ** ON CONFLICT clauses this is an error. Otherwise, use the
83746           ** explicitly specified behavior for the index.
83747           */
83748           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
83749             sqlite3ErrorMsg(pParse,
83750                 "conflicting ON CONFLICT clauses specified", 0);
83751           }
83752           if( pIdx->onError==OE_Default ){
83753             pIdx->onError = pIndex->onError;
83754           }
83755         }
83756         goto exit_create_index;
83757       }
83758     }
83759   }
83760 
83761   /* Link the new Index structure to its table and to the other
83762   ** in-memory database structures.
83763   */
83764   if( db->init.busy ){
83765     Index *p;
83766     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
83767     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
83768                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
83769                           pIndex);
83770     if( p ){
83771       assert( p==pIndex );  /* Malloc must have failed */
83772       db->mallocFailed = 1;
83773       goto exit_create_index;
83774     }
83775     db->flags |= SQLITE_InternChanges;
83776     if( pTblName!=0 ){
83777       pIndex->tnum = db->init.newTnum;
83778     }
83779   }
83780 
83781   /* If the db->init.busy is 0 then create the index on disk.  This
83782   ** involves writing the index into the master table and filling in the
83783   ** index with the current table contents.
83784   **
83785   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
83786   ** command.  db->init.busy is 1 when a database is opened and
83787   ** CREATE INDEX statements are read out of the master table.  In
83788   ** the latter case the index already exists on disk, which is why
83789   ** we don't want to recreate it.
83790   **
83791   ** If pTblName==0 it means this index is generated as a primary key
83792   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
83793   ** has just been created, it contains no data and the index initialization
83794   ** step can be skipped.
83795   */
83796   else{ /* if( db->init.busy==0 ) */
83797     Vdbe *v;
83798     char *zStmt;
83799     int iMem = ++pParse->nMem;
83800 
83801     v = sqlite3GetVdbe(pParse);
83802     if( v==0 ) goto exit_create_index;
83803 
83804 
83805     /* Create the rootpage for the index
83806     */
83807     sqlite3BeginWriteOperation(pParse, 1, iDb);
83808     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
83809 
83810     /* Gather the complete text of the CREATE INDEX statement into
83811     ** the zStmt variable
83812     */
83813     if( pStart ){
83814       assert( pEnd!=0 );
83815       /* A named index with an explicit CREATE INDEX statement */
83816       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
83817         onError==OE_None ? "" : " UNIQUE",
83818         (int)(pEnd->z - pName->z) + 1,
83819         pName->z);
83820     }else{
83821       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
83822       /* zStmt = sqlite3MPrintf(""); */
83823       zStmt = 0;
83824     }
83825 
83826     /* Add an entry in sqlite_master for this index
83827     */
83828     sqlite3NestedParse(pParse,
83829         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
83830         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83831         pIndex->zName,
83832         pTab->zName,
83833         iMem,
83834         zStmt
83835     );
83836     sqlite3DbFree(db, zStmt);
83837 
83838     /* Fill the index with data and reparse the schema. Code an OP_Expire
83839     ** to invalidate all pre-compiled statements.
83840     */
83841     if( pTblName ){
83842       sqlite3RefillIndex(pParse, pIndex, iMem);
83843       sqlite3ChangeCookie(pParse, iDb);
83844       sqlite3VdbeAddParseSchemaOp(v, iDb,
83845          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
83846       sqlite3VdbeAddOp1(v, OP_Expire, 0);
83847     }
83848   }
83849 
83850   /* When adding an index to the list of indices for a table, make
83851   ** sure all indices labeled OE_Replace come after all those labeled
83852   ** OE_Ignore.  This is necessary for the correct constraint check
83853   ** processing (in sqlite3GenerateConstraintChecks()) as part of
83854   ** UPDATE and INSERT statements.
83855   */
83856   if( db->init.busy || pTblName==0 ){
83857     if( onError!=OE_Replace || pTab->pIndex==0
83858          || pTab->pIndex->onError==OE_Replace){
83859       pIndex->pNext = pTab->pIndex;
83860       pTab->pIndex = pIndex;
83861     }else{
83862       Index *pOther = pTab->pIndex;
83863       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
83864         pOther = pOther->pNext;
83865       }
83866       pIndex->pNext = pOther->pNext;
83867       pOther->pNext = pIndex;
83868     }
83869     pRet = pIndex;
83870     pIndex = 0;
83871   }
83872 
83873   /* Clean up before exiting */
83874 exit_create_index:
83875   if( pIndex ){
83876     sqlite3DbFree(db, pIndex->zColAff);
83877     sqlite3DbFree(db, pIndex);
83878   }
83879   sqlite3ExprListDelete(db, pList);
83880   sqlite3SrcListDelete(db, pTblName);
83881   sqlite3DbFree(db, zName);
83882   return pRet;
83883 }
83884 
83885 /*
83886 ** Fill the Index.aiRowEst[] array with default information - information
83887 ** to be used when we have not run the ANALYZE command.
83888 **
83889 ** aiRowEst[0] is suppose to contain the number of elements in the index.
83890 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
83891 ** number of rows in the table that match any particular value of the
83892 ** first column of the index.  aiRowEst[2] is an estimate of the number
83893 ** of rows that match any particular combiniation of the first 2 columns
83894 ** of the index.  And so forth.  It must always be the case that
83895 *
83896 **           aiRowEst[N]<=aiRowEst[N-1]
83897 **           aiRowEst[N]>=1
83898 **
83899 ** Apart from that, we have little to go on besides intuition as to
83900 ** how aiRowEst[] should be initialized.  The numbers generated here
83901 ** are based on typical values found in actual indices.
83902 */
83903 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
83904   tRowcnt *a = pIdx->aiRowEst;
83905   int i;
83906   tRowcnt n;
83907   assert( a!=0 );
83908   a[0] = pIdx->pTable->nRowEst;
83909   if( a[0]<10 ) a[0] = 10;
83910   n = 10;
83911   for(i=1; i<=pIdx->nColumn; i++){
83912     a[i] = n;
83913     if( n>5 ) n--;
83914   }
83915   if( pIdx->onError!=OE_None ){
83916     a[pIdx->nColumn] = 1;
83917   }
83918 }
83919 
83920 /*
83921 ** This routine will drop an existing named index.  This routine
83922 ** implements the DROP INDEX statement.
83923 */
83924 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
83925   Index *pIndex;
83926   Vdbe *v;
83927   sqlite3 *db = pParse->db;
83928   int iDb;
83929 
83930   assert( pParse->nErr==0 );   /* Never called with prior errors */
83931   if( db->mallocFailed ){
83932     goto exit_drop_index;
83933   }
83934   assert( pName->nSrc==1 );
83935   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83936     goto exit_drop_index;
83937   }
83938   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
83939   if( pIndex==0 ){
83940     if( !ifExists ){
83941       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
83942     }else{
83943       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83944     }
83945     pParse->checkSchema = 1;
83946     goto exit_drop_index;
83947   }
83948   if( pIndex->autoIndex ){
83949     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
83950       "or PRIMARY KEY constraint cannot be dropped", 0);
83951     goto exit_drop_index;
83952   }
83953   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83954 #ifndef SQLITE_OMIT_AUTHORIZATION
83955   {
83956     int code = SQLITE_DROP_INDEX;
83957     Table *pTab = pIndex->pTable;
83958     const char *zDb = db->aDb[iDb].zName;
83959     const char *zTab = SCHEMA_TABLE(iDb);
83960     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
83961       goto exit_drop_index;
83962     }
83963     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
83964     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
83965       goto exit_drop_index;
83966     }
83967   }
83968 #endif
83969 
83970   /* Generate code to remove the index and from the master table */
83971   v = sqlite3GetVdbe(pParse);
83972   if( v ){
83973     sqlite3BeginWriteOperation(pParse, 1, iDb);
83974     sqlite3NestedParse(pParse,
83975        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
83976        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
83977     );
83978     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
83979     sqlite3ChangeCookie(pParse, iDb);
83980     destroyRootPage(pParse, pIndex->tnum, iDb);
83981     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
83982   }
83983 
83984 exit_drop_index:
83985   sqlite3SrcListDelete(db, pName);
83986 }
83987 
83988 /*
83989 ** pArray is a pointer to an array of objects. Each object in the
83990 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
83991 ** to extend the array so that there is space for a new object at the end.
83992 **
83993 ** When this function is called, *pnEntry contains the current size of
83994 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
83995 ** in total).
83996 **
83997 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
83998 ** space allocated for the new object is zeroed, *pnEntry updated to
83999 ** reflect the new size of the array and a pointer to the new allocation
84000 ** returned. *pIdx is set to the index of the new array entry in this case.
84001 **
84002 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
84003 ** unchanged and a copy of pArray returned.
84004 */
84005 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
84006   sqlite3 *db,      /* Connection to notify of malloc failures */
84007   void *pArray,     /* Array of objects.  Might be reallocated */
84008   int szEntry,      /* Size of each object in the array */
84009   int *pnEntry,     /* Number of objects currently in use */
84010   int *pIdx         /* Write the index of a new slot here */
84011 ){
84012   char *z;
84013   int n = *pnEntry;
84014   if( (n & (n-1))==0 ){
84015     int sz = (n==0) ? 1 : 2*n;
84016     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
84017     if( pNew==0 ){
84018       *pIdx = -1;
84019       return pArray;
84020     }
84021     pArray = pNew;
84022   }
84023   z = (char*)pArray;
84024   memset(&z[n * szEntry], 0, szEntry);
84025   *pIdx = n;
84026   ++*pnEntry;
84027   return pArray;
84028 }
84029 
84030 /*
84031 ** Append a new element to the given IdList.  Create a new IdList if
84032 ** need be.
84033 **
84034 ** A new IdList is returned, or NULL if malloc() fails.
84035 */
84036 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
84037   int i;
84038   if( pList==0 ){
84039     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
84040     if( pList==0 ) return 0;
84041   }
84042   pList->a = sqlite3ArrayAllocate(
84043       db,
84044       pList->a,
84045       sizeof(pList->a[0]),
84046       &pList->nId,
84047       &i
84048   );
84049   if( i<0 ){
84050     sqlite3IdListDelete(db, pList);
84051     return 0;
84052   }
84053   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
84054   return pList;
84055 }
84056 
84057 /*
84058 ** Delete an IdList.
84059 */
84060 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
84061   int i;
84062   if( pList==0 ) return;
84063   for(i=0; i<pList->nId; i++){
84064     sqlite3DbFree(db, pList->a[i].zName);
84065   }
84066   sqlite3DbFree(db, pList->a);
84067   sqlite3DbFree(db, pList);
84068 }
84069 
84070 /*
84071 ** Return the index in pList of the identifier named zId.  Return -1
84072 ** if not found.
84073 */
84074 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
84075   int i;
84076   if( pList==0 ) return -1;
84077   for(i=0; i<pList->nId; i++){
84078     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
84079   }
84080   return -1;
84081 }
84082 
84083 /*
84084 ** Expand the space allocated for the given SrcList object by
84085 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
84086 ** New slots are zeroed.
84087 **
84088 ** For example, suppose a SrcList initially contains two entries: A,B.
84089 ** To append 3 new entries onto the end, do this:
84090 **
84091 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
84092 **
84093 ** After the call above it would contain:  A, B, nil, nil, nil.
84094 ** If the iStart argument had been 1 instead of 2, then the result
84095 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
84096 ** the iStart value would be 0.  The result then would
84097 ** be: nil, nil, nil, A, B.
84098 **
84099 ** If a memory allocation fails the SrcList is unchanged.  The
84100 ** db->mallocFailed flag will be set to true.
84101 */
84102 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
84103   sqlite3 *db,       /* Database connection to notify of OOM errors */
84104   SrcList *pSrc,     /* The SrcList to be enlarged */
84105   int nExtra,        /* Number of new slots to add to pSrc->a[] */
84106   int iStart         /* Index in pSrc->a[] of first new slot */
84107 ){
84108   int i;
84109 
84110   /* Sanity checking on calling parameters */
84111   assert( iStart>=0 );
84112   assert( nExtra>=1 );
84113   assert( pSrc!=0 );
84114   assert( iStart<=pSrc->nSrc );
84115 
84116   /* Allocate additional space if needed */
84117   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
84118     SrcList *pNew;
84119     int nAlloc = pSrc->nSrc+nExtra;
84120     int nGot;
84121     pNew = sqlite3DbRealloc(db, pSrc,
84122                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
84123     if( pNew==0 ){
84124       assert( db->mallocFailed );
84125       return pSrc;
84126     }
84127     pSrc = pNew;
84128     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
84129     pSrc->nAlloc = (u16)nGot;
84130   }
84131 
84132   /* Move existing slots that come after the newly inserted slots
84133   ** out of the way */
84134   for(i=pSrc->nSrc-1; i>=iStart; i--){
84135     pSrc->a[i+nExtra] = pSrc->a[i];
84136   }
84137   pSrc->nSrc += (i16)nExtra;
84138 
84139   /* Zero the newly allocated slots */
84140   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
84141   for(i=iStart; i<iStart+nExtra; i++){
84142     pSrc->a[i].iCursor = -1;
84143   }
84144 
84145   /* Return a pointer to the enlarged SrcList */
84146   return pSrc;
84147 }
84148 
84149 
84150 /*
84151 ** Append a new table name to the given SrcList.  Create a new SrcList if
84152 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
84153 **
84154 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
84155 ** SrcList might be the same as the SrcList that was input or it might be
84156 ** a new one.  If an OOM error does occurs, then the prior value of pList
84157 ** that is input to this routine is automatically freed.
84158 **
84159 ** If pDatabase is not null, it means that the table has an optional
84160 ** database name prefix.  Like this:  "database.table".  The pDatabase
84161 ** points to the table name and the pTable points to the database name.
84162 ** The SrcList.a[].zName field is filled with the table name which might
84163 ** come from pTable (if pDatabase is NULL) or from pDatabase.
84164 ** SrcList.a[].zDatabase is filled with the database name from pTable,
84165 ** or with NULL if no database is specified.
84166 **
84167 ** In other words, if call like this:
84168 **
84169 **         sqlite3SrcListAppend(D,A,B,0);
84170 **
84171 ** Then B is a table name and the database name is unspecified.  If called
84172 ** like this:
84173 **
84174 **         sqlite3SrcListAppend(D,A,B,C);
84175 **
84176 ** Then C is the table name and B is the database name.  If C is defined
84177 ** then so is B.  In other words, we never have a case where:
84178 **
84179 **         sqlite3SrcListAppend(D,A,0,C);
84180 **
84181 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84182 ** before being added to the SrcList.
84183 */
84184 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
84185   sqlite3 *db,        /* Connection to notify of malloc failures */
84186   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84187   Token *pTable,      /* Table to append */
84188   Token *pDatabase    /* Database of the table */
84189 ){
84190   struct SrcList_item *pItem;
84191   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84192   if( pList==0 ){
84193     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
84194     if( pList==0 ) return 0;
84195     pList->nAlloc = 1;
84196   }
84197   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
84198   if( db->mallocFailed ){
84199     sqlite3SrcListDelete(db, pList);
84200     return 0;
84201   }
84202   pItem = &pList->a[pList->nSrc-1];
84203   if( pDatabase && pDatabase->z==0 ){
84204     pDatabase = 0;
84205   }
84206   if( pDatabase ){
84207     Token *pTemp = pDatabase;
84208     pDatabase = pTable;
84209     pTable = pTemp;
84210   }
84211   pItem->zName = sqlite3NameFromToken(db, pTable);
84212   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
84213   return pList;
84214 }
84215 
84216 /*
84217 ** Assign VdbeCursor index numbers to all tables in a SrcList
84218 */
84219 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84220   int i;
84221   struct SrcList_item *pItem;
84222   assert(pList || pParse->db->mallocFailed );
84223   if( pList ){
84224     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84225       if( pItem->iCursor>=0 ) break;
84226       pItem->iCursor = pParse->nTab++;
84227       if( pItem->pSelect ){
84228         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84229       }
84230     }
84231   }
84232 }
84233 
84234 /*
84235 ** Delete an entire SrcList including all its substructure.
84236 */
84237 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
84238   int i;
84239   struct SrcList_item *pItem;
84240   if( pList==0 ) return;
84241   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84242     sqlite3DbFree(db, pItem->zDatabase);
84243     sqlite3DbFree(db, pItem->zName);
84244     sqlite3DbFree(db, pItem->zAlias);
84245     sqlite3DbFree(db, pItem->zIndex);
84246     sqlite3DeleteTable(db, pItem->pTab);
84247     sqlite3SelectDelete(db, pItem->pSelect);
84248     sqlite3ExprDelete(db, pItem->pOn);
84249     sqlite3IdListDelete(db, pItem->pUsing);
84250   }
84251   sqlite3DbFree(db, pList);
84252 }
84253 
84254 /*
84255 ** This routine is called by the parser to add a new term to the
84256 ** end of a growing FROM clause.  The "p" parameter is the part of
84257 ** the FROM clause that has already been constructed.  "p" is NULL
84258 ** if this is the first term of the FROM clause.  pTable and pDatabase
84259 ** are the name of the table and database named in the FROM clause term.
84260 ** pDatabase is NULL if the database name qualifier is missing - the
84261 ** usual case.  If the term has a alias, then pAlias points to the
84262 ** alias token.  If the term is a subquery, then pSubquery is the
84263 ** SELECT statement that the subquery encodes.  The pTable and
84264 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84265 ** parameters are the content of the ON and USING clauses.
84266 **
84267 ** Return a new SrcList which encodes is the FROM with the new
84268 ** term added.
84269 */
84270 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
84271   Parse *pParse,          /* Parsing context */
84272   SrcList *p,             /* The left part of the FROM clause already seen */
84273   Token *pTable,          /* Name of the table to add to the FROM clause */
84274   Token *pDatabase,       /* Name of the database containing pTable */
84275   Token *pAlias,          /* The right-hand side of the AS subexpression */
84276   Select *pSubquery,      /* A subquery used in place of a table name */
84277   Expr *pOn,              /* The ON clause of a join */
84278   IdList *pUsing          /* The USING clause of a join */
84279 ){
84280   struct SrcList_item *pItem;
84281   sqlite3 *db = pParse->db;
84282   if( !p && (pOn || pUsing) ){
84283     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
84284       (pOn ? "ON" : "USING")
84285     );
84286     goto append_from_error;
84287   }
84288   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
84289   if( p==0 || NEVER(p->nSrc==0) ){
84290     goto append_from_error;
84291   }
84292   pItem = &p->a[p->nSrc-1];
84293   assert( pAlias!=0 );
84294   if( pAlias->n ){
84295     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
84296   }
84297   pItem->pSelect = pSubquery;
84298   pItem->pOn = pOn;
84299   pItem->pUsing = pUsing;
84300   return p;
84301 
84302  append_from_error:
84303   assert( p==0 );
84304   sqlite3ExprDelete(db, pOn);
84305   sqlite3IdListDelete(db, pUsing);
84306   sqlite3SelectDelete(db, pSubquery);
84307   return 0;
84308 }
84309 
84310 /*
84311 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
84312 ** element of the source-list passed as the second argument.
84313 */
84314 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84315   assert( pIndexedBy!=0 );
84316   if( p && ALWAYS(p->nSrc>0) ){
84317     struct SrcList_item *pItem = &p->a[p->nSrc-1];
84318     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84319     if( pIndexedBy->n==1 && !pIndexedBy->z ){
84320       /* A "NOT INDEXED" clause was supplied. See parse.y
84321       ** construct "indexed_opt" for details. */
84322       pItem->notIndexed = 1;
84323     }else{
84324       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
84325     }
84326   }
84327 }
84328 
84329 /*
84330 ** When building up a FROM clause in the parser, the join operator
84331 ** is initially attached to the left operand.  But the code generator
84332 ** expects the join operator to be on the right operand.  This routine
84333 ** Shifts all join operators from left to right for an entire FROM
84334 ** clause.
84335 **
84336 ** Example: Suppose the join is like this:
84337 **
84338 **           A natural cross join B
84339 **
84340 ** The operator is "natural cross join".  The A and B operands are stored
84341 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84342 ** operator with A.  This routine shifts that operator over to B.
84343 */
84344 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
84345   if( p ){
84346     int i;
84347     assert( p->a || p->nSrc==0 );
84348     for(i=p->nSrc-1; i>0; i--){
84349       p->a[i].jointype = p->a[i-1].jointype;
84350     }
84351     p->a[0].jointype = 0;
84352   }
84353 }
84354 
84355 /*
84356 ** Begin a transaction
84357 */
84358 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
84359   sqlite3 *db;
84360   Vdbe *v;
84361   int i;
84362 
84363   assert( pParse!=0 );
84364   db = pParse->db;
84365   assert( db!=0 );
84366 /*  if( db->aDb[0].pBt==0 ) return; */
84367   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
84368     return;
84369   }
84370   v = sqlite3GetVdbe(pParse);
84371   if( !v ) return;
84372   if( type!=TK_DEFERRED ){
84373     for(i=0; i<db->nDb; i++){
84374       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84375       sqlite3VdbeUsesBtree(v, i);
84376     }
84377   }
84378   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84379 }
84380 
84381 /*
84382 ** Commit a transaction
84383 */
84384 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
84385   Vdbe *v;
84386 
84387   assert( pParse!=0 );
84388   assert( pParse->db!=0 );
84389   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
84390     return;
84391   }
84392   v = sqlite3GetVdbe(pParse);
84393   if( v ){
84394     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84395   }
84396 }
84397 
84398 /*
84399 ** Rollback a transaction
84400 */
84401 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
84402   Vdbe *v;
84403 
84404   assert( pParse!=0 );
84405   assert( pParse->db!=0 );
84406   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
84407     return;
84408   }
84409   v = sqlite3GetVdbe(pParse);
84410   if( v ){
84411     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84412   }
84413 }
84414 
84415 /*
84416 ** This function is called by the parser when it parses a command to create,
84417 ** release or rollback an SQL savepoint.
84418 */
84419 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
84420   char *zName = sqlite3NameFromToken(pParse->db, pName);
84421   if( zName ){
84422     Vdbe *v = sqlite3GetVdbe(pParse);
84423 #ifndef SQLITE_OMIT_AUTHORIZATION
84424     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84425     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84426 #endif
84427     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
84428       sqlite3DbFree(pParse->db, zName);
84429       return;
84430     }
84431     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84432   }
84433 }
84434 
84435 /*
84436 ** Make sure the TEMP database is open and available for use.  Return
84437 ** the number of errors.  Leave any error messages in the pParse structure.
84438 */
84439 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
84440   sqlite3 *db = pParse->db;
84441   if( db->aDb[1].pBt==0 && !pParse->explain ){
84442     int rc;
84443     Btree *pBt;
84444     static const int flags =
84445           SQLITE_OPEN_READWRITE |
84446           SQLITE_OPEN_CREATE |
84447           SQLITE_OPEN_EXCLUSIVE |
84448           SQLITE_OPEN_DELETEONCLOSE |
84449           SQLITE_OPEN_TEMP_DB;
84450 
84451     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84452     if( rc!=SQLITE_OK ){
84453       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
84454         "file for storing temporary tables");
84455       pParse->rc = rc;
84456       return 1;
84457     }
84458     db->aDb[1].pBt = pBt;
84459     assert( db->aDb[1].pSchema );
84460     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84461       db->mallocFailed = 1;
84462       return 1;
84463     }
84464   }
84465   return 0;
84466 }
84467 
84468 /*
84469 ** Generate VDBE code that will verify the schema cookie and start
84470 ** a read-transaction for all named database files.
84471 **
84472 ** It is important that all schema cookies be verified and all
84473 ** read transactions be started before anything else happens in
84474 ** the VDBE program.  But this routine can be called after much other
84475 ** code has been generated.  So here is what we do:
84476 **
84477 ** The first time this routine is called, we code an OP_Goto that
84478 ** will jump to a subroutine at the end of the program.  Then we
84479 ** record every database that needs its schema verified in the
84480 ** pParse->cookieMask field.  Later, after all other code has been
84481 ** generated, the subroutine that does the cookie verifications and
84482 ** starts the transactions will be coded and the OP_Goto P2 value
84483 ** will be made to point to that subroutine.  The generation of the
84484 ** cookie verification subroutine code happens in sqlite3FinishCoding().
84485 **
84486 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84487 ** schema on any databases.  This can be used to position the OP_Goto
84488 ** early in the code, before we know if any database tables will be used.
84489 */
84490 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
84491   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84492 
84493 #ifndef SQLITE_OMIT_TRIGGER
84494   if( pToplevel!=pParse ){
84495     /* This branch is taken if a trigger is currently being coded. In this
84496     ** case, set cookieGoto to a non-zero value to show that this function
84497     ** has been called. This is used by the sqlite3ExprCodeConstants()
84498     ** function. */
84499     pParse->cookieGoto = -1;
84500   }
84501 #endif
84502   if( pToplevel->cookieGoto==0 ){
84503     Vdbe *v = sqlite3GetVdbe(pToplevel);
84504     if( v==0 ) return;  /* This only happens if there was a prior error */
84505     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84506   }
84507   if( iDb>=0 ){
84508     sqlite3 *db = pToplevel->db;
84509     yDbMask mask;
84510 
84511     assert( iDb<db->nDb );
84512     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84513     assert( iDb<SQLITE_MAX_ATTACHED+2 );
84514     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84515     mask = ((yDbMask)1)<<iDb;
84516     if( (pToplevel->cookieMask & mask)==0 ){
84517       pToplevel->cookieMask |= mask;
84518       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84519       if( !OMIT_TEMPDB && iDb==1 ){
84520         sqlite3OpenTempDatabase(pToplevel);
84521       }
84522     }
84523   }
84524 }
84525 
84526 /*
84527 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
84528 ** attached database. Otherwise, invoke it for the database named zDb only.
84529 */
84530 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84531   sqlite3 *db = pParse->db;
84532   int i;
84533   for(i=0; i<db->nDb; i++){
84534     Db *pDb = &db->aDb[i];
84535     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
84536       sqlite3CodeVerifySchema(pParse, i);
84537     }
84538   }
84539 }
84540 
84541 /*
84542 ** Generate VDBE code that prepares for doing an operation that
84543 ** might change the database.
84544 **
84545 ** This routine starts a new transaction if we are not already within
84546 ** a transaction.  If we are already within a transaction, then a checkpoint
84547 ** is set if the setStatement parameter is true.  A checkpoint should
84548 ** be set for operations that might fail (due to a constraint) part of
84549 ** the way through and which will need to undo some writes without having to
84550 ** rollback the whole transaction.  For operations where all constraints
84551 ** can be checked before any changes are made to the database, it is never
84552 ** necessary to undo a write and the checkpoint should not be set.
84553 */
84554 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84555   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84556   sqlite3CodeVerifySchema(pParse, iDb);
84557   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84558   pToplevel->isMultiWrite |= setStatement;
84559 }
84560 
84561 /*
84562 ** Indicate that the statement currently under construction might write
84563 ** more than one entry (example: deleting one row then inserting another,
84564 ** inserting multiple rows in a table, or inserting a row and index entries.)
84565 ** If an abort occurs after some of these writes have completed, then it will
84566 ** be necessary to undo the completed writes.
84567 */
84568 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
84569   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84570   pToplevel->isMultiWrite = 1;
84571 }
84572 
84573 /*
84574 ** The code generator calls this routine if is discovers that it is
84575 ** possible to abort a statement prior to completion.  In order to
84576 ** perform this abort without corrupting the database, we need to make
84577 ** sure that the statement is protected by a statement transaction.
84578 **
84579 ** Technically, we only need to set the mayAbort flag if the
84580 ** isMultiWrite flag was previously set.  There is a time dependency
84581 ** such that the abort must occur after the multiwrite.  This makes
84582 ** some statements involving the REPLACE conflict resolution algorithm
84583 ** go a little faster.  But taking advantage of this time dependency
84584 ** makes it more difficult to prove that the code is correct (in
84585 ** particular, it prevents us from writing an effective
84586 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
84587 ** to take the safe route and skip the optimization.
84588 */
84589 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
84590   Parse *pToplevel = sqlite3ParseToplevel(pParse);
84591   pToplevel->mayAbort = 1;
84592 }
84593 
84594 /*
84595 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
84596 ** error. The onError parameter determines which (if any) of the statement
84597 ** and/or current transaction is rolled back.
84598 */
84599 SQLITE_PRIVATE void sqlite3HaltConstraint(
84600   Parse *pParse,    /* Parsing context */
84601   int errCode,      /* extended error code */
84602   int onError,      /* Constraint type */
84603   char *p4,         /* Error message */
84604   int p4type        /* P4_STATIC or P4_TRANSIENT */
84605 ){
84606   Vdbe *v = sqlite3GetVdbe(pParse);
84607   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
84608   if( onError==OE_Abort ){
84609     sqlite3MayAbort(pParse);
84610   }
84611   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
84612 }
84613 
84614 /*
84615 ** Check to see if pIndex uses the collating sequence pColl.  Return
84616 ** true if it does and false if it does not.
84617 */
84618 #ifndef SQLITE_OMIT_REINDEX
84619 static int collationMatch(const char *zColl, Index *pIndex){
84620   int i;
84621   assert( zColl!=0 );
84622   for(i=0; i<pIndex->nColumn; i++){
84623     const char *z = pIndex->azColl[i];
84624     assert( z!=0 );
84625     if( 0==sqlite3StrICmp(z, zColl) ){
84626       return 1;
84627     }
84628   }
84629   return 0;
84630 }
84631 #endif
84632 
84633 /*
84634 ** Recompute all indices of pTab that use the collating sequence pColl.
84635 ** If pColl==0 then recompute all indices of pTab.
84636 */
84637 #ifndef SQLITE_OMIT_REINDEX
84638 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84639   Index *pIndex;              /* An index associated with pTab */
84640 
84641   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84642     if( zColl==0 || collationMatch(zColl, pIndex) ){
84643       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84644       sqlite3BeginWriteOperation(pParse, 0, iDb);
84645       sqlite3RefillIndex(pParse, pIndex, -1);
84646     }
84647   }
84648 }
84649 #endif
84650 
84651 /*
84652 ** Recompute all indices of all tables in all databases where the
84653 ** indices use the collating sequence pColl.  If pColl==0 then recompute
84654 ** all indices everywhere.
84655 */
84656 #ifndef SQLITE_OMIT_REINDEX
84657 static void reindexDatabases(Parse *pParse, char const *zColl){
84658   Db *pDb;                    /* A single database */
84659   int iDb;                    /* The database index number */
84660   sqlite3 *db = pParse->db;   /* The database connection */
84661   HashElem *k;                /* For looping over tables in pDb */
84662   Table *pTab;                /* A table in the database */
84663 
84664   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84665   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84666     assert( pDb!=0 );
84667     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
84668       pTab = (Table*)sqliteHashData(k);
84669       reindexTable(pParse, pTab, zColl);
84670     }
84671   }
84672 }
84673 #endif
84674 
84675 /*
84676 ** Generate code for the REINDEX command.
84677 **
84678 **        REINDEX                            -- 1
84679 **        REINDEX  <collation>               -- 2
84680 **        REINDEX  ?<database>.?<tablename>  -- 3
84681 **        REINDEX  ?<database>.?<indexname>  -- 4
84682 **
84683 ** Form 1 causes all indices in all attached databases to be rebuilt.
84684 ** Form 2 rebuilds all indices in all databases that use the named
84685 ** collating function.  Forms 3 and 4 rebuild the named index or all
84686 ** indices associated with the named table.
84687 */
84688 #ifndef SQLITE_OMIT_REINDEX
84689 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84690   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84691   char *z;                    /* Name of a table or index */
84692   const char *zDb;            /* Name of the database */
84693   Table *pTab;                /* A table in the database */
84694   Index *pIndex;              /* An index associated with pTab */
84695   int iDb;                    /* The database index number */
84696   sqlite3 *db = pParse->db;   /* The database connection */
84697   Token *pObjName;            /* Name of the table or index to be reindexed */
84698 
84699   /* Read the database schema. If an error occurs, leave an error message
84700   ** and code in pParse and return NULL. */
84701   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84702     return;
84703   }
84704 
84705   if( pName1==0 ){
84706     reindexDatabases(pParse, 0);
84707     return;
84708   }else if( NEVER(pName2==0) || pName2->z==0 ){
84709     char *zColl;
84710     assert( pName1->z );
84711     zColl = sqlite3NameFromToken(pParse->db, pName1);
84712     if( !zColl ) return;
84713     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
84714     if( pColl ){
84715       reindexDatabases(pParse, zColl);
84716       sqlite3DbFree(db, zColl);
84717       return;
84718     }
84719     sqlite3DbFree(db, zColl);
84720   }
84721   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
84722   if( iDb<0 ) return;
84723   z = sqlite3NameFromToken(db, pObjName);
84724   if( z==0 ) return;
84725   zDb = db->aDb[iDb].zName;
84726   pTab = sqlite3FindTable(db, z, zDb);
84727   if( pTab ){
84728     reindexTable(pParse, pTab, 0);
84729     sqlite3DbFree(db, z);
84730     return;
84731   }
84732   pIndex = sqlite3FindIndex(db, z, zDb);
84733   sqlite3DbFree(db, z);
84734   if( pIndex ){
84735     sqlite3BeginWriteOperation(pParse, 0, iDb);
84736     sqlite3RefillIndex(pParse, pIndex, -1);
84737     return;
84738   }
84739   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84740 }
84741 #endif
84742 
84743 /*
84744 ** Return a dynamicly allocated KeyInfo structure that can be used
84745 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84746 **
84747 ** If successful, a pointer to the new structure is returned. In this case
84748 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
84749 ** pointer. If an error occurs (out of memory or missing collation
84750 ** sequence), NULL is returned and the state of pParse updated to reflect
84751 ** the error.
84752 */
84753 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
84754   int i;
84755   int nCol = pIdx->nColumn;
84756   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
84757   sqlite3 *db = pParse->db;
84758   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
84759 
84760   if( pKey ){
84761     pKey->db = pParse->db;
84762     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
84763     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
84764     for(i=0; i<nCol; i++){
84765       char *zColl = pIdx->azColl[i];
84766       assert( zColl );
84767       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
84768       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
84769     }
84770     pKey->nField = (u16)nCol;
84771   }
84772 
84773   if( pParse->nErr ){
84774     sqlite3DbFree(db, pKey);
84775     pKey = 0;
84776   }
84777   return pKey;
84778 }
84779 
84780 /************** End of build.c ***********************************************/
84781 /************** Begin file callback.c ****************************************/
84782 /*
84783 ** 2005 May 23
84784 **
84785 ** The author disclaims copyright to this source code.  In place of
84786 ** a legal notice, here is a blessing:
84787 **
84788 **    May you do good and not evil.
84789 **    May you find forgiveness for yourself and forgive others.
84790 **    May you share freely, never taking more than you give.
84791 **
84792 *************************************************************************
84793 **
84794 ** This file contains functions used to access the internal hash tables
84795 ** of user defined functions and collation sequences.
84796 */
84797 
84798 
84799 /*
84800 ** Invoke the 'collation needed' callback to request a collation sequence
84801 ** in the encoding enc of name zName, length nName.
84802 */
84803 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
84804   assert( !db->xCollNeeded || !db->xCollNeeded16 );
84805   if( db->xCollNeeded ){
84806     char *zExternal = sqlite3DbStrDup(db, zName);
84807     if( !zExternal ) return;
84808     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
84809     sqlite3DbFree(db, zExternal);
84810   }
84811 #ifndef SQLITE_OMIT_UTF16
84812   if( db->xCollNeeded16 ){
84813     char const *zExternal;
84814     sqlite3_value *pTmp = sqlite3ValueNew(db);
84815     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
84816     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
84817     if( zExternal ){
84818       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
84819     }
84820     sqlite3ValueFree(pTmp);
84821   }
84822 #endif
84823 }
84824 
84825 /*
84826 ** This routine is called if the collation factory fails to deliver a
84827 ** collation function in the best encoding but there may be other versions
84828 ** of this collation function (for other text encodings) available. Use one
84829 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
84830 ** possible.
84831 */
84832 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
84833   CollSeq *pColl2;
84834   char *z = pColl->zName;
84835   int i;
84836   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
84837   for(i=0; i<3; i++){
84838     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
84839     if( pColl2->xCmp!=0 ){
84840       memcpy(pColl, pColl2, sizeof(CollSeq));
84841       pColl->xDel = 0;         /* Do not copy the destructor */
84842       return SQLITE_OK;
84843     }
84844   }
84845   return SQLITE_ERROR;
84846 }
84847 
84848 /*
84849 ** This function is responsible for invoking the collation factory callback
84850 ** or substituting a collation sequence of a different encoding when the
84851 ** requested collation sequence is not available in the desired encoding.
84852 **
84853 ** If it is not NULL, then pColl must point to the database native encoding
84854 ** collation sequence with name zName, length nName.
84855 **
84856 ** The return value is either the collation sequence to be used in database
84857 ** db for collation type name zName, length nName, or NULL, if no collation
84858 ** sequence can be found.  If no collation is found, leave an error message.
84859 **
84860 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
84861 */
84862 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
84863   Parse *pParse,        /* Parsing context */
84864   u8 enc,               /* The desired encoding for the collating sequence */
84865   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
84866   const char *zName     /* Collating sequence name */
84867 ){
84868   CollSeq *p;
84869   sqlite3 *db = pParse->db;
84870 
84871   p = pColl;
84872   if( !p ){
84873     p = sqlite3FindCollSeq(db, enc, zName, 0);
84874   }
84875   if( !p || !p->xCmp ){
84876     /* No collation sequence of this type for this encoding is registered.
84877     ** Call the collation factory to see if it can supply us with one.
84878     */
84879     callCollNeeded(db, enc, zName);
84880     p = sqlite3FindCollSeq(db, enc, zName, 0);
84881   }
84882   if( p && !p->xCmp && synthCollSeq(db, p) ){
84883     p = 0;
84884   }
84885   assert( !p || p->xCmp );
84886   if( p==0 ){
84887     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
84888   }
84889   return p;
84890 }
84891 
84892 /*
84893 ** This routine is called on a collation sequence before it is used to
84894 ** check that it is defined. An undefined collation sequence exists when
84895 ** a database is loaded that contains references to collation sequences
84896 ** that have not been defined by sqlite3_create_collation() etc.
84897 **
84898 ** If required, this routine calls the 'collation needed' callback to
84899 ** request a definition of the collating sequence. If this doesn't work,
84900 ** an equivalent collating sequence that uses a text encoding different
84901 ** from the main database is substituted, if one is available.
84902 */
84903 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
84904   if( pColl ){
84905     const char *zName = pColl->zName;
84906     sqlite3 *db = pParse->db;
84907     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
84908     if( !p ){
84909       return SQLITE_ERROR;
84910     }
84911     assert( p==pColl );
84912   }
84913   return SQLITE_OK;
84914 }
84915 
84916 
84917 
84918 /*
84919 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
84920 ** specified by zName and nName is not found and parameter 'create' is
84921 ** true, then create a new entry. Otherwise return NULL.
84922 **
84923 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
84924 ** array of three CollSeq structures. The first is the collation sequence
84925 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
84926 **
84927 ** Stored immediately after the three collation sequences is a copy of
84928 ** the collation sequence name. A pointer to this string is stored in
84929 ** each collation sequence structure.
84930 */
84931 static CollSeq *findCollSeqEntry(
84932   sqlite3 *db,          /* Database connection */
84933   const char *zName,    /* Name of the collating sequence */
84934   int create            /* Create a new entry if true */
84935 ){
84936   CollSeq *pColl;
84937   int nName = sqlite3Strlen30(zName);
84938   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
84939 
84940   if( 0==pColl && create ){
84941     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
84942     if( pColl ){
84943       CollSeq *pDel = 0;
84944       pColl[0].zName = (char*)&pColl[3];
84945       pColl[0].enc = SQLITE_UTF8;
84946       pColl[1].zName = (char*)&pColl[3];
84947       pColl[1].enc = SQLITE_UTF16LE;
84948       pColl[2].zName = (char*)&pColl[3];
84949       pColl[2].enc = SQLITE_UTF16BE;
84950       memcpy(pColl[0].zName, zName, nName);
84951       pColl[0].zName[nName] = 0;
84952       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
84953 
84954       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
84955       ** return the pColl pointer to be deleted (because it wasn't added
84956       ** to the hash table).
84957       */
84958       assert( pDel==0 || pDel==pColl );
84959       if( pDel!=0 ){
84960         db->mallocFailed = 1;
84961         sqlite3DbFree(db, pDel);
84962         pColl = 0;
84963       }
84964     }
84965   }
84966   return pColl;
84967 }
84968 
84969 /*
84970 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
84971 ** Return the CollSeq* pointer for the collation sequence named zName
84972 ** for the encoding 'enc' from the database 'db'.
84973 **
84974 ** If the entry specified is not found and 'create' is true, then create a
84975 ** new entry.  Otherwise return NULL.
84976 **
84977 ** A separate function sqlite3LocateCollSeq() is a wrapper around
84978 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
84979 ** if necessary and generates an error message if the collating sequence
84980 ** cannot be found.
84981 **
84982 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
84983 */
84984 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
84985   sqlite3 *db,
84986   u8 enc,
84987   const char *zName,
84988   int create
84989 ){
84990   CollSeq *pColl;
84991   if( zName ){
84992     pColl = findCollSeqEntry(db, zName, create);
84993   }else{
84994     pColl = db->pDfltColl;
84995   }
84996   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
84997   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
84998   if( pColl ) pColl += enc-1;
84999   return pColl;
85000 }
85001 
85002 /* During the search for the best function definition, this procedure
85003 ** is called to test how well the function passed as the first argument
85004 ** matches the request for a function with nArg arguments in a system
85005 ** that uses encoding enc. The value returned indicates how well the
85006 ** request is matched. A higher value indicates a better match.
85007 **
85008 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
85009 ** is also -1.  In other words, we are searching for a function that
85010 ** takes a variable number of arguments.
85011 **
85012 ** If nArg is -2 that means that we are searching for any function
85013 ** regardless of the number of arguments it uses, so return a positive
85014 ** match score for any
85015 **
85016 ** The returned value is always between 0 and 6, as follows:
85017 **
85018 ** 0: Not a match.
85019 ** 1: UTF8/16 conversion required and function takes any number of arguments.
85020 ** 2: UTF16 byte order change required and function takes any number of args.
85021 ** 3: encoding matches and function takes any number of arguments
85022 ** 4: UTF8/16 conversion required - argument count matches exactly
85023 ** 5: UTF16 byte order conversion required - argument count matches exactly
85024 ** 6: Perfect match:  encoding and argument count match exactly.
85025 **
85026 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
85027 ** a perfect match and any function with both xStep and xFunc NULL is
85028 ** a non-match.
85029 */
85030 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
85031 static int matchQuality(
85032   FuncDef *p,     /* The function we are evaluating for match quality */
85033   int nArg,       /* Desired number of arguments.  (-1)==any */
85034   u8 enc          /* Desired text encoding */
85035 ){
85036   int match;
85037 
85038   /* nArg of -2 is a special case */
85039   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
85040 
85041   /* Wrong number of arguments means "no match" */
85042   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
85043 
85044   /* Give a better score to a function with a specific number of arguments
85045   ** than to function that accepts any number of arguments. */
85046   if( p->nArg==nArg ){
85047     match = 4;
85048   }else{
85049     match = 1;
85050   }
85051 
85052   /* Bonus points if the text encoding matches */
85053   if( enc==p->iPrefEnc ){
85054     match += 2;  /* Exact encoding match */
85055   }else if( (enc & p->iPrefEnc & 2)!=0 ){
85056     match += 1;  /* Both are UTF16, but with different byte orders */
85057   }
85058 
85059   return match;
85060 }
85061 
85062 /*
85063 ** Search a FuncDefHash for a function with the given name.  Return
85064 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
85065 */
85066 static FuncDef *functionSearch(
85067   FuncDefHash *pHash,  /* Hash table to search */
85068   int h,               /* Hash of the name */
85069   const char *zFunc,   /* Name of function */
85070   int nFunc            /* Number of bytes in zFunc */
85071 ){
85072   FuncDef *p;
85073   for(p=pHash->a[h]; p; p=p->pHash){
85074     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
85075       return p;
85076     }
85077   }
85078   return 0;
85079 }
85080 
85081 /*
85082 ** Insert a new FuncDef into a FuncDefHash hash table.
85083 */
85084 SQLITE_PRIVATE void sqlite3FuncDefInsert(
85085   FuncDefHash *pHash,  /* The hash table into which to insert */
85086   FuncDef *pDef        /* The function definition to insert */
85087 ){
85088   FuncDef *pOther;
85089   int nName = sqlite3Strlen30(pDef->zName);
85090   u8 c1 = (u8)pDef->zName[0];
85091   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
85092   pOther = functionSearch(pHash, h, pDef->zName, nName);
85093   if( pOther ){
85094     assert( pOther!=pDef && pOther->pNext!=pDef );
85095     pDef->pNext = pOther->pNext;
85096     pOther->pNext = pDef;
85097   }else{
85098     pDef->pNext = 0;
85099     pDef->pHash = pHash->a[h];
85100     pHash->a[h] = pDef;
85101   }
85102 }
85103 
85104 
85105 
85106 /*
85107 ** Locate a user function given a name, a number of arguments and a flag
85108 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
85109 ** pointer to the FuncDef structure that defines that function, or return
85110 ** NULL if the function does not exist.
85111 **
85112 ** If the createFlag argument is true, then a new (blank) FuncDef
85113 ** structure is created and liked into the "db" structure if a
85114 ** no matching function previously existed.
85115 **
85116 ** If nArg is -2, then the first valid function found is returned.  A
85117 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
85118 ** case is used to see if zName is a valid function name for some number
85119 ** of arguments.  If nArg is -2, then createFlag must be 0.
85120 **
85121 ** If createFlag is false, then a function with the required name and
85122 ** number of arguments may be returned even if the eTextRep flag does not
85123 ** match that requested.
85124 */
85125 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
85126   sqlite3 *db,       /* An open database */
85127   const char *zName, /* Name of the function.  Not null-terminated */
85128   int nName,         /* Number of characters in the name */
85129   int nArg,          /* Number of arguments.  -1 means any number */
85130   u8 enc,            /* Preferred text encoding */
85131   u8 createFlag      /* Create new entry if true and does not otherwise exist */
85132 ){
85133   FuncDef *p;         /* Iterator variable */
85134   FuncDef *pBest = 0; /* Best match found so far */
85135   int bestScore = 0;  /* Score of best match */
85136   int h;              /* Hash value */
85137 
85138   assert( nArg>=(-2) );
85139   assert( nArg>=(-1) || createFlag==0 );
85140   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
85141   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
85142 
85143   /* First search for a match amongst the application-defined functions.
85144   */
85145   p = functionSearch(&db->aFunc, h, zName, nName);
85146   while( p ){
85147     int score = matchQuality(p, nArg, enc);
85148     if( score>bestScore ){
85149       pBest = p;
85150       bestScore = score;
85151     }
85152     p = p->pNext;
85153   }
85154 
85155   /* If no match is found, search the built-in functions.
85156   **
85157   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
85158   ** functions even if a prior app-defined function was found.  And give
85159   ** priority to built-in functions.
85160   **
85161   ** Except, if createFlag is true, that means that we are trying to
85162   ** install a new function.  Whatever FuncDef structure is returned it will
85163   ** have fields overwritten with new information appropriate for the
85164   ** new function.  But the FuncDefs for built-in functions are read-only.
85165   ** So we must not search for built-ins when creating a new function.
85166   */
85167   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
85168     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85169     bestScore = 0;
85170     p = functionSearch(pHash, h, zName, nName);
85171     while( p ){
85172       int score = matchQuality(p, nArg, enc);
85173       if( score>bestScore ){
85174         pBest = p;
85175         bestScore = score;
85176       }
85177       p = p->pNext;
85178     }
85179   }
85180 
85181   /* If the createFlag parameter is true and the search did not reveal an
85182   ** exact match for the name, number of arguments and encoding, then add a
85183   ** new entry to the hash table and return it.
85184   */
85185   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
85186       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85187     pBest->zName = (char *)&pBest[1];
85188     pBest->nArg = (u16)nArg;
85189     pBest->iPrefEnc = enc;
85190     memcpy(pBest->zName, zName, nName);
85191     pBest->zName[nName] = 0;
85192     sqlite3FuncDefInsert(&db->aFunc, pBest);
85193   }
85194 
85195   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85196     return pBest;
85197   }
85198   return 0;
85199 }
85200 
85201 /*
85202 ** Free all resources held by the schema structure. The void* argument points
85203 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
85204 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85205 ** of the schema hash tables).
85206 **
85207 ** The Schema.cache_size variable is not cleared.
85208 */
85209 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
85210   Hash temp1;
85211   Hash temp2;
85212   HashElem *pElem;
85213   Schema *pSchema = (Schema *)p;
85214 
85215   temp1 = pSchema->tblHash;
85216   temp2 = pSchema->trigHash;
85217   sqlite3HashInit(&pSchema->trigHash);
85218   sqlite3HashClear(&pSchema->idxHash);
85219   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
85220     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
85221   }
85222   sqlite3HashClear(&temp2);
85223   sqlite3HashInit(&pSchema->tblHash);
85224   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
85225     Table *pTab = sqliteHashData(pElem);
85226     sqlite3DeleteTable(0, pTab);
85227   }
85228   sqlite3HashClear(&temp1);
85229   sqlite3HashClear(&pSchema->fkeyHash);
85230   pSchema->pSeqTab = 0;
85231   if( pSchema->flags & DB_SchemaLoaded ){
85232     pSchema->iGeneration++;
85233     pSchema->flags &= ~DB_SchemaLoaded;
85234   }
85235 }
85236 
85237 /*
85238 ** Find and return the schema associated with a BTree.  Create
85239 ** a new one if necessary.
85240 */
85241 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
85242   Schema * p;
85243   if( pBt ){
85244     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
85245   }else{
85246     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
85247   }
85248   if( !p ){
85249     db->mallocFailed = 1;
85250   }else if ( 0==p->file_format ){
85251     sqlite3HashInit(&p->tblHash);
85252     sqlite3HashInit(&p->idxHash);
85253     sqlite3HashInit(&p->trigHash);
85254     sqlite3HashInit(&p->fkeyHash);
85255     p->enc = SQLITE_UTF8;
85256   }
85257   return p;
85258 }
85259 
85260 /************** End of callback.c ********************************************/
85261 /************** Begin file delete.c ******************************************/
85262 /*
85263 ** 2001 September 15
85264 **
85265 ** The author disclaims copyright to this source code.  In place of
85266 ** a legal notice, here is a blessing:
85267 **
85268 **    May you do good and not evil.
85269 **    May you find forgiveness for yourself and forgive others.
85270 **    May you share freely, never taking more than you give.
85271 **
85272 *************************************************************************
85273 ** This file contains C code routines that are called by the parser
85274 ** in order to generate code for DELETE FROM statements.
85275 */
85276 
85277 /*
85278 ** While a SrcList can in general represent multiple tables and subqueries
85279 ** (as in the FROM clause of a SELECT statement) in this case it contains
85280 ** the name of a single table, as one might find in an INSERT, DELETE,
85281 ** or UPDATE statement.  Look up that table in the symbol table and
85282 ** return a pointer.  Set an error message and return NULL if the table
85283 ** name is not found or if any other error occurs.
85284 **
85285 ** The following fields are initialized appropriate in pSrc:
85286 **
85287 **    pSrc->a[0].pTab       Pointer to the Table object
85288 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85289 **
85290 */
85291 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
85292   struct SrcList_item *pItem = pSrc->a;
85293   Table *pTab;
85294   assert( pItem && pSrc->nSrc==1 );
85295   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
85296   sqlite3DeleteTable(pParse->db, pItem->pTab);
85297   pItem->pTab = pTab;
85298   if( pTab ){
85299     pTab->nRef++;
85300   }
85301   if( sqlite3IndexedByLookup(pParse, pItem) ){
85302     pTab = 0;
85303   }
85304   return pTab;
85305 }
85306 
85307 /*
85308 ** Check to make sure the given table is writable.  If it is not
85309 ** writable, generate an error message and return 1.  If it is
85310 ** writable return 0;
85311 */
85312 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85313   /* A table is not writable under the following circumstances:
85314   **
85315   **   1) It is a virtual table and no implementation of the xUpdate method
85316   **      has been provided, or
85317   **   2) It is a system table (i.e. sqlite_master), this call is not
85318   **      part of a nested parse and writable_schema pragma has not
85319   **      been specified.
85320   **
85321   ** In either case leave an error message in pParse and return non-zero.
85322   */
85323   if( ( IsVirtual(pTab)
85324      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85325    || ( (pTab->tabFlags & TF_Readonly)!=0
85326      && (pParse->db->flags & SQLITE_WriteSchema)==0
85327      && pParse->nested==0 )
85328   ){
85329     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85330     return 1;
85331   }
85332 
85333 #ifndef SQLITE_OMIT_VIEW
85334   if( !viewOk && pTab->pSelect ){
85335     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85336     return 1;
85337   }
85338 #endif
85339   return 0;
85340 }
85341 
85342 
85343 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85344 /*
85345 ** Evaluate a view and store its result in an ephemeral table.  The
85346 ** pWhere argument is an optional WHERE clause that restricts the
85347 ** set of rows in the view that are to be added to the ephemeral table.
85348 */
85349 SQLITE_PRIVATE void sqlite3MaterializeView(
85350   Parse *pParse,       /* Parsing context */
85351   Table *pView,        /* View definition */
85352   Expr *pWhere,        /* Optional WHERE clause to be added */
85353   int iCur             /* Cursor number for ephemerial table */
85354 ){
85355   SelectDest dest;
85356   Select *pSel;
85357   SrcList *pFrom;
85358   sqlite3 *db = pParse->db;
85359   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
85360 
85361   pWhere = sqlite3ExprDup(db, pWhere, 0);
85362   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
85363 
85364   if( pFrom ){
85365     assert( pFrom->nSrc==1 );
85366     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
85367     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
85368     assert( pFrom->a[0].pOn==0 );
85369     assert( pFrom->a[0].pUsing==0 );
85370   }
85371 
85372   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85373   if( pSel ) pSel->selFlags |= SF_Materialize;
85374 
85375   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
85376   sqlite3Select(pParse, pSel, &dest);
85377   sqlite3SelectDelete(db, pSel);
85378 }
85379 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
85380 
85381 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
85382 /*
85383 ** Generate an expression tree to implement the WHERE, ORDER BY,
85384 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85385 **
85386 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85387 **                            \__________________________/
85388 **                               pLimitWhere (pInClause)
85389 */
85390 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
85391   Parse *pParse,               /* The parser context */
85392   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85393   Expr *pWhere,                /* The WHERE clause.  May be null */
85394   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85395   Expr *pLimit,                /* The LIMIT clause.  May be null */
85396   Expr *pOffset,               /* The OFFSET clause.  May be null */
85397   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85398 ){
85399   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85400   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85401   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85402   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85403   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85404   Select *pSelect = NULL;      /* Complete SELECT tree */
85405 
85406   /* Check that there isn't an ORDER BY without a LIMIT clause.
85407   */
85408   if( pOrderBy && (pLimit == 0) ) {
85409     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85410     goto limit_where_cleanup_2;
85411   }
85412 
85413   /* We only need to generate a select expression if there
85414   ** is a limit/offset term to enforce.
85415   */
85416   if( pLimit == 0 ) {
85417     /* if pLimit is null, pOffset will always be null as well. */
85418     assert( pOffset == 0 );
85419     return pWhere;
85420   }
85421 
85422   /* Generate a select expression tree to enforce the limit/offset
85423   ** term for the DELETE or UPDATE statement.  For example:
85424   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85425   ** becomes:
85426   **   DELETE FROM table_a WHERE rowid IN (
85427   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85428   **   );
85429   */
85430 
85431   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85432   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85433   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
85434   if( pEList == 0 ) goto limit_where_cleanup_2;
85435 
85436   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85437   ** and the SELECT subtree. */
85438   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
85439   if( pSelectSrc == 0 ) {
85440     sqlite3ExprListDelete(pParse->db, pEList);
85441     goto limit_where_cleanup_2;
85442   }
85443 
85444   /* generate the SELECT expression tree. */
85445   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85446                              pOrderBy,0,pLimit,pOffset);
85447   if( pSelect == 0 ) return 0;
85448 
85449   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85450   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85451   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85452   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85453   if( pInClause == 0 ) goto limit_where_cleanup_1;
85454 
85455   pInClause->x.pSelect = pSelect;
85456   pInClause->flags |= EP_xIsSelect;
85457   sqlite3ExprSetHeight(pParse, pInClause);
85458   return pInClause;
85459 
85460   /* something went wrong. clean up anything allocated. */
85461 limit_where_cleanup_1:
85462   sqlite3SelectDelete(pParse->db, pSelect);
85463   return 0;
85464 
85465 limit_where_cleanup_2:
85466   sqlite3ExprDelete(pParse->db, pWhere);
85467   sqlite3ExprListDelete(pParse->db, pOrderBy);
85468   sqlite3ExprDelete(pParse->db, pLimit);
85469   sqlite3ExprDelete(pParse->db, pOffset);
85470   return 0;
85471 }
85472 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
85473 
85474 /*
85475 ** Generate code for a DELETE FROM statement.
85476 **
85477 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85478 **                 \________/       \________________/
85479 **                  pTabList              pWhere
85480 */
85481 SQLITE_PRIVATE void sqlite3DeleteFrom(
85482   Parse *pParse,         /* The parser context */
85483   SrcList *pTabList,     /* The table from which we should delete things */
85484   Expr *pWhere           /* The WHERE clause.  May be null */
85485 ){
85486   Vdbe *v;               /* The virtual database engine */
85487   Table *pTab;           /* The table from which records will be deleted */
85488   const char *zDb;       /* Name of database holding pTab */
85489   int end, addr = 0;     /* A couple addresses of generated code */
85490   int i;                 /* Loop counter */
85491   WhereInfo *pWInfo;     /* Information about the WHERE clause */
85492   Index *pIdx;           /* For looping over indices of the table */
85493   int iCur;              /* VDBE Cursor number for pTab */
85494   sqlite3 *db;           /* Main database structure */
85495   AuthContext sContext;  /* Authorization context */
85496   NameContext sNC;       /* Name context to resolve expressions in */
85497   int iDb;               /* Database number */
85498   int memCnt = -1;       /* Memory cell used for change counting */
85499   int rcauth;            /* Value returned by authorization callback */
85500 
85501 #ifndef SQLITE_OMIT_TRIGGER
85502   int isView;                  /* True if attempting to delete from a view */
85503   Trigger *pTrigger;           /* List of table triggers, if required */
85504 #endif
85505 
85506   memset(&sContext, 0, sizeof(sContext));
85507   db = pParse->db;
85508   if( pParse->nErr || db->mallocFailed ){
85509     goto delete_from_cleanup;
85510   }
85511   assert( pTabList->nSrc==1 );
85512 
85513   /* Locate the table which we want to delete.  This table has to be
85514   ** put in an SrcList structure because some of the subroutines we
85515   ** will be calling are designed to work with multiple tables and expect
85516   ** an SrcList* parameter instead of just a Table* parameter.
85517   */
85518   pTab = sqlite3SrcListLookup(pParse, pTabList);
85519   if( pTab==0 )  goto delete_from_cleanup;
85520 
85521   /* Figure out if we have any triggers and if the table being
85522   ** deleted from is a view
85523   */
85524 #ifndef SQLITE_OMIT_TRIGGER
85525   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85526   isView = pTab->pSelect!=0;
85527 #else
85528 # define pTrigger 0
85529 # define isView 0
85530 #endif
85531 #ifdef SQLITE_OMIT_VIEW
85532 # undef isView
85533 # define isView 0
85534 #endif
85535 
85536   /* If pTab is really a view, make sure it has been initialized.
85537   */
85538   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85539     goto delete_from_cleanup;
85540   }
85541 
85542   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85543     goto delete_from_cleanup;
85544   }
85545   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85546   assert( iDb<db->nDb );
85547   zDb = db->aDb[iDb].zName;
85548   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
85549   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
85550   if( rcauth==SQLITE_DENY ){
85551     goto delete_from_cleanup;
85552   }
85553   assert(!isView || pTrigger);
85554 
85555   /* Assign  cursor number to the table and all its indices.
85556   */
85557   assert( pTabList->nSrc==1 );
85558   iCur = pTabList->a[0].iCursor = pParse->nTab++;
85559   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85560     pParse->nTab++;
85561   }
85562 
85563   /* Start the view context
85564   */
85565   if( isView ){
85566     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85567   }
85568 
85569   /* Begin generating code.
85570   */
85571   v = sqlite3GetVdbe(pParse);
85572   if( v==0 ){
85573     goto delete_from_cleanup;
85574   }
85575   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85576   sqlite3BeginWriteOperation(pParse, 1, iDb);
85577 
85578   /* If we are trying to delete from a view, realize that view into
85579   ** a ephemeral table.
85580   */
85581 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85582   if( isView ){
85583     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85584   }
85585 #endif
85586 
85587   /* Resolve the column names in the WHERE clause.
85588   */
85589   memset(&sNC, 0, sizeof(sNC));
85590   sNC.pParse = pParse;
85591   sNC.pSrcList = pTabList;
85592   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85593     goto delete_from_cleanup;
85594   }
85595 
85596   /* Initialize the counter of the number of rows deleted, if
85597   ** we are counting rows.
85598   */
85599   if( db->flags & SQLITE_CountRows ){
85600     memCnt = ++pParse->nMem;
85601     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85602   }
85603 
85604 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
85605   /* Special case: A DELETE without a WHERE clause deletes everything.
85606   ** It is easier just to erase the whole table. Prior to version 3.6.5,
85607   ** this optimization caused the row change count (the value returned by
85608   ** API function sqlite3_count_changes) to be set incorrectly.  */
85609   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
85610    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
85611   ){
85612     assert( !isView );
85613     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85614                       pTab->zName, P4_STATIC);
85615     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85616       assert( pIdx->pSchema==pTab->pSchema );
85617       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85618     }
85619   }else
85620 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
85621   /* The usual case: There is a WHERE clause so we have to scan through
85622   ** the table and pick which records to delete.
85623   */
85624   {
85625     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85626     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85627     int regRowid;                   /* Actual register containing rowids */
85628 
85629     /* Collect rowids of every row to be deleted.
85630     */
85631     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85632     pWInfo = sqlite3WhereBegin(
85633         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
85634     );
85635     if( pWInfo==0 ) goto delete_from_cleanup;
85636     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
85637     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85638     if( db->flags & SQLITE_CountRows ){
85639       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85640     }
85641     sqlite3WhereEnd(pWInfo);
85642 
85643     /* Delete every item whose key was written to the list during the
85644     ** database scan.  We have to delete items after the scan is complete
85645     ** because deleting an item can change the scan order.  */
85646     end = sqlite3VdbeMakeLabel(v);
85647 
85648     /* Unless this is a view, open cursors for the table we are
85649     ** deleting from and all its indices. If this is a view, then the
85650     ** only effect this statement has is to fire the INSTEAD OF
85651     ** triggers.  */
85652     if( !isView ){
85653       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85654     }
85655 
85656     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85657 
85658     /* Delete the row */
85659 #ifndef SQLITE_OMIT_VIRTUALTABLE
85660     if( IsVirtual(pTab) ){
85661       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85662       sqlite3VtabMakeWritable(pParse, pTab);
85663       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85664       sqlite3VdbeChangeP5(v, OE_Abort);
85665       sqlite3MayAbort(pParse);
85666     }else
85667 #endif
85668     {
85669       int count = (pParse->nested==0);    /* True to count changes */
85670       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85671     }
85672 
85673     /* End of the delete loop */
85674     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85675     sqlite3VdbeResolveLabel(v, end);
85676 
85677     /* Close the cursors open on the table and its indexes. */
85678     if( !isView && !IsVirtual(pTab) ){
85679       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85680         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85681       }
85682       sqlite3VdbeAddOp1(v, OP_Close, iCur);
85683     }
85684   }
85685 
85686   /* Update the sqlite_sequence table by storing the content of the
85687   ** maximum rowid counter values recorded while inserting into
85688   ** autoincrement tables.
85689   */
85690   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85691     sqlite3AutoincrementEnd(pParse);
85692   }
85693 
85694   /* Return the number of rows that were deleted. If this routine is
85695   ** generating code because of a call to sqlite3NestedParse(), do not
85696   ** invoke the callback function.
85697   */
85698   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85699     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85700     sqlite3VdbeSetNumCols(v, 1);
85701     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
85702   }
85703 
85704 delete_from_cleanup:
85705   sqlite3AuthContextPop(&sContext);
85706   sqlite3SrcListDelete(db, pTabList);
85707   sqlite3ExprDelete(db, pWhere);
85708   return;
85709 }
85710 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85711 ** thely may interfere with compilation of other functions in this file
85712 ** (or in another file, if this file becomes part of the amalgamation).  */
85713 #ifdef isView
85714  #undef isView
85715 #endif
85716 #ifdef pTrigger
85717  #undef pTrigger
85718 #endif
85719 
85720 /*
85721 ** This routine generates VDBE code that causes a single row of a
85722 ** single table to be deleted.
85723 **
85724 ** The VDBE must be in a particular state when this routine is called.
85725 ** These are the requirements:
85726 **
85727 **   1.  A read/write cursor pointing to pTab, the table containing the row
85728 **       to be deleted, must be opened as cursor number $iCur.
85729 **
85730 **   2.  Read/write cursors for all indices of pTab must be open as
85731 **       cursor number base+i for the i-th index.
85732 **
85733 **   3.  The record number of the row to be deleted must be stored in
85734 **       memory cell iRowid.
85735 **
85736 ** This routine generates code to remove both the table record and all
85737 ** index entries that point to that record.
85738 */
85739 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
85740   Parse *pParse,     /* Parsing context */
85741   Table *pTab,       /* Table containing the row to be deleted */
85742   int iCur,          /* Cursor number for the table */
85743   int iRowid,        /* Memory cell that contains the rowid to delete */
85744   int count,         /* If non-zero, increment the row change counter */
85745   Trigger *pTrigger, /* List of triggers to (potentially) fire */
85746   int onconf         /* Default ON CONFLICT policy for triggers */
85747 ){
85748   Vdbe *v = pParse->pVdbe;        /* Vdbe */
85749   int iOld = 0;                   /* First register in OLD.* array */
85750   int iLabel;                     /* Label resolved to end of generated code */
85751 
85752   /* Vdbe is guaranteed to have been allocated by this stage. */
85753   assert( v );
85754 
85755   /* Seek cursor iCur to the row to delete. If this row no longer exists
85756   ** (this can happen if a trigger program has already deleted it), do
85757   ** not attempt to delete it or fire any DELETE triggers.  */
85758   iLabel = sqlite3VdbeMakeLabel(v);
85759   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85760 
85761   /* If there are any triggers to fire, allocate a range of registers to
85762   ** use for the old.* references in the triggers.  */
85763   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85764     u32 mask;                     /* Mask of OLD.* columns in use */
85765     int iCol;                     /* Iterator used while populating OLD.* */
85766 
85767     /* TODO: Could use temporary registers here. Also could attempt to
85768     ** avoid copying the contents of the rowid register.  */
85769     mask = sqlite3TriggerColmask(
85770         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85771     );
85772     mask |= sqlite3FkOldmask(pParse, pTab);
85773     iOld = pParse->nMem+1;
85774     pParse->nMem += (1 + pTab->nCol);
85775 
85776     /* Populate the OLD.* pseudo-table register array. These values will be
85777     ** used by any BEFORE and AFTER triggers that exist.  */
85778     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
85779     for(iCol=0; iCol<pTab->nCol; iCol++){
85780       if( mask==0xffffffff || mask&(1<<iCol) ){
85781         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
85782       }
85783     }
85784 
85785     /* Invoke BEFORE DELETE trigger programs. */
85786     sqlite3CodeRowTrigger(pParse, pTrigger,
85787         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
85788     );
85789 
85790     /* Seek the cursor to the row to be deleted again. It may be that
85791     ** the BEFORE triggers coded above have already removed the row
85792     ** being deleted. Do not attempt to delete the row a second time, and
85793     ** do not fire AFTER triggers.  */
85794     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85795 
85796     /* Do FK processing. This call checks that any FK constraints that
85797     ** refer to this table (i.e. constraints attached to other tables)
85798     ** are not violated by deleting this row.  */
85799     sqlite3FkCheck(pParse, pTab, iOld, 0);
85800   }
85801 
85802   /* Delete the index and table entries. Skip this step if pTab is really
85803   ** a view (in which case the only effect of the DELETE statement is to
85804   ** fire the INSTEAD OF triggers).  */
85805   if( pTab->pSelect==0 ){
85806     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
85807     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
85808     if( count ){
85809       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
85810     }
85811   }
85812 
85813   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85814   ** handle rows (possibly in other tables) that refer via a foreign key
85815   ** to the row just deleted. */
85816   sqlite3FkActions(pParse, pTab, 0, iOld);
85817 
85818   /* Invoke AFTER DELETE trigger programs. */
85819   sqlite3CodeRowTrigger(pParse, pTrigger,
85820       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
85821   );
85822 
85823   /* Jump here if the row had already been deleted before any BEFORE
85824   ** trigger programs were invoked. Or if a trigger program throws a
85825   ** RAISE(IGNORE) exception.  */
85826   sqlite3VdbeResolveLabel(v, iLabel);
85827 }
85828 
85829 /*
85830 ** This routine generates VDBE code that causes the deletion of all
85831 ** index entries associated with a single row of a single table.
85832 **
85833 ** The VDBE must be in a particular state when this routine is called.
85834 ** These are the requirements:
85835 **
85836 **   1.  A read/write cursor pointing to pTab, the table containing the row
85837 **       to be deleted, must be opened as cursor number "iCur".
85838 **
85839 **   2.  Read/write cursors for all indices of pTab must be open as
85840 **       cursor number iCur+i for the i-th index.
85841 **
85842 **   3.  The "iCur" cursor must be pointing to the row that is to be
85843 **       deleted.
85844 */
85845 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
85846   Parse *pParse,     /* Parsing and code generating context */
85847   Table *pTab,       /* Table containing the row to be deleted */
85848   int iCur,          /* Cursor number for the table */
85849   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
85850 ){
85851   int i;
85852   Index *pIdx;
85853   int r1;
85854 
85855   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85856     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
85857     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
85858     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
85859   }
85860 }
85861 
85862 /*
85863 ** Generate code that will assemble an index key and put it in register
85864 ** regOut.  The key with be for index pIdx which is an index on pTab.
85865 ** iCur is the index of a cursor open on the pTab table and pointing to
85866 ** the entry that needs indexing.
85867 **
85868 ** Return a register number which is the first in a block of
85869 ** registers that holds the elements of the index key.  The
85870 ** block of registers has already been deallocated by the time
85871 ** this routine returns.
85872 */
85873 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
85874   Parse *pParse,     /* Parsing context */
85875   Index *pIdx,       /* The index for which to generate a key */
85876   int iCur,          /* Cursor number for the pIdx->pTable table */
85877   int regOut,        /* Write the new index key to this register */
85878   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
85879 ){
85880   Vdbe *v = pParse->pVdbe;
85881   int j;
85882   Table *pTab = pIdx->pTable;
85883   int regBase;
85884   int nCol;
85885 
85886   nCol = pIdx->nColumn;
85887   regBase = sqlite3GetTempRange(pParse, nCol+1);
85888   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
85889   for(j=0; j<nCol; j++){
85890     int idx = pIdx->aiColumn[j];
85891     if( idx==pTab->iPKey ){
85892       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
85893     }else{
85894       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
85895       sqlite3ColumnDefault(v, pTab, idx, -1);
85896     }
85897   }
85898   if( doMakeRec ){
85899     const char *zAff;
85900     if( pTab->pSelect
85901      || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
85902     ){
85903       zAff = 0;
85904     }else{
85905       zAff = sqlite3IndexAffinityStr(v, pIdx);
85906     }
85907     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
85908     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
85909   }
85910   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
85911   return regBase;
85912 }
85913 
85914 /************** End of delete.c **********************************************/
85915 /************** Begin file func.c ********************************************/
85916 /*
85917 ** 2002 February 23
85918 **
85919 ** The author disclaims copyright to this source code.  In place of
85920 ** a legal notice, here is a blessing:
85921 **
85922 **    May you do good and not evil.
85923 **    May you find forgiveness for yourself and forgive others.
85924 **    May you share freely, never taking more than you give.
85925 **
85926 *************************************************************************
85927 ** This file contains the C functions that implement various SQL
85928 ** functions of SQLite.
85929 **
85930 ** There is only one exported symbol in this file - the function
85931 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
85932 ** All other code has file scope.
85933 */
85934 /* #include <stdlib.h> */
85935 /* #include <assert.h> */
85936 
85937 /*
85938 ** Return the collating function associated with a function.
85939 */
85940 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
85941   return context->pColl;
85942 }
85943 
85944 /*
85945 ** Indicate that the accumulator load should be skipped on this
85946 ** iteration of the aggregate loop.
85947 */
85948 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
85949   context->skipFlag = 1;
85950 }
85951 
85952 /*
85953 ** Implementation of the non-aggregate min() and max() functions
85954 */
85955 static void minmaxFunc(
85956   sqlite3_context *context,
85957   int argc,
85958   sqlite3_value **argv
85959 ){
85960   int i;
85961   int mask;    /* 0 for min() or 0xffffffff for max() */
85962   int iBest;
85963   CollSeq *pColl;
85964 
85965   assert( argc>1 );
85966   mask = sqlite3_user_data(context)==0 ? 0 : -1;
85967   pColl = sqlite3GetFuncCollSeq(context);
85968   assert( pColl );
85969   assert( mask==-1 || mask==0 );
85970   iBest = 0;
85971   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85972   for(i=1; i<argc; i++){
85973     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
85974     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
85975       testcase( mask==0 );
85976       iBest = i;
85977     }
85978   }
85979   sqlite3_result_value(context, argv[iBest]);
85980 }
85981 
85982 /*
85983 ** Return the type of the argument.
85984 */
85985 static void typeofFunc(
85986   sqlite3_context *context,
85987   int NotUsed,
85988   sqlite3_value **argv
85989 ){
85990   const char *z = 0;
85991   UNUSED_PARAMETER(NotUsed);
85992   switch( sqlite3_value_type(argv[0]) ){
85993     case SQLITE_INTEGER: z = "integer"; break;
85994     case SQLITE_TEXT:    z = "text";    break;
85995     case SQLITE_FLOAT:   z = "real";    break;
85996     case SQLITE_BLOB:    z = "blob";    break;
85997     default:             z = "null";    break;
85998   }
85999   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
86000 }
86001 
86002 
86003 /*
86004 ** Implementation of the length() function
86005 */
86006 static void lengthFunc(
86007   sqlite3_context *context,
86008   int argc,
86009   sqlite3_value **argv
86010 ){
86011   int len;
86012 
86013   assert( argc==1 );
86014   UNUSED_PARAMETER(argc);
86015   switch( sqlite3_value_type(argv[0]) ){
86016     case SQLITE_BLOB:
86017     case SQLITE_INTEGER:
86018     case SQLITE_FLOAT: {
86019       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
86020       break;
86021     }
86022     case SQLITE_TEXT: {
86023       const unsigned char *z = sqlite3_value_text(argv[0]);
86024       if( z==0 ) return;
86025       len = 0;
86026       while( *z ){
86027         len++;
86028         SQLITE_SKIP_UTF8(z);
86029       }
86030       sqlite3_result_int(context, len);
86031       break;
86032     }
86033     default: {
86034       sqlite3_result_null(context);
86035       break;
86036     }
86037   }
86038 }
86039 
86040 /*
86041 ** Implementation of the abs() function.
86042 **
86043 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
86044 ** the numeric argument X.
86045 */
86046 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86047   assert( argc==1 );
86048   UNUSED_PARAMETER(argc);
86049   switch( sqlite3_value_type(argv[0]) ){
86050     case SQLITE_INTEGER: {
86051       i64 iVal = sqlite3_value_int64(argv[0]);
86052       if( iVal<0 ){
86053         if( (iVal<<1)==0 ){
86054           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
86055           ** abs(X) throws an integer overflow error since there is no
86056           ** equivalent positive 64-bit two complement value. */
86057           sqlite3_result_error(context, "integer overflow", -1);
86058           return;
86059         }
86060         iVal = -iVal;
86061       }
86062       sqlite3_result_int64(context, iVal);
86063       break;
86064     }
86065     case SQLITE_NULL: {
86066       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
86067       sqlite3_result_null(context);
86068       break;
86069     }
86070     default: {
86071       /* Because sqlite3_value_double() returns 0.0 if the argument is not
86072       ** something that can be converted into a number, we have:
86073       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
86074       ** cannot be converted to a numeric value.
86075       */
86076       double rVal = sqlite3_value_double(argv[0]);
86077       if( rVal<0 ) rVal = -rVal;
86078       sqlite3_result_double(context, rVal);
86079       break;
86080     }
86081   }
86082 }
86083 
86084 /*
86085 ** Implementation of the instr() function.
86086 **
86087 ** instr(haystack,needle) finds the first occurrence of needle
86088 ** in haystack and returns the number of previous characters plus 1,
86089 ** or 0 if needle does not occur within haystack.
86090 **
86091 ** If both haystack and needle are BLOBs, then the result is one more than
86092 ** the number of bytes in haystack prior to the first occurrence of needle,
86093 ** or 0 if needle never occurs in haystack.
86094 */
86095 static void instrFunc(
86096   sqlite3_context *context,
86097   int argc,
86098   sqlite3_value **argv
86099 ){
86100   const unsigned char *zHaystack;
86101   const unsigned char *zNeedle;
86102   int nHaystack;
86103   int nNeedle;
86104   int typeHaystack, typeNeedle;
86105   int N = 1;
86106   int isText;
86107 
86108   UNUSED_PARAMETER(argc);
86109   typeHaystack = sqlite3_value_type(argv[0]);
86110   typeNeedle = sqlite3_value_type(argv[1]);
86111   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
86112   nHaystack = sqlite3_value_bytes(argv[0]);
86113   nNeedle = sqlite3_value_bytes(argv[1]);
86114   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
86115     zHaystack = sqlite3_value_blob(argv[0]);
86116     zNeedle = sqlite3_value_blob(argv[1]);
86117     isText = 0;
86118   }else{
86119     zHaystack = sqlite3_value_text(argv[0]);
86120     zNeedle = sqlite3_value_text(argv[1]);
86121     isText = 1;
86122   }
86123   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
86124     N++;
86125     do{
86126       nHaystack--;
86127       zHaystack++;
86128     }while( isText && (zHaystack[0]&0xc0)==0x80 );
86129   }
86130   if( nNeedle>nHaystack ) N = 0;
86131   sqlite3_result_int(context, N);
86132 }
86133 
86134 /*
86135 ** Implementation of the substr() function.
86136 **
86137 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
86138 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
86139 ** of x.  If x is text, then we actually count UTF-8 characters.
86140 ** If x is a blob, then we count bytes.
86141 **
86142 ** If p1 is negative, then we begin abs(p1) from the end of x[].
86143 **
86144 ** If p2 is negative, return the p2 characters preceeding p1.
86145 */
86146 static void substrFunc(
86147   sqlite3_context *context,
86148   int argc,
86149   sqlite3_value **argv
86150 ){
86151   const unsigned char *z;
86152   const unsigned char *z2;
86153   int len;
86154   int p0type;
86155   i64 p1, p2;
86156   int negP2 = 0;
86157 
86158   assert( argc==3 || argc==2 );
86159   if( sqlite3_value_type(argv[1])==SQLITE_NULL
86160    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
86161   ){
86162     return;
86163   }
86164   p0type = sqlite3_value_type(argv[0]);
86165   p1 = sqlite3_value_int(argv[1]);
86166   if( p0type==SQLITE_BLOB ){
86167     len = sqlite3_value_bytes(argv[0]);
86168     z = sqlite3_value_blob(argv[0]);
86169     if( z==0 ) return;
86170     assert( len==sqlite3_value_bytes(argv[0]) );
86171   }else{
86172     z = sqlite3_value_text(argv[0]);
86173     if( z==0 ) return;
86174     len = 0;
86175     if( p1<0 ){
86176       for(z2=z; *z2; len++){
86177         SQLITE_SKIP_UTF8(z2);
86178       }
86179     }
86180   }
86181   if( argc==3 ){
86182     p2 = sqlite3_value_int(argv[2]);
86183     if( p2<0 ){
86184       p2 = -p2;
86185       negP2 = 1;
86186     }
86187   }else{
86188     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
86189   }
86190   if( p1<0 ){
86191     p1 += len;
86192     if( p1<0 ){
86193       p2 += p1;
86194       if( p2<0 ) p2 = 0;
86195       p1 = 0;
86196     }
86197   }else if( p1>0 ){
86198     p1--;
86199   }else if( p2>0 ){
86200     p2--;
86201   }
86202   if( negP2 ){
86203     p1 -= p2;
86204     if( p1<0 ){
86205       p2 += p1;
86206       p1 = 0;
86207     }
86208   }
86209   assert( p1>=0 && p2>=0 );
86210   if( p0type!=SQLITE_BLOB ){
86211     while( *z && p1 ){
86212       SQLITE_SKIP_UTF8(z);
86213       p1--;
86214     }
86215     for(z2=z; *z2 && p2; p2--){
86216       SQLITE_SKIP_UTF8(z2);
86217     }
86218     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
86219   }else{
86220     if( p1+p2>len ){
86221       p2 = len-p1;
86222       if( p2<0 ) p2 = 0;
86223     }
86224     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
86225   }
86226 }
86227 
86228 /*
86229 ** Implementation of the round() function
86230 */
86231 #ifndef SQLITE_OMIT_FLOATING_POINT
86232 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86233   int n = 0;
86234   double r;
86235   char *zBuf;
86236   assert( argc==1 || argc==2 );
86237   if( argc==2 ){
86238     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
86239     n = sqlite3_value_int(argv[1]);
86240     if( n>30 ) n = 30;
86241     if( n<0 ) n = 0;
86242   }
86243   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86244   r = sqlite3_value_double(argv[0]);
86245   /* If Y==0 and X will fit in a 64-bit int,
86246   ** handle the rounding directly,
86247   ** otherwise use printf.
86248   */
86249   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86250     r = (double)((sqlite_int64)(r+0.5));
86251   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86252     r = -(double)((sqlite_int64)((-r)+0.5));
86253   }else{
86254     zBuf = sqlite3_mprintf("%.*f",n,r);
86255     if( zBuf==0 ){
86256       sqlite3_result_error_nomem(context);
86257       return;
86258     }
86259     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
86260     sqlite3_free(zBuf);
86261   }
86262   sqlite3_result_double(context, r);
86263 }
86264 #endif
86265 
86266 /*
86267 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
86268 ** allocation fails, call sqlite3_result_error_nomem() to notify
86269 ** the database handle that malloc() has failed and return NULL.
86270 ** If nByte is larger than the maximum string or blob length, then
86271 ** raise an SQLITE_TOOBIG exception and return NULL.
86272 */
86273 static void *contextMalloc(sqlite3_context *context, i64 nByte){
86274   char *z;
86275   sqlite3 *db = sqlite3_context_db_handle(context);
86276   assert( nByte>0 );
86277   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
86278   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86279   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86280     sqlite3_result_error_toobig(context);
86281     z = 0;
86282   }else{
86283     z = sqlite3Malloc((int)nByte);
86284     if( !z ){
86285       sqlite3_result_error_nomem(context);
86286     }
86287   }
86288   return z;
86289 }
86290 
86291 /*
86292 ** Implementation of the upper() and lower() SQL functions.
86293 */
86294 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86295   char *z1;
86296   const char *z2;
86297   int i, n;
86298   UNUSED_PARAMETER(argc);
86299   z2 = (char*)sqlite3_value_text(argv[0]);
86300   n = sqlite3_value_bytes(argv[0]);
86301   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86302   assert( z2==(char*)sqlite3_value_text(argv[0]) );
86303   if( z2 ){
86304     z1 = contextMalloc(context, ((i64)n)+1);
86305     if( z1 ){
86306       for(i=0; i<n; i++){
86307         z1[i] = (char)sqlite3Toupper(z2[i]);
86308       }
86309       sqlite3_result_text(context, z1, n, sqlite3_free);
86310     }
86311   }
86312 }
86313 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86314   char *z1;
86315   const char *z2;
86316   int i, n;
86317   UNUSED_PARAMETER(argc);
86318   z2 = (char*)sqlite3_value_text(argv[0]);
86319   n = sqlite3_value_bytes(argv[0]);
86320   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86321   assert( z2==(char*)sqlite3_value_text(argv[0]) );
86322   if( z2 ){
86323     z1 = contextMalloc(context, ((i64)n)+1);
86324     if( z1 ){
86325       for(i=0; i<n; i++){
86326         z1[i] = sqlite3Tolower(z2[i]);
86327       }
86328       sqlite3_result_text(context, z1, n, sqlite3_free);
86329     }
86330   }
86331 }
86332 
86333 /*
86334 ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
86335 ** that unused argument values do not have to be computed.  However, we
86336 ** still need some kind of function implementation for this routines in
86337 ** the function table.  That function implementation will never be called
86338 ** so it doesn't matter what the implementation is.  We might as well use
86339 ** the "version()" function as a substitute.
86340 */
86341 #define ifnullFunc versionFunc   /* Substitute function - never called */
86342 
86343 /*
86344 ** Implementation of random().  Return a random integer.
86345 */
86346 static void randomFunc(
86347   sqlite3_context *context,
86348   int NotUsed,
86349   sqlite3_value **NotUsed2
86350 ){
86351   sqlite_int64 r;
86352   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86353   sqlite3_randomness(sizeof(r), &r);
86354   if( r<0 ){
86355     /* We need to prevent a random number of 0x8000000000000000
86356     ** (or -9223372036854775808) since when you do abs() of that
86357     ** number of you get the same value back again.  To do this
86358     ** in a way that is testable, mask the sign bit off of negative
86359     ** values, resulting in a positive value.  Then take the
86360     ** 2s complement of that positive value.  The end result can
86361     ** therefore be no less than -9223372036854775807.
86362     */
86363     r = -(r & LARGEST_INT64);
86364   }
86365   sqlite3_result_int64(context, r);
86366 }
86367 
86368 /*
86369 ** Implementation of randomblob(N).  Return a random blob
86370 ** that is N bytes long.
86371 */
86372 static void randomBlob(
86373   sqlite3_context *context,
86374   int argc,
86375   sqlite3_value **argv
86376 ){
86377   int n;
86378   unsigned char *p;
86379   assert( argc==1 );
86380   UNUSED_PARAMETER(argc);
86381   n = sqlite3_value_int(argv[0]);
86382   if( n<1 ){
86383     n = 1;
86384   }
86385   p = contextMalloc(context, n);
86386   if( p ){
86387     sqlite3_randomness(n, p);
86388     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
86389   }
86390 }
86391 
86392 /*
86393 ** Implementation of the last_insert_rowid() SQL function.  The return
86394 ** value is the same as the sqlite3_last_insert_rowid() API function.
86395 */
86396 static void last_insert_rowid(
86397   sqlite3_context *context,
86398   int NotUsed,
86399   sqlite3_value **NotUsed2
86400 ){
86401   sqlite3 *db = sqlite3_context_db_handle(context);
86402   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86403   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86404   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
86405   ** function. */
86406   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
86407 }
86408 
86409 /*
86410 ** Implementation of the changes() SQL function.
86411 **
86412 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
86413 ** around the sqlite3_changes() C/C++ function and hence follows the same
86414 ** rules for counting changes.
86415 */
86416 static void changes(
86417   sqlite3_context *context,
86418   int NotUsed,
86419   sqlite3_value **NotUsed2
86420 ){
86421   sqlite3 *db = sqlite3_context_db_handle(context);
86422   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86423   sqlite3_result_int(context, sqlite3_changes(db));
86424 }
86425 
86426 /*
86427 ** Implementation of the total_changes() SQL function.  The return value is
86428 ** the same as the sqlite3_total_changes() API function.
86429 */
86430 static void total_changes(
86431   sqlite3_context *context,
86432   int NotUsed,
86433   sqlite3_value **NotUsed2
86434 ){
86435   sqlite3 *db = sqlite3_context_db_handle(context);
86436   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86437   /* IMP: R-52756-41993 This function is a wrapper around the
86438   ** sqlite3_total_changes() C/C++ interface. */
86439   sqlite3_result_int(context, sqlite3_total_changes(db));
86440 }
86441 
86442 /*
86443 ** A structure defining how to do GLOB-style comparisons.
86444 */
86445 struct compareInfo {
86446   u8 matchAll;
86447   u8 matchOne;
86448   u8 matchSet;
86449   u8 noCase;
86450 };
86451 
86452 /*
86453 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
86454 ** character is exactly one byte in size.  Also, all characters are
86455 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
86456 ** whereas only characters less than 0x80 do in ASCII.
86457 */
86458 #if defined(SQLITE_EBCDIC)
86459 # define sqlite3Utf8Read(A)    (*((*A)++))
86460 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
86461 #else
86462 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
86463 #endif
86464 
86465 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86466 /* The correct SQL-92 behavior is for the LIKE operator to ignore
86467 ** case.  Thus  'a' LIKE 'A' would be true. */
86468 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86469 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86470 ** is case sensitive causing 'a' LIKE 'A' to be false */
86471 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86472 
86473 /*
86474 ** Compare two UTF-8 strings for equality where the first string can
86475 ** potentially be a "glob" expression.  Return true (1) if they
86476 ** are the same and false (0) if they are different.
86477 **
86478 ** Globbing rules:
86479 **
86480 **      '*'       Matches any sequence of zero or more characters.
86481 **
86482 **      '?'       Matches exactly one character.
86483 **
86484 **     [...]      Matches one character from the enclosed list of
86485 **                characters.
86486 **
86487 **     [^...]     Matches one character not in the enclosed list.
86488 **
86489 ** With the [...] and [^...] matching, a ']' character can be included
86490 ** in the list by making it the first character after '[' or '^'.  A
86491 ** range of characters can be specified using '-'.  Example:
86492 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
86493 ** it the last character in the list.
86494 **
86495 ** This routine is usually quick, but can be N**2 in the worst case.
86496 **
86497 ** Hints: to match '*' or '?', put them in "[]".  Like this:
86498 **
86499 **         abc[*]xyz        Matches "abc*xyz" only
86500 */
86501 static int patternCompare(
86502   const u8 *zPattern,              /* The glob pattern */
86503   const u8 *zString,               /* The string to compare against the glob */
86504   const struct compareInfo *pInfo, /* Information about how to do the compare */
86505   u32 esc                          /* The escape character */
86506 ){
86507   u32 c, c2;
86508   int invert;
86509   int seen;
86510   u8 matchOne = pInfo->matchOne;
86511   u8 matchAll = pInfo->matchAll;
86512   u8 matchSet = pInfo->matchSet;
86513   u8 noCase = pInfo->noCase;
86514   int prevEscape = 0;     /* True if the previous character was 'escape' */
86515 
86516   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
86517     if( c==matchAll && !prevEscape ){
86518       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
86519                || c == matchOne ){
86520         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
86521           return 0;
86522         }
86523       }
86524       if( c==0 ){
86525         return 1;
86526       }else if( c==esc ){
86527         c = sqlite3Utf8Read(&zPattern);
86528         if( c==0 ){
86529           return 0;
86530         }
86531       }else if( c==matchSet ){
86532         assert( esc==0 );         /* This is GLOB, not LIKE */
86533         assert( matchSet<0x80 );  /* '[' is a single-byte character */
86534         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86535           SQLITE_SKIP_UTF8(zString);
86536         }
86537         return *zString!=0;
86538       }
86539       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
86540         if( noCase ){
86541           GlogUpperToLower(c2);
86542           GlogUpperToLower(c);
86543           while( c2 != 0 && c2 != c ){
86544             c2 = sqlite3Utf8Read(&zString);
86545             GlogUpperToLower(c2);
86546           }
86547         }else{
86548           while( c2 != 0 && c2 != c ){
86549             c2 = sqlite3Utf8Read(&zString);
86550           }
86551         }
86552         if( c2==0 ) return 0;
86553         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86554       }
86555       return 0;
86556     }else if( c==matchOne && !prevEscape ){
86557       if( sqlite3Utf8Read(&zString)==0 ){
86558         return 0;
86559       }
86560     }else if( c==matchSet ){
86561       u32 prior_c = 0;
86562       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86563       seen = 0;
86564       invert = 0;
86565       c = sqlite3Utf8Read(&zString);
86566       if( c==0 ) return 0;
86567       c2 = sqlite3Utf8Read(&zPattern);
86568       if( c2=='^' ){
86569         invert = 1;
86570         c2 = sqlite3Utf8Read(&zPattern);
86571       }
86572       if( c2==']' ){
86573         if( c==']' ) seen = 1;
86574         c2 = sqlite3Utf8Read(&zPattern);
86575       }
86576       while( c2 && c2!=']' ){
86577         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86578           c2 = sqlite3Utf8Read(&zPattern);
86579           if( c>=prior_c && c<=c2 ) seen = 1;
86580           prior_c = 0;
86581         }else{
86582           if( c==c2 ){
86583             seen = 1;
86584           }
86585           prior_c = c2;
86586         }
86587         c2 = sqlite3Utf8Read(&zPattern);
86588       }
86589       if( c2==0 || (seen ^ invert)==0 ){
86590         return 0;
86591       }
86592     }else if( esc==c && !prevEscape ){
86593       prevEscape = 1;
86594     }else{
86595       c2 = sqlite3Utf8Read(&zString);
86596       if( noCase ){
86597         GlogUpperToLower(c);
86598         GlogUpperToLower(c2);
86599       }
86600       if( c!=c2 ){
86601         return 0;
86602       }
86603       prevEscape = 0;
86604     }
86605   }
86606   return *zString==0;
86607 }
86608 
86609 /*
86610 ** Count the number of times that the LIKE operator (or GLOB which is
86611 ** just a variation of LIKE) gets called.  This is used for testing
86612 ** only.
86613 */
86614 #ifdef SQLITE_TEST
86615 SQLITE_API int sqlite3_like_count = 0;
86616 #endif
86617 
86618 
86619 /*
86620 ** Implementation of the like() SQL function.  This function implements
86621 ** the build-in LIKE operator.  The first argument to the function is the
86622 ** pattern and the second argument is the string.  So, the SQL statements:
86623 **
86624 **       A LIKE B
86625 **
86626 ** is implemented as like(B,A).
86627 **
86628 ** This same function (with a different compareInfo structure) computes
86629 ** the GLOB operator.
86630 */
86631 static void likeFunc(
86632   sqlite3_context *context,
86633   int argc,
86634   sqlite3_value **argv
86635 ){
86636   const unsigned char *zA, *zB;
86637   u32 escape = 0;
86638   int nPat;
86639   sqlite3 *db = sqlite3_context_db_handle(context);
86640 
86641   zB = sqlite3_value_text(argv[0]);
86642   zA = sqlite3_value_text(argv[1]);
86643 
86644   /* Limit the length of the LIKE or GLOB pattern to avoid problems
86645   ** of deep recursion and N*N behavior in patternCompare().
86646   */
86647   nPat = sqlite3_value_bytes(argv[0]);
86648   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
86649   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86650   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
86651     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86652     return;
86653   }
86654   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
86655 
86656   if( argc==3 ){
86657     /* The escape character string must consist of a single UTF-8 character.
86658     ** Otherwise, return an error.
86659     */
86660     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
86661     if( zEsc==0 ) return;
86662     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
86663       sqlite3_result_error(context,
86664           "ESCAPE expression must be a single character", -1);
86665       return;
86666     }
86667     escape = sqlite3Utf8Read(&zEsc);
86668   }
86669   if( zA && zB ){
86670     struct compareInfo *pInfo = sqlite3_user_data(context);
86671 #ifdef SQLITE_TEST
86672     sqlite3_like_count++;
86673 #endif
86674 
86675     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86676   }
86677 }
86678 
86679 /*
86680 ** Implementation of the NULLIF(x,y) function.  The result is the first
86681 ** argument if the arguments are different.  The result is NULL if the
86682 ** arguments are equal to each other.
86683 */
86684 static void nullifFunc(
86685   sqlite3_context *context,
86686   int NotUsed,
86687   sqlite3_value **argv
86688 ){
86689   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
86690   UNUSED_PARAMETER(NotUsed);
86691   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
86692     sqlite3_result_value(context, argv[0]);
86693   }
86694 }
86695 
86696 /*
86697 ** Implementation of the sqlite_version() function.  The result is the version
86698 ** of the SQLite library that is running.
86699 */
86700 static void versionFunc(
86701   sqlite3_context *context,
86702   int NotUsed,
86703   sqlite3_value **NotUsed2
86704 ){
86705   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86706   /* IMP: R-48699-48617 This function is an SQL wrapper around the
86707   ** sqlite3_libversion() C-interface. */
86708   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
86709 }
86710 
86711 /*
86712 ** Implementation of the sqlite_source_id() function. The result is a string
86713 ** that identifies the particular version of the source code used to build
86714 ** SQLite.
86715 */
86716 static void sourceidFunc(
86717   sqlite3_context *context,
86718   int NotUsed,
86719   sqlite3_value **NotUsed2
86720 ){
86721   UNUSED_PARAMETER2(NotUsed, NotUsed2);
86722   /* IMP: R-24470-31136 This function is an SQL wrapper around the
86723   ** sqlite3_sourceid() C interface. */
86724   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
86725 }
86726 
86727 /*
86728 ** Implementation of the sqlite_log() function.  This is a wrapper around
86729 ** sqlite3_log().  The return value is NULL.  The function exists purely for
86730 ** its side-effects.
86731 */
86732 static void errlogFunc(
86733   sqlite3_context *context,
86734   int argc,
86735   sqlite3_value **argv
86736 ){
86737   UNUSED_PARAMETER(argc);
86738   UNUSED_PARAMETER(context);
86739   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
86740 }
86741 
86742 /*
86743 ** Implementation of the sqlite_compileoption_used() function.
86744 ** The result is an integer that identifies if the compiler option
86745 ** was used to build SQLite.
86746 */
86747 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86748 static void compileoptionusedFunc(
86749   sqlite3_context *context,
86750   int argc,
86751   sqlite3_value **argv
86752 ){
86753   const char *zOptName;
86754   assert( argc==1 );
86755   UNUSED_PARAMETER(argc);
86756   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
86757   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
86758   ** function.
86759   */
86760   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
86761     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
86762   }
86763 }
86764 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86765 
86766 /*
86767 ** Implementation of the sqlite_compileoption_get() function.
86768 ** The result is a string that identifies the compiler options
86769 ** used to build SQLite.
86770 */
86771 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86772 static void compileoptiongetFunc(
86773   sqlite3_context *context,
86774   int argc,
86775   sqlite3_value **argv
86776 ){
86777   int n;
86778   assert( argc==1 );
86779   UNUSED_PARAMETER(argc);
86780   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
86781   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
86782   */
86783   n = sqlite3_value_int(argv[0]);
86784   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
86785 }
86786 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86787 
86788 /* Array for converting from half-bytes (nybbles) into ASCII hex
86789 ** digits. */
86790 static const char hexdigits[] = {
86791   '0', '1', '2', '3', '4', '5', '6', '7',
86792   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
86793 };
86794 
86795 /*
86796 ** EXPERIMENTAL - This is not an official function.  The interface may
86797 ** change.  This function may disappear.  Do not write code that depends
86798 ** on this function.
86799 **
86800 ** Implementation of the QUOTE() function.  This function takes a single
86801 ** argument.  If the argument is numeric, the return value is the same as
86802 ** the argument.  If the argument is NULL, the return value is the string
86803 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
86804 ** single-quote escapes.
86805 */
86806 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86807   assert( argc==1 );
86808   UNUSED_PARAMETER(argc);
86809   switch( sqlite3_value_type(argv[0]) ){
86810     case SQLITE_FLOAT: {
86811       double r1, r2;
86812       char zBuf[50];
86813       r1 = sqlite3_value_double(argv[0]);
86814       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
86815       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
86816       if( r1!=r2 ){
86817         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
86818       }
86819       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
86820       break;
86821     }
86822     case SQLITE_INTEGER: {
86823       sqlite3_result_value(context, argv[0]);
86824       break;
86825     }
86826     case SQLITE_BLOB: {
86827       char *zText = 0;
86828       char const *zBlob = sqlite3_value_blob(argv[0]);
86829       int nBlob = sqlite3_value_bytes(argv[0]);
86830       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
86831       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
86832       if( zText ){
86833         int i;
86834         for(i=0; i<nBlob; i++){
86835           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
86836           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
86837         }
86838         zText[(nBlob*2)+2] = '\'';
86839         zText[(nBlob*2)+3] = '\0';
86840         zText[0] = 'X';
86841         zText[1] = '\'';
86842         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
86843         sqlite3_free(zText);
86844       }
86845       break;
86846     }
86847     case SQLITE_TEXT: {
86848       int i,j;
86849       u64 n;
86850       const unsigned char *zArg = sqlite3_value_text(argv[0]);
86851       char *z;
86852 
86853       if( zArg==0 ) return;
86854       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
86855       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
86856       if( z ){
86857         z[0] = '\'';
86858         for(i=0, j=1; zArg[i]; i++){
86859           z[j++] = zArg[i];
86860           if( zArg[i]=='\'' ){
86861             z[j++] = '\'';
86862           }
86863         }
86864         z[j++] = '\'';
86865         z[j] = 0;
86866         sqlite3_result_text(context, z, j, sqlite3_free);
86867       }
86868       break;
86869     }
86870     default: {
86871       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
86872       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
86873       break;
86874     }
86875   }
86876 }
86877 
86878 /*
86879 ** The unicode() function.  Return the integer unicode code-point value
86880 ** for the first character of the input string.
86881 */
86882 static void unicodeFunc(
86883   sqlite3_context *context,
86884   int argc,
86885   sqlite3_value **argv
86886 ){
86887   const unsigned char *z = sqlite3_value_text(argv[0]);
86888   (void)argc;
86889   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
86890 }
86891 
86892 /*
86893 ** The char() function takes zero or more arguments, each of which is
86894 ** an integer.  It constructs a string where each character of the string
86895 ** is the unicode character for the corresponding integer argument.
86896 */
86897 static void charFunc(
86898   sqlite3_context *context,
86899   int argc,
86900   sqlite3_value **argv
86901 ){
86902   unsigned char *z, *zOut;
86903   int i;
86904   zOut = z = sqlite3_malloc( argc*4 );
86905   if( z==0 ){
86906     sqlite3_result_error_nomem(context);
86907     return;
86908   }
86909   for(i=0; i<argc; i++){
86910     sqlite3_int64 x;
86911     unsigned c;
86912     x = sqlite3_value_int64(argv[i]);
86913     if( x<0 || x>0x10ffff ) x = 0xfffd;
86914     c = (unsigned)(x & 0x1fffff);
86915     if( c<0x00080 ){
86916       *zOut++ = (u8)(c&0xFF);
86917     }else if( c<0x00800 ){
86918       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
86919       *zOut++ = 0x80 + (u8)(c & 0x3F);
86920     }else if( c<0x10000 ){
86921       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
86922       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
86923       *zOut++ = 0x80 + (u8)(c & 0x3F);
86924     }else{
86925       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
86926       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
86927       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
86928       *zOut++ = 0x80 + (u8)(c & 0x3F);
86929     }                                                    \
86930   }
86931   sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
86932 }
86933 
86934 /*
86935 ** The hex() function.  Interpret the argument as a blob.  Return
86936 ** a hexadecimal rendering as text.
86937 */
86938 static void hexFunc(
86939   sqlite3_context *context,
86940   int argc,
86941   sqlite3_value **argv
86942 ){
86943   int i, n;
86944   const unsigned char *pBlob;
86945   char *zHex, *z;
86946   assert( argc==1 );
86947   UNUSED_PARAMETER(argc);
86948   pBlob = sqlite3_value_blob(argv[0]);
86949   n = sqlite3_value_bytes(argv[0]);
86950   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
86951   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
86952   if( zHex ){
86953     for(i=0; i<n; i++, pBlob++){
86954       unsigned char c = *pBlob;
86955       *(z++) = hexdigits[(c>>4)&0xf];
86956       *(z++) = hexdigits[c&0xf];
86957     }
86958     *z = 0;
86959     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
86960   }
86961 }
86962 
86963 /*
86964 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
86965 */
86966 static void zeroblobFunc(
86967   sqlite3_context *context,
86968   int argc,
86969   sqlite3_value **argv
86970 ){
86971   i64 n;
86972   sqlite3 *db = sqlite3_context_db_handle(context);
86973   assert( argc==1 );
86974   UNUSED_PARAMETER(argc);
86975   n = sqlite3_value_int64(argv[0]);
86976   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
86977   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86978   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86979     sqlite3_result_error_toobig(context);
86980   }else{
86981     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
86982   }
86983 }
86984 
86985 /*
86986 ** The replace() function.  Three arguments are all strings: call
86987 ** them A, B, and C. The result is also a string which is derived
86988 ** from A by replacing every occurance of B with C.  The match
86989 ** must be exact.  Collating sequences are not used.
86990 */
86991 static void replaceFunc(
86992   sqlite3_context *context,
86993   int argc,
86994   sqlite3_value **argv
86995 ){
86996   const unsigned char *zStr;        /* The input string A */
86997   const unsigned char *zPattern;    /* The pattern string B */
86998   const unsigned char *zRep;        /* The replacement string C */
86999   unsigned char *zOut;              /* The output */
87000   int nStr;                /* Size of zStr */
87001   int nPattern;            /* Size of zPattern */
87002   int nRep;                /* Size of zRep */
87003   i64 nOut;                /* Maximum size of zOut */
87004   int loopLimit;           /* Last zStr[] that might match zPattern[] */
87005   int i, j;                /* Loop counters */
87006 
87007   assert( argc==3 );
87008   UNUSED_PARAMETER(argc);
87009   zStr = sqlite3_value_text(argv[0]);
87010   if( zStr==0 ) return;
87011   nStr = sqlite3_value_bytes(argv[0]);
87012   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
87013   zPattern = sqlite3_value_text(argv[1]);
87014   if( zPattern==0 ){
87015     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
87016             || sqlite3_context_db_handle(context)->mallocFailed );
87017     return;
87018   }
87019   if( zPattern[0]==0 ){
87020     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
87021     sqlite3_result_value(context, argv[0]);
87022     return;
87023   }
87024   nPattern = sqlite3_value_bytes(argv[1]);
87025   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
87026   zRep = sqlite3_value_text(argv[2]);
87027   if( zRep==0 ) return;
87028   nRep = sqlite3_value_bytes(argv[2]);
87029   assert( zRep==sqlite3_value_text(argv[2]) );
87030   nOut = nStr + 1;
87031   assert( nOut<SQLITE_MAX_LENGTH );
87032   zOut = contextMalloc(context, (i64)nOut);
87033   if( zOut==0 ){
87034     return;
87035   }
87036   loopLimit = nStr - nPattern;
87037   for(i=j=0; i<=loopLimit; i++){
87038     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
87039       zOut[j++] = zStr[i];
87040     }else{
87041       u8 *zOld;
87042       sqlite3 *db = sqlite3_context_db_handle(context);
87043       nOut += nRep - nPattern;
87044       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
87045       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
87046       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87047         sqlite3_result_error_toobig(context);
87048         sqlite3_free(zOut);
87049         return;
87050       }
87051       zOld = zOut;
87052       zOut = sqlite3_realloc(zOut, (int)nOut);
87053       if( zOut==0 ){
87054         sqlite3_result_error_nomem(context);
87055         sqlite3_free(zOld);
87056         return;
87057       }
87058       memcpy(&zOut[j], zRep, nRep);
87059       j += nRep;
87060       i += nPattern-1;
87061     }
87062   }
87063   assert( j+nStr-i+1==nOut );
87064   memcpy(&zOut[j], &zStr[i], nStr-i);
87065   j += nStr - i;
87066   assert( j<=nOut );
87067   zOut[j] = 0;
87068   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
87069 }
87070 
87071 /*
87072 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
87073 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
87074 */
87075 static void trimFunc(
87076   sqlite3_context *context,
87077   int argc,
87078   sqlite3_value **argv
87079 ){
87080   const unsigned char *zIn;         /* Input string */
87081   const unsigned char *zCharSet;    /* Set of characters to trim */
87082   int nIn;                          /* Number of bytes in input */
87083   int flags;                        /* 1: trimleft  2: trimright  3: trim */
87084   int i;                            /* Loop counter */
87085   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
87086   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
87087   int nChar;                        /* Number of characters in zCharSet */
87088 
87089   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87090     return;
87091   }
87092   zIn = sqlite3_value_text(argv[0]);
87093   if( zIn==0 ) return;
87094   nIn = sqlite3_value_bytes(argv[0]);
87095   assert( zIn==sqlite3_value_text(argv[0]) );
87096   if( argc==1 ){
87097     static const unsigned char lenOne[] = { 1 };
87098     static unsigned char * const azOne[] = { (u8*)" " };
87099     nChar = 1;
87100     aLen = (u8*)lenOne;
87101     azChar = (unsigned char **)azOne;
87102     zCharSet = 0;
87103   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
87104     return;
87105   }else{
87106     const unsigned char *z;
87107     for(z=zCharSet, nChar=0; *z; nChar++){
87108       SQLITE_SKIP_UTF8(z);
87109     }
87110     if( nChar>0 ){
87111       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
87112       if( azChar==0 ){
87113         return;
87114       }
87115       aLen = (unsigned char*)&azChar[nChar];
87116       for(z=zCharSet, nChar=0; *z; nChar++){
87117         azChar[nChar] = (unsigned char *)z;
87118         SQLITE_SKIP_UTF8(z);
87119         aLen[nChar] = (u8)(z - azChar[nChar]);
87120       }
87121     }
87122   }
87123   if( nChar>0 ){
87124     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
87125     if( flags & 1 ){
87126       while( nIn>0 ){
87127         int len = 0;
87128         for(i=0; i<nChar; i++){
87129           len = aLen[i];
87130           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
87131         }
87132         if( i>=nChar ) break;
87133         zIn += len;
87134         nIn -= len;
87135       }
87136     }
87137     if( flags & 2 ){
87138       while( nIn>0 ){
87139         int len = 0;
87140         for(i=0; i<nChar; i++){
87141           len = aLen[i];
87142           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
87143         }
87144         if( i>=nChar ) break;
87145         nIn -= len;
87146       }
87147     }
87148     if( zCharSet ){
87149       sqlite3_free(azChar);
87150     }
87151   }
87152   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
87153 }
87154 
87155 
87156 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
87157 ** is only available if the SQLITE_SOUNDEX compile-time option is used
87158 ** when SQLite is built.
87159 */
87160 #ifdef SQLITE_SOUNDEX
87161 /*
87162 ** Compute the soundex encoding of a word.
87163 **
87164 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
87165 ** soundex encoding of the string X.
87166 */
87167 static void soundexFunc(
87168   sqlite3_context *context,
87169   int argc,
87170   sqlite3_value **argv
87171 ){
87172   char zResult[8];
87173   const u8 *zIn;
87174   int i, j;
87175   static const unsigned char iCode[] = {
87176     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87177     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87178     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87179     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87180     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87181     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87182     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87183     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87184   };
87185   assert( argc==1 );
87186   zIn = (u8*)sqlite3_value_text(argv[0]);
87187   if( zIn==0 ) zIn = (u8*)"";
87188   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
87189   if( zIn[i] ){
87190     u8 prevcode = iCode[zIn[i]&0x7f];
87191     zResult[0] = sqlite3Toupper(zIn[i]);
87192     for(j=1; j<4 && zIn[i]; i++){
87193       int code = iCode[zIn[i]&0x7f];
87194       if( code>0 ){
87195         if( code!=prevcode ){
87196           prevcode = code;
87197           zResult[j++] = code + '0';
87198         }
87199       }else{
87200         prevcode = 0;
87201       }
87202     }
87203     while( j<4 ){
87204       zResult[j++] = '0';
87205     }
87206     zResult[j] = 0;
87207     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
87208   }else{
87209     /* IMP: R-64894-50321 The string "?000" is returned if the argument
87210     ** is NULL or contains no ASCII alphabetic characters. */
87211     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
87212   }
87213 }
87214 #endif /* SQLITE_SOUNDEX */
87215 
87216 #ifndef SQLITE_OMIT_LOAD_EXTENSION
87217 /*
87218 ** A function that loads a shared-library extension then returns NULL.
87219 */
87220 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
87221   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
87222   const char *zProc;
87223   sqlite3 *db = sqlite3_context_db_handle(context);
87224   char *zErrMsg = 0;
87225 
87226   if( argc==2 ){
87227     zProc = (const char *)sqlite3_value_text(argv[1]);
87228   }else{
87229     zProc = 0;
87230   }
87231   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
87232     sqlite3_result_error(context, zErrMsg, -1);
87233     sqlite3_free(zErrMsg);
87234   }
87235 }
87236 #endif
87237 
87238 
87239 /*
87240 ** An instance of the following structure holds the context of a
87241 ** sum() or avg() aggregate computation.
87242 */
87243 typedef struct SumCtx SumCtx;
87244 struct SumCtx {
87245   double rSum;      /* Floating point sum */
87246   i64 iSum;         /* Integer sum */
87247   i64 cnt;          /* Number of elements summed */
87248   u8 overflow;      /* True if integer overflow seen */
87249   u8 approx;        /* True if non-integer value was input to the sum */
87250 };
87251 
87252 /*
87253 ** Routines used to compute the sum, average, and total.
87254 **
87255 ** The SUM() function follows the (broken) SQL standard which means
87256 ** that it returns NULL if it sums over no inputs.  TOTAL returns
87257 ** 0.0 in that case.  In addition, TOTAL always returns a float where
87258 ** SUM might return an integer if it never encounters a floating point
87259 ** value.  TOTAL never fails, but SUM might through an exception if
87260 ** it overflows an integer.
87261 */
87262 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87263   SumCtx *p;
87264   int type;
87265   assert( argc==1 );
87266   UNUSED_PARAMETER(argc);
87267   p = sqlite3_aggregate_context(context, sizeof(*p));
87268   type = sqlite3_value_numeric_type(argv[0]);
87269   if( p && type!=SQLITE_NULL ){
87270     p->cnt++;
87271     if( type==SQLITE_INTEGER ){
87272       i64 v = sqlite3_value_int64(argv[0]);
87273       p->rSum += v;
87274       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
87275         p->overflow = 1;
87276       }
87277     }else{
87278       p->rSum += sqlite3_value_double(argv[0]);
87279       p->approx = 1;
87280     }
87281   }
87282 }
87283 static void sumFinalize(sqlite3_context *context){
87284   SumCtx *p;
87285   p = sqlite3_aggregate_context(context, 0);
87286   if( p && p->cnt>0 ){
87287     if( p->overflow ){
87288       sqlite3_result_error(context,"integer overflow",-1);
87289     }else if( p->approx ){
87290       sqlite3_result_double(context, p->rSum);
87291     }else{
87292       sqlite3_result_int64(context, p->iSum);
87293     }
87294   }
87295 }
87296 static void avgFinalize(sqlite3_context *context){
87297   SumCtx *p;
87298   p = sqlite3_aggregate_context(context, 0);
87299   if( p && p->cnt>0 ){
87300     sqlite3_result_double(context, p->rSum/(double)p->cnt);
87301   }
87302 }
87303 static void totalFinalize(sqlite3_context *context){
87304   SumCtx *p;
87305   p = sqlite3_aggregate_context(context, 0);
87306   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
87307   sqlite3_result_double(context, p ? p->rSum : (double)0);
87308 }
87309 
87310 /*
87311 ** The following structure keeps track of state information for the
87312 ** count() aggregate function.
87313 */
87314 typedef struct CountCtx CountCtx;
87315 struct CountCtx {
87316   i64 n;
87317 };
87318 
87319 /*
87320 ** Routines to implement the count() aggregate function.
87321 */
87322 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87323   CountCtx *p;
87324   p = sqlite3_aggregate_context(context, sizeof(*p));
87325   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
87326     p->n++;
87327   }
87328 
87329 #ifndef SQLITE_OMIT_DEPRECATED
87330   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
87331   ** sure it still operates correctly, verify that its count agrees with our
87332   ** internal count when using count(*) and when the total count can be
87333   ** expressed as a 32-bit integer. */
87334   assert( argc==1 || p==0 || p->n>0x7fffffff
87335           || p->n==sqlite3_aggregate_count(context) );
87336 #endif
87337 }
87338 static void countFinalize(sqlite3_context *context){
87339   CountCtx *p;
87340   p = sqlite3_aggregate_context(context, 0);
87341   sqlite3_result_int64(context, p ? p->n : 0);
87342 }
87343 
87344 /*
87345 ** Routines to implement min() and max() aggregate functions.
87346 */
87347 static void minmaxStep(
87348   sqlite3_context *context,
87349   int NotUsed,
87350   sqlite3_value **argv
87351 ){
87352   Mem *pArg  = (Mem *)argv[0];
87353   Mem *pBest;
87354   UNUSED_PARAMETER(NotUsed);
87355 
87356   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
87357   if( !pBest ) return;
87358 
87359   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87360     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
87361   }else if( pBest->flags ){
87362     int max;
87363     int cmp;
87364     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87365     /* This step function is used for both the min() and max() aggregates,
87366     ** the only difference between the two being that the sense of the
87367     ** comparison is inverted. For the max() aggregate, the
87368     ** sqlite3_user_data() function returns (void *)-1. For min() it
87369     ** returns (void *)db, where db is the sqlite3* database pointer.
87370     ** Therefore the next statement sets variable 'max' to 1 for the max()
87371     ** aggregate, or 0 for min().
87372     */
87373     max = sqlite3_user_data(context)!=0;
87374     cmp = sqlite3MemCompare(pBest, pArg, pColl);
87375     if( (max && cmp<0) || (!max && cmp>0) ){
87376       sqlite3VdbeMemCopy(pBest, pArg);
87377     }else{
87378       sqlite3SkipAccumulatorLoad(context);
87379     }
87380   }else{
87381     sqlite3VdbeMemCopy(pBest, pArg);
87382   }
87383 }
87384 static void minMaxFinalize(sqlite3_context *context){
87385   sqlite3_value *pRes;
87386   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
87387   if( pRes ){
87388     if( pRes->flags ){
87389       sqlite3_result_value(context, pRes);
87390     }
87391     sqlite3VdbeMemRelease(pRes);
87392   }
87393 }
87394 
87395 /*
87396 ** group_concat(EXPR, ?SEPARATOR?)
87397 */
87398 static void groupConcatStep(
87399   sqlite3_context *context,
87400   int argc,
87401   sqlite3_value **argv
87402 ){
87403   const char *zVal;
87404   StrAccum *pAccum;
87405   const char *zSep;
87406   int nVal, nSep;
87407   assert( argc==1 || argc==2 );
87408   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87409   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
87410 
87411   if( pAccum ){
87412     sqlite3 *db = sqlite3_context_db_handle(context);
87413     int firstTerm = pAccum->useMalloc==0;
87414     pAccum->useMalloc = 2;
87415     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
87416     if( !firstTerm ){
87417       if( argc==2 ){
87418         zSep = (char*)sqlite3_value_text(argv[1]);
87419         nSep = sqlite3_value_bytes(argv[1]);
87420       }else{
87421         zSep = ",";
87422         nSep = 1;
87423       }
87424       sqlite3StrAccumAppend(pAccum, zSep, nSep);
87425     }
87426     zVal = (char*)sqlite3_value_text(argv[0]);
87427     nVal = sqlite3_value_bytes(argv[0]);
87428     sqlite3StrAccumAppend(pAccum, zVal, nVal);
87429   }
87430 }
87431 static void groupConcatFinalize(sqlite3_context *context){
87432   StrAccum *pAccum;
87433   pAccum = sqlite3_aggregate_context(context, 0);
87434   if( pAccum ){
87435     if( pAccum->tooBig ){
87436       sqlite3_result_error_toobig(context);
87437     }else if( pAccum->mallocFailed ){
87438       sqlite3_result_error_nomem(context);
87439     }else{
87440       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
87441                           sqlite3_free);
87442     }
87443   }
87444 }
87445 
87446 /*
87447 ** This routine does per-connection function registration.  Most
87448 ** of the built-in functions above are part of the global function set.
87449 ** This routine only deals with those that are not global.
87450 */
87451 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
87452   int rc = sqlite3_overload_function(db, "MATCH", 2);
87453   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
87454   if( rc==SQLITE_NOMEM ){
87455     db->mallocFailed = 1;
87456   }
87457 }
87458 
87459 /*
87460 ** Set the LIKEOPT flag on the 2-argument function with the given name.
87461 */
87462 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
87463   FuncDef *pDef;
87464   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
87465                              2, SQLITE_UTF8, 0);
87466   if( ALWAYS(pDef) ){
87467     pDef->flags = flagVal;
87468   }
87469 }
87470 
87471 /*
87472 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
87473 ** parameter determines whether or not the LIKE operator is case
87474 ** sensitive.  GLOB is always case sensitive.
87475 */
87476 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
87477   struct compareInfo *pInfo;
87478   if( caseSensitive ){
87479     pInfo = (struct compareInfo*)&likeInfoAlt;
87480   }else{
87481     pInfo = (struct compareInfo*)&likeInfoNorm;
87482   }
87483   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87484   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87485   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
87486       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87487   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
87488   setLikeOptFlag(db, "like",
87489       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
87490 }
87491 
87492 /*
87493 ** pExpr points to an expression which implements a function.  If
87494 ** it is appropriate to apply the LIKE optimization to that function
87495 ** then set aWc[0] through aWc[2] to the wildcard characters and
87496 ** return TRUE.  If the function is not a LIKE-style function then
87497 ** return FALSE.
87498 */
87499 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87500   FuncDef *pDef;
87501   if( pExpr->op!=TK_FUNCTION
87502    || !pExpr->x.pList
87503    || pExpr->x.pList->nExpr!=2
87504   ){
87505     return 0;
87506   }
87507   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87508   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
87509                              sqlite3Strlen30(pExpr->u.zToken),
87510                              2, SQLITE_UTF8, 0);
87511   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
87512     return 0;
87513   }
87514 
87515   /* The memcpy() statement assumes that the wildcard characters are
87516   ** the first three statements in the compareInfo structure.  The
87517   ** asserts() that follow verify that assumption
87518   */
87519   memcpy(aWc, pDef->pUserData, 3);
87520   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87521   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87522   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87523   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
87524   return 1;
87525 }
87526 
87527 /*
87528 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
87529 ** to the global function hash table.  This occurs at start-time (as
87530 ** a consequence of calling sqlite3_initialize()).
87531 **
87532 ** After this routine runs
87533 */
87534 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
87535   /*
87536   ** The following array holds FuncDef structures for all of the functions
87537   ** defined in this file.
87538   **
87539   ** The array cannot be constant since changes are made to the
87540   ** FuncDef.pHash elements at start-time.  The elements of this array
87541   ** are read-only after initialization is complete.
87542   */
87543   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
87544     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87545     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87546     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87547     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87548     FUNCTION(trim,               1, 3, 0, trimFunc         ),
87549     FUNCTION(trim,               2, 3, 0, trimFunc         ),
87550     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87551     FUNCTION(min,                0, 0, 1, 0                ),
87552     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87553     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87554     FUNCTION(max,                0, 1, 1, 0                ),
87555     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87556     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
87557     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
87558     FUNCTION(instr,              2, 0, 0, instrFunc        ),
87559     FUNCTION(substr,             2, 0, 0, substrFunc       ),
87560     FUNCTION(substr,             3, 0, 0, substrFunc       ),
87561     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
87562     FUNCTION(char,              -1, 0, 0, charFunc         ),
87563     FUNCTION(abs,                1, 0, 0, absFunc          ),
87564 #ifndef SQLITE_OMIT_FLOATING_POINT
87565     FUNCTION(round,              1, 0, 0, roundFunc        ),
87566     FUNCTION(round,              2, 0, 0, roundFunc        ),
87567 #endif
87568     FUNCTION(upper,              1, 0, 0, upperFunc        ),
87569     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87570     FUNCTION(coalesce,           1, 0, 0, 0                ),
87571     FUNCTION(coalesce,           0, 0, 0, 0                ),
87572     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
87573     FUNCTION(hex,                1, 0, 0, hexFunc          ),
87574     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
87575     FUNCTION(random,             0, 0, 0, randomFunc       ),
87576     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87577     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87578     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
87579     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
87580     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
87581 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87582     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87583     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87584 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87585     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87586     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87587     FUNCTION(changes,            0, 0, 0, changes          ),
87588     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87589     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87590     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87591   #ifdef SQLITE_SOUNDEX
87592     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87593   #endif
87594   #ifndef SQLITE_OMIT_LOAD_EXTENSION
87595     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87596     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87597   #endif
87598     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87599     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87600     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87601  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87602     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87603     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87604     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87605     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87606 
87607     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87608   #ifdef SQLITE_CASE_SENSITIVE_LIKE
87609     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87610     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87611   #else
87612     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
87613     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
87614   #endif
87615   };
87616 
87617   int i;
87618   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87619   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87620 
87621   for(i=0; i<ArraySize(aBuiltinFunc); i++){
87622     sqlite3FuncDefInsert(pHash, &aFunc[i]);
87623   }
87624   sqlite3RegisterDateTimeFunctions();
87625 #ifndef SQLITE_OMIT_ALTERTABLE
87626   sqlite3AlterFunctions();
87627 #endif
87628 }
87629 
87630 /************** End of func.c ************************************************/
87631 /************** Begin file fkey.c ********************************************/
87632 /*
87633 **
87634 ** The author disclaims copyright to this source code.  In place of
87635 ** a legal notice, here is a blessing:
87636 **
87637 **    May you do good and not evil.
87638 **    May you find forgiveness for yourself and forgive others.
87639 **    May you share freely, never taking more than you give.
87640 **
87641 *************************************************************************
87642 ** This file contains code used by the compiler to add foreign key
87643 ** support to compiled SQL statements.
87644 */
87645 
87646 #ifndef SQLITE_OMIT_FOREIGN_KEY
87647 #ifndef SQLITE_OMIT_TRIGGER
87648 
87649 /*
87650 ** Deferred and Immediate FKs
87651 ** --------------------------
87652 **
87653 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
87654 ** If an immediate foreign key constraint is violated,
87655 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
87656 ** statement transaction rolled back. If a
87657 ** deferred foreign key constraint is violated, no action is taken
87658 ** immediately. However if the application attempts to commit the
87659 ** transaction before fixing the constraint violation, the attempt fails.
87660 **
87661 ** Deferred constraints are implemented using a simple counter associated
87662 ** with the database handle. The counter is set to zero each time a
87663 ** database transaction is opened. Each time a statement is executed
87664 ** that causes a foreign key violation, the counter is incremented. Each
87665 ** time a statement is executed that removes an existing violation from
87666 ** the database, the counter is decremented. When the transaction is
87667 ** committed, the commit fails if the current value of the counter is
87668 ** greater than zero. This scheme has two big drawbacks:
87669 **
87670 **   * When a commit fails due to a deferred foreign key constraint,
87671 **     there is no way to tell which foreign constraint is not satisfied,
87672 **     or which row it is not satisfied for.
87673 **
87674 **   * If the database contains foreign key violations when the
87675 **     transaction is opened, this may cause the mechanism to malfunction.
87676 **
87677 ** Despite these problems, this approach is adopted as it seems simpler
87678 ** than the alternatives.
87679 **
87680 ** INSERT operations:
87681 **
87682 **   I.1) For each FK for which the table is the child table, search
87683 **        the parent table for a match. If none is found increment the
87684 **        constraint counter.
87685 **
87686 **   I.2) For each FK for which the table is the parent table,
87687 **        search the child table for rows that correspond to the new
87688 **        row in the parent table. Decrement the counter for each row
87689 **        found (as the constraint is now satisfied).
87690 **
87691 ** DELETE operations:
87692 **
87693 **   D.1) For each FK for which the table is the child table,
87694 **        search the parent table for a row that corresponds to the
87695 **        deleted row in the child table. If such a row is not found,
87696 **        decrement the counter.
87697 **
87698 **   D.2) For each FK for which the table is the parent table, search
87699 **        the child table for rows that correspond to the deleted row
87700 **        in the parent table. For each found increment the counter.
87701 **
87702 ** UPDATE operations:
87703 **
87704 **   An UPDATE command requires that all 4 steps above are taken, but only
87705 **   for FK constraints for which the affected columns are actually
87706 **   modified (values must be compared at runtime).
87707 **
87708 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87709 ** This simplifies the implementation a bit.
87710 **
87711 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
87712 ** resolution is considered to delete rows before the new row is inserted.
87713 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
87714 ** is thrown, even if the FK constraint would be satisfied after the new
87715 ** row is inserted.
87716 **
87717 ** Immediate constraints are usually handled similarly. The only difference
87718 ** is that the counter used is stored as part of each individual statement
87719 ** object (struct Vdbe). If, after the statement has run, its immediate
87720 ** constraint counter is greater than zero,
87721 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
87722 ** and the statement transaction is rolled back. An exception is an INSERT
87723 ** statement that inserts a single row only (no triggers). In this case,
87724 ** instead of using a counter, an exception is thrown immediately if the
87725 ** INSERT violates a foreign key constraint. This is necessary as such
87726 ** an INSERT does not open a statement transaction.
87727 **
87728 ** TODO: How should dropping a table be handled? How should renaming a
87729 ** table be handled?
87730 **
87731 **
87732 ** Query API Notes
87733 ** ---------------
87734 **
87735 ** Before coding an UPDATE or DELETE row operation, the code-generator
87736 ** for those two operations needs to know whether or not the operation
87737 ** requires any FK processing and, if so, which columns of the original
87738 ** row are required by the FK processing VDBE code (i.e. if FKs were
87739 ** implemented using triggers, which of the old.* columns would be
87740 ** accessed). No information is required by the code-generator before
87741 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
87742 ** generation code to query for this information are:
87743 **
87744 **   sqlite3FkRequired() - Test to see if FK processing is required.
87745 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
87746 **
87747 **
87748 ** Externally accessible module functions
87749 ** --------------------------------------
87750 **
87751 **   sqlite3FkCheck()    - Check for foreign key violations.
87752 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87753 **   sqlite3FkDelete()   - Delete an FKey structure.
87754 */
87755 
87756 /*
87757 ** VDBE Calling Convention
87758 ** -----------------------
87759 **
87760 ** Example:
87761 **
87762 **   For the following INSERT statement:
87763 **
87764 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87765 **     INSERT INTO t1 VALUES(1, 2, 3.1);
87766 **
87767 **   Register (x):        2    (type integer)
87768 **   Register (x+1):      1    (type integer)
87769 **   Register (x+2):      NULL (type NULL)
87770 **   Register (x+3):      3.1  (type real)
87771 */
87772 
87773 /*
87774 ** A foreign key constraint requires that the key columns in the parent
87775 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87776 ** Given that pParent is the parent table for foreign key constraint pFKey,
87777 ** search the schema for a unique index on the parent key columns.
87778 **
87779 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
87780 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
87781 ** is set to point to the unique index.
87782 **
87783 ** If the parent key consists of a single column (the foreign key constraint
87784 ** is not a composite foreign key), output variable *paiCol is set to NULL.
87785 ** Otherwise, it is set to point to an allocated array of size N, where
87786 ** N is the number of columns in the parent key. The first element of the
87787 ** array is the index of the child table column that is mapped by the FK
87788 ** constraint to the parent table column stored in the left-most column
87789 ** of index *ppIdx. The second element of the array is the index of the
87790 ** child table column that corresponds to the second left-most column of
87791 ** *ppIdx, and so on.
87792 **
87793 ** If the required index cannot be found, either because:
87794 **
87795 **   1) The named parent key columns do not exist, or
87796 **
87797 **   2) The named parent key columns do exist, but are not subject to a
87798 **      UNIQUE or PRIMARY KEY constraint, or
87799 **
87800 **   3) No parent key columns were provided explicitly as part of the
87801 **      foreign key definition, and the parent table does not have a
87802 **      PRIMARY KEY, or
87803 **
87804 **   4) No parent key columns were provided explicitly as part of the
87805 **      foreign key definition, and the PRIMARY KEY of the parent table
87806 **      consists of a a different number of columns to the child key in
87807 **      the child table.
87808 **
87809 ** then non-zero is returned, and a "foreign key mismatch" error loaded
87810 ** into pParse. If an OOM error occurs, non-zero is returned and the
87811 ** pParse->db->mallocFailed flag is set.
87812 */
87813 SQLITE_PRIVATE int sqlite3FkLocateIndex(
87814   Parse *pParse,                  /* Parse context to store any error in */
87815   Table *pParent,                 /* Parent table of FK constraint pFKey */
87816   FKey *pFKey,                    /* Foreign key to find index for */
87817   Index **ppIdx,                  /* OUT: Unique index on parent table */
87818   int **paiCol                    /* OUT: Map of index columns in pFKey */
87819 ){
87820   Index *pIdx = 0;                    /* Value to return via *ppIdx */
87821   int *aiCol = 0;                     /* Value to return via *paiCol */
87822   int nCol = pFKey->nCol;             /* Number of columns in parent key */
87823   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87824 
87825   /* The caller is responsible for zeroing output parameters. */
87826   assert( ppIdx && *ppIdx==0 );
87827   assert( !paiCol || *paiCol==0 );
87828   assert( pParse );
87829 
87830   /* If this is a non-composite (single column) foreign key, check if it
87831   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
87832   ** and *paiCol set to zero and return early.
87833   **
87834   ** Otherwise, for a composite foreign key (more than one column), allocate
87835   ** space for the aiCol array (returned via output parameter *paiCol).
87836   ** Non-composite foreign keys do not require the aiCol array.
87837   */
87838   if( nCol==1 ){
87839     /* The FK maps to the IPK if any of the following are true:
87840     **
87841     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
87842     **      mapped to the primary key of table pParent, or
87843     **   2) The FK is explicitly mapped to a column declared as INTEGER
87844     **      PRIMARY KEY.
87845     */
87846     if( pParent->iPKey>=0 ){
87847       if( !zKey ) return 0;
87848       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87849     }
87850   }else if( paiCol ){
87851     assert( nCol>1 );
87852     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
87853     if( !aiCol ) return 1;
87854     *paiCol = aiCol;
87855   }
87856 
87857   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87858     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
87859       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87860       ** of columns. If each indexed column corresponds to a foreign key
87861       ** column of pFKey, then this index is a winner.  */
87862 
87863       if( zKey==0 ){
87864         /* If zKey is NULL, then this foreign key is implicitly mapped to
87865         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
87866         ** identified by the test (Index.autoIndex==2).  */
87867         if( pIdx->autoIndex==2 ){
87868           if( aiCol ){
87869             int i;
87870             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87871           }
87872           break;
87873         }
87874       }else{
87875         /* If zKey is non-NULL, then this foreign key was declared to
87876         ** map to an explicit list of columns in table pParent. Check if this
87877         ** index matches those columns. Also, check that the index uses
87878         ** the default collation sequences for each column. */
87879         int i, j;
87880         for(i=0; i<nCol; i++){
87881           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
87882           char *zDfltColl;                  /* Def. collation for column */
87883           char *zIdxCol;                    /* Name of indexed column */
87884 
87885           /* If the index uses a collation sequence that is different from
87886           ** the default collation sequence for the column, this index is
87887           ** unusable. Bail out early in this case.  */
87888           zDfltColl = pParent->aCol[iCol].zColl;
87889           if( !zDfltColl ){
87890             zDfltColl = "BINARY";
87891           }
87892           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
87893 
87894           zIdxCol = pParent->aCol[iCol].zName;
87895           for(j=0; j<nCol; j++){
87896             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
87897               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
87898               break;
87899             }
87900           }
87901           if( j==nCol ) break;
87902         }
87903         if( i==nCol ) break;      /* pIdx is usable */
87904       }
87905     }
87906   }
87907 
87908   if( !pIdx ){
87909     if( !pParse->disableTriggers ){
87910       sqlite3ErrorMsg(pParse,
87911            "foreign key mismatch - \"%w\" referencing \"%w\"",
87912            pFKey->pFrom->zName, pFKey->zTo);
87913     }
87914     sqlite3DbFree(pParse->db, aiCol);
87915     return 1;
87916   }
87917 
87918   *ppIdx = pIdx;
87919   return 0;
87920 }
87921 
87922 /*
87923 ** This function is called when a row is inserted into or deleted from the
87924 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
87925 ** on the child table of pFKey, this function is invoked twice for each row
87926 ** affected - once to "delete" the old row, and then again to "insert" the
87927 ** new row.
87928 **
87929 ** Each time it is called, this function generates VDBE code to locate the
87930 ** row in the parent table that corresponds to the row being inserted into
87931 ** or deleted from the child table. If the parent row can be found, no
87932 ** special action is taken. Otherwise, if the parent row can *not* be
87933 ** found in the parent table:
87934 **
87935 **   Operation | FK type   | Action taken
87936 **   --------------------------------------------------------------------------
87937 **   INSERT      immediate   Increment the "immediate constraint counter".
87938 **
87939 **   DELETE      immediate   Decrement the "immediate constraint counter".
87940 **
87941 **   INSERT      deferred    Increment the "deferred constraint counter".
87942 **
87943 **   DELETE      deferred    Decrement the "deferred constraint counter".
87944 **
87945 ** These operations are identified in the comment at the top of this file
87946 ** (fkey.c) as "I.1" and "D.1".
87947 */
87948 static void fkLookupParent(
87949   Parse *pParse,        /* Parse context */
87950   int iDb,              /* Index of database housing pTab */
87951   Table *pTab,          /* Parent table of FK pFKey */
87952   Index *pIdx,          /* Unique index on parent key columns in pTab */
87953   FKey *pFKey,          /* Foreign key constraint */
87954   int *aiCol,           /* Map from parent key columns to child table columns */
87955   int regData,          /* Address of array containing child table row */
87956   int nIncr,            /* Increment constraint counter by this */
87957   int isIgnore          /* If true, pretend pTab contains all NULL values */
87958 ){
87959   int i;                                    /* Iterator variable */
87960   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
87961   int iCur = pParse->nTab - 1;              /* Cursor number to use */
87962   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
87963 
87964   /* If nIncr is less than zero, then check at runtime if there are any
87965   ** outstanding constraints to resolve. If there are not, there is no need
87966   ** to check if deleting this row resolves any outstanding violations.
87967   **
87968   ** Check if any of the key columns in the child table row are NULL. If
87969   ** any are, then the constraint is considered satisfied. No need to
87970   ** search for a matching row in the parent table.  */
87971   if( nIncr<0 ){
87972     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
87973   }
87974   for(i=0; i<pFKey->nCol; i++){
87975     int iReg = aiCol[i] + regData + 1;
87976     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
87977   }
87978 
87979   if( isIgnore==0 ){
87980     if( pIdx==0 ){
87981       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
87982       ** column of the parent table (table pTab).  */
87983       int iMustBeInt;               /* Address of MustBeInt instruction */
87984       int regTemp = sqlite3GetTempReg(pParse);
87985 
87986       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
87987       ** apply the affinity of the parent key). If this fails, then there
87988       ** is no matching parent key. Before using MustBeInt, make a copy of
87989       ** the value. Otherwise, the value inserted into the child key column
87990       ** will have INTEGER affinity applied to it, which may not be correct.  */
87991       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
87992       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
87993 
87994       /* If the parent table is the same as the child table, and we are about
87995       ** to increment the constraint-counter (i.e. this is an INSERT operation),
87996       ** then check if the row being inserted matches itself. If so, do not
87997       ** increment the constraint-counter.  */
87998       if( pTab==pFKey->pFrom && nIncr==1 ){
87999         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
88000       }
88001 
88002       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
88003       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
88004       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88005       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
88006       sqlite3VdbeJumpHere(v, iMustBeInt);
88007       sqlite3ReleaseTempReg(pParse, regTemp);
88008     }else{
88009       int nCol = pFKey->nCol;
88010       int regTemp = sqlite3GetTempRange(pParse, nCol);
88011       int regRec = sqlite3GetTempReg(pParse);
88012       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
88013 
88014       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
88015       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
88016       for(i=0; i<nCol; i++){
88017         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
88018       }
88019 
88020       /* If the parent table is the same as the child table, and we are about
88021       ** to increment the constraint-counter (i.e. this is an INSERT operation),
88022       ** then check if the row being inserted matches itself. If so, do not
88023       ** increment the constraint-counter.
88024       **
88025       ** If any of the parent-key values are NULL, then the row cannot match
88026       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
88027       ** of the parent-key values are NULL (at this point it is known that
88028       ** none of the child key values are).
88029       */
88030       if( pTab==pFKey->pFrom && nIncr==1 ){
88031         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
88032         for(i=0; i<nCol; i++){
88033           int iChild = aiCol[i]+1+regData;
88034           int iParent = pIdx->aiColumn[i]+1+regData;
88035           assert( aiCol[i]!=pTab->iPKey );
88036           if( pIdx->aiColumn[i]==pTab->iPKey ){
88037             /* The parent key is a composite key that includes the IPK column */
88038             iParent = regData;
88039           }
88040           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
88041           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
88042         }
88043         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88044       }
88045 
88046       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
88047       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
88048       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
88049 
88050       sqlite3ReleaseTempReg(pParse, regRec);
88051       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
88052     }
88053   }
88054 
88055   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88056     /* Special case: If this is an INSERT statement that will insert exactly
88057     ** one row into the table, raise a constraint immediately instead of
88058     ** incrementing a counter. This is necessary as the VM code is being
88059     ** generated for will not open a statement transaction.  */
88060     assert( nIncr==1 );
88061     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
88062         OE_Abort, "foreign key constraint failed", P4_STATIC
88063     );
88064   }else{
88065     if( nIncr>0 && pFKey->isDeferred==0 ){
88066       sqlite3ParseToplevel(pParse)->mayAbort = 1;
88067     }
88068     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88069   }
88070 
88071   sqlite3VdbeResolveLabel(v, iOk);
88072   sqlite3VdbeAddOp1(v, OP_Close, iCur);
88073 }
88074 
88075 /*
88076 ** This function is called to generate code executed when a row is deleted
88077 ** from the parent table of foreign key constraint pFKey and, if pFKey is
88078 ** deferred, when a row is inserted into the same table. When generating
88079 ** code for an SQL UPDATE operation, this function may be called twice -
88080 ** once to "delete" the old row and once to "insert" the new row.
88081 **
88082 ** The code generated by this function scans through the rows in the child
88083 ** table that correspond to the parent table row being deleted or inserted.
88084 ** For each child row found, one of the following actions is taken:
88085 **
88086 **   Operation | FK type   | Action taken
88087 **   --------------------------------------------------------------------------
88088 **   DELETE      immediate   Increment the "immediate constraint counter".
88089 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88090 **                           throw a "foreign key constraint failed" exception.
88091 **
88092 **   INSERT      immediate   Decrement the "immediate constraint counter".
88093 **
88094 **   DELETE      deferred    Increment the "deferred constraint counter".
88095 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88096 **                           throw a "foreign key constraint failed" exception.
88097 **
88098 **   INSERT      deferred    Decrement the "deferred constraint counter".
88099 **
88100 ** These operations are identified in the comment at the top of this file
88101 ** (fkey.c) as "I.2" and "D.2".
88102 */
88103 static void fkScanChildren(
88104   Parse *pParse,                  /* Parse context */
88105   SrcList *pSrc,                  /* SrcList containing the table to scan */
88106   Table *pTab,
88107   Index *pIdx,                    /* Foreign key index */
88108   FKey *pFKey,                    /* Foreign key relationship */
88109   int *aiCol,                     /* Map from pIdx cols to child table cols */
88110   int regData,                    /* Referenced table data starts here */
88111   int nIncr                       /* Amount to increment deferred counter by */
88112 ){
88113   sqlite3 *db = pParse->db;       /* Database handle */
88114   int i;                          /* Iterator variable */
88115   Expr *pWhere = 0;               /* WHERE clause to scan with */
88116   NameContext sNameContext;       /* Context used to resolve WHERE clause */
88117   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
88118   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
88119   Vdbe *v = sqlite3GetVdbe(pParse);
88120 
88121   assert( !pIdx || pIdx->pTable==pTab );
88122 
88123   if( nIncr<0 ){
88124     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
88125   }
88126 
88127   /* Create an Expr object representing an SQL expression like:
88128   **
88129   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
88130   **
88131   ** The collation sequence used for the comparison should be that of
88132   ** the parent key columns. The affinity of the parent key column should
88133   ** be applied to each child key value before the comparison takes place.
88134   */
88135   for(i=0; i<pFKey->nCol; i++){
88136     Expr *pLeft;                  /* Value from parent table row */
88137     Expr *pRight;                 /* Column ref to child table */
88138     Expr *pEq;                    /* Expression (pLeft = pRight) */
88139     int iCol;                     /* Index of column in child table */
88140     const char *zCol;             /* Name of column in child table */
88141 
88142     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88143     if( pLeft ){
88144       /* Set the collation sequence and affinity of the LHS of each TK_EQ
88145       ** expression to the parent key column defaults.  */
88146       if( pIdx ){
88147         Column *pCol;
88148         const char *zColl;
88149         iCol = pIdx->aiColumn[i];
88150         pCol = &pTab->aCol[iCol];
88151         if( pTab->iPKey==iCol ) iCol = -1;
88152         pLeft->iTable = regData+iCol+1;
88153         pLeft->affinity = pCol->affinity;
88154         zColl = pCol->zColl;
88155         if( zColl==0 ) zColl = db->pDfltColl->zName;
88156         pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
88157       }else{
88158         pLeft->iTable = regData;
88159         pLeft->affinity = SQLITE_AFF_INTEGER;
88160       }
88161     }
88162     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88163     assert( iCol>=0 );
88164     zCol = pFKey->pFrom->aCol[iCol].zName;
88165     pRight = sqlite3Expr(db, TK_ID, zCol);
88166     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
88167     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88168   }
88169 
88170   /* If the child table is the same as the parent table, and this scan
88171   ** is taking place as part of a DELETE operation (operation D.2), omit the
88172   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
88173   ** clause, where $rowid is the rowid of the row being deleted.  */
88174   if( pTab==pFKey->pFrom && nIncr>0 ){
88175     Expr *pEq;                    /* Expression (pLeft = pRight) */
88176     Expr *pLeft;                  /* Value from parent table row */
88177     Expr *pRight;                 /* Column ref to child table */
88178     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88179     pRight = sqlite3Expr(db, TK_COLUMN, 0);
88180     if( pLeft && pRight ){
88181       pLeft->iTable = regData;
88182       pLeft->affinity = SQLITE_AFF_INTEGER;
88183       pRight->iTable = pSrc->a[0].iCursor;
88184       pRight->iColumn = -1;
88185     }
88186     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
88187     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88188   }
88189 
88190   /* Resolve the references in the WHERE clause. */
88191   memset(&sNameContext, 0, sizeof(NameContext));
88192   sNameContext.pSrcList = pSrc;
88193   sNameContext.pParse = pParse;
88194   sqlite3ResolveExprNames(&sNameContext, pWhere);
88195 
88196   /* Create VDBE to loop through the entries in pSrc that match the WHERE
88197   ** clause. If the constraint is not deferred, throw an exception for
88198   ** each row found. Otherwise, for deferred constraints, increment the
88199   ** deferred constraint counter by nIncr for each row selected.  */
88200   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
88201   if( nIncr>0 && pFKey->isDeferred==0 ){
88202     sqlite3ParseToplevel(pParse)->mayAbort = 1;
88203   }
88204   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88205   if( pWInfo ){
88206     sqlite3WhereEnd(pWInfo);
88207   }
88208 
88209   /* Clean up the WHERE clause constructed above. */
88210   sqlite3ExprDelete(db, pWhere);
88211   if( iFkIfZero ){
88212     sqlite3VdbeJumpHere(v, iFkIfZero);
88213   }
88214 }
88215 
88216 /*
88217 ** This function returns a pointer to the head of a linked list of FK
88218 ** constraints for which table pTab is the parent table. For example,
88219 ** given the following schema:
88220 **
88221 **   CREATE TABLE t1(a PRIMARY KEY);
88222 **   CREATE TABLE t2(b REFERENCES t1(a);
88223 **
88224 ** Calling this function with table "t1" as an argument returns a pointer
88225 ** to the FKey structure representing the foreign key constraint on table
88226 ** "t2". Calling this function with "t2" as the argument would return a
88227 ** NULL pointer (as there are no FK constraints for which t2 is the parent
88228 ** table).
88229 */
88230 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
88231   int nName = sqlite3Strlen30(pTab->zName);
88232   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
88233 }
88234 
88235 /*
88236 ** The second argument is a Trigger structure allocated by the
88237 ** fkActionTrigger() routine. This function deletes the Trigger structure
88238 ** and all of its sub-components.
88239 **
88240 ** The Trigger structure or any of its sub-components may be allocated from
88241 ** the lookaside buffer belonging to database handle dbMem.
88242 */
88243 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
88244   if( p ){
88245     TriggerStep *pStep = p->step_list;
88246     sqlite3ExprDelete(dbMem, pStep->pWhere);
88247     sqlite3ExprListDelete(dbMem, pStep->pExprList);
88248     sqlite3SelectDelete(dbMem, pStep->pSelect);
88249     sqlite3ExprDelete(dbMem, p->pWhen);
88250     sqlite3DbFree(dbMem, p);
88251   }
88252 }
88253 
88254 /*
88255 ** This function is called to generate code that runs when table pTab is
88256 ** being dropped from the database. The SrcList passed as the second argument
88257 ** to this function contains a single entry guaranteed to resolve to
88258 ** table pTab.
88259 **
88260 ** Normally, no code is required. However, if either
88261 **
88262 **   (a) The table is the parent table of a FK constraint, or
88263 **   (b) The table is the child table of a deferred FK constraint and it is
88264 **       determined at runtime that there are outstanding deferred FK
88265 **       constraint violations in the database,
88266 **
88267 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88268 ** the table from the database. Triggers are disabled while running this
88269 ** DELETE, but foreign key actions are not.
88270 */
88271 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88272   sqlite3 *db = pParse->db;
88273   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88274     int iSkip = 0;
88275     Vdbe *v = sqlite3GetVdbe(pParse);
88276 
88277     assert( v );                  /* VDBE has already been allocated */
88278     if( sqlite3FkReferences(pTab)==0 ){
88279       /* Search for a deferred foreign key constraint for which this table
88280       ** is the child table. If one cannot be found, return without
88281       ** generating any VDBE code. If one can be found, then jump over
88282       ** the entire DELETE if there are no outstanding deferred constraints
88283       ** when this statement is run.  */
88284       FKey *p;
88285       for(p=pTab->pFKey; p; p=p->pNextFrom){
88286         if( p->isDeferred ) break;
88287       }
88288       if( !p ) return;
88289       iSkip = sqlite3VdbeMakeLabel(v);
88290       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88291     }
88292 
88293     pParse->disableTriggers = 1;
88294     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
88295     pParse->disableTriggers = 0;
88296 
88297     /* If the DELETE has generated immediate foreign key constraint
88298     ** violations, halt the VDBE and return an error at this point, before
88299     ** any modifications to the schema are made. This is because statement
88300     ** transactions are not able to rollback schema changes.  */
88301     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
88302     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
88303         OE_Abort, "foreign key constraint failed", P4_STATIC
88304     );
88305 
88306     if( iSkip ){
88307       sqlite3VdbeResolveLabel(v, iSkip);
88308     }
88309   }
88310 }
88311 
88312 /*
88313 ** This function is called when inserting, deleting or updating a row of
88314 ** table pTab to generate VDBE code to perform foreign key constraint
88315 ** processing for the operation.
88316 **
88317 ** For a DELETE operation, parameter regOld is passed the index of the
88318 ** first register in an array of (pTab->nCol+1) registers containing the
88319 ** rowid of the row being deleted, followed by each of the column values
88320 ** of the row being deleted, from left to right. Parameter regNew is passed
88321 ** zero in this case.
88322 **
88323 ** For an INSERT operation, regOld is passed zero and regNew is passed the
88324 ** first register of an array of (pTab->nCol+1) registers containing the new
88325 ** row data.
88326 **
88327 ** For an UPDATE operation, this function is called twice. Once before
88328 ** the original record is deleted from the table using the calling convention
88329 ** described for DELETE. Then again after the original record is deleted
88330 ** but before the new record is inserted using the INSERT convention.
88331 */
88332 SQLITE_PRIVATE void sqlite3FkCheck(
88333   Parse *pParse,                  /* Parse context */
88334   Table *pTab,                    /* Row is being deleted from this table */
88335   int regOld,                     /* Previous row data is stored here */
88336   int regNew                      /* New row data is stored here */
88337 ){
88338   sqlite3 *db = pParse->db;       /* Database handle */
88339   FKey *pFKey;                    /* Used to iterate through FKs */
88340   int iDb;                        /* Index of database containing pTab */
88341   const char *zDb;                /* Name of database containing pTab */
88342   int isIgnoreErrors = pParse->disableTriggers;
88343 
88344   /* Exactly one of regOld and regNew should be non-zero. */
88345   assert( (regOld==0)!=(regNew==0) );
88346 
88347   /* If foreign-keys are disabled, this function is a no-op. */
88348   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
88349 
88350   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88351   zDb = db->aDb[iDb].zName;
88352 
88353   /* Loop through all the foreign key constraints for which pTab is the
88354   ** child table (the table that the foreign key definition is part of).  */
88355   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88356     Table *pTo;                   /* Parent table of foreign key pFKey */
88357     Index *pIdx = 0;              /* Index on key columns in pTo */
88358     int *aiFree = 0;
88359     int *aiCol;
88360     int iCol;
88361     int i;
88362     int isIgnore = 0;
88363 
88364     /* Find the parent table of this foreign key. Also find a unique index
88365     ** on the parent key columns in the parent table. If either of these
88366     ** schema items cannot be located, set an error in pParse and return
88367     ** early.  */
88368     if( pParse->disableTriggers ){
88369       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
88370     }else{
88371       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
88372     }
88373     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88374       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88375       if( !isIgnoreErrors || db->mallocFailed ) return;
88376       if( pTo==0 ){
88377         /* If isIgnoreErrors is true, then a table is being dropped. In this
88378         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88379         ** before actually dropping it in order to check FK constraints.
88380         ** If the parent table of an FK constraint on the current table is
88381         ** missing, behave as if it is empty. i.e. decrement the relevant
88382         ** FK counter for each row of the current table with non-NULL keys.
88383         */
88384         Vdbe *v = sqlite3GetVdbe(pParse);
88385         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88386         for(i=0; i<pFKey->nCol; i++){
88387           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88388           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88389         }
88390         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88391       }
88392       continue;
88393     }
88394     assert( pFKey->nCol==1 || (aiFree && pIdx) );
88395 
88396     if( aiFree ){
88397       aiCol = aiFree;
88398     }else{
88399       iCol = pFKey->aCol[0].iFrom;
88400       aiCol = &iCol;
88401     }
88402     for(i=0; i<pFKey->nCol; i++){
88403       if( aiCol[i]==pTab->iPKey ){
88404         aiCol[i] = -1;
88405       }
88406 #ifndef SQLITE_OMIT_AUTHORIZATION
88407       /* Request permission to read the parent key columns. If the
88408       ** authorization callback returns SQLITE_IGNORE, behave as if any
88409       ** values read from the parent table are NULL. */
88410       if( db->xAuth ){
88411         int rcauth;
88412         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88413         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88414         isIgnore = (rcauth==SQLITE_IGNORE);
88415       }
88416 #endif
88417     }
88418 
88419     /* Take a shared-cache advisory read-lock on the parent table. Allocate
88420     ** a cursor to use to search the unique index on the parent key columns
88421     ** in the parent table.  */
88422     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88423     pParse->nTab++;
88424 
88425     if( regOld!=0 ){
88426       /* A row is being removed from the child table. Search for the parent.
88427       ** If the parent does not exist, removing the child row resolves an
88428       ** outstanding foreign key constraint violation. */
88429       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88430     }
88431     if( regNew!=0 ){
88432       /* A row is being added to the child table. If a parent row cannot
88433       ** be found, adding the child row has violated the FK constraint. */
88434       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88435     }
88436 
88437     sqlite3DbFree(db, aiFree);
88438   }
88439 
88440   /* Loop through all the foreign key constraints that refer to this table */
88441   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88442     Index *pIdx = 0;              /* Foreign key index for pFKey */
88443     SrcList *pSrc;
88444     int *aiCol = 0;
88445 
88446     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88447       assert( regOld==0 && regNew!=0 );
88448       /* Inserting a single row into a parent table cannot cause an immediate
88449       ** foreign key violation. So do nothing in this case.  */
88450       continue;
88451     }
88452 
88453     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88454       if( !isIgnoreErrors || db->mallocFailed ) return;
88455       continue;
88456     }
88457     assert( aiCol || pFKey->nCol==1 );
88458 
88459     /* Create a SrcList structure containing a single table (the table
88460     ** the foreign key that refers to this table is attached to). This
88461     ** is required for the sqlite3WhereXXX() interface.  */
88462     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88463     if( pSrc ){
88464       struct SrcList_item *pItem = pSrc->a;
88465       pItem->pTab = pFKey->pFrom;
88466       pItem->zName = pFKey->pFrom->zName;
88467       pItem->pTab->nRef++;
88468       pItem->iCursor = pParse->nTab++;
88469 
88470       if( regNew!=0 ){
88471         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88472       }
88473       if( regOld!=0 ){
88474         /* If there is a RESTRICT action configured for the current operation
88475         ** on the parent table of this FK, then throw an exception
88476         ** immediately if the FK constraint is violated, even if this is a
88477         ** deferred trigger. That's what RESTRICT means. To defer checking
88478         ** the constraint, the FK should specify NO ACTION (represented
88479         ** using OE_None). NO ACTION is the default.  */
88480         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88481       }
88482       pItem->zName = 0;
88483       sqlite3SrcListDelete(db, pSrc);
88484     }
88485     sqlite3DbFree(db, aiCol);
88486   }
88487 }
88488 
88489 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88490 
88491 /*
88492 ** This function is called before generating code to update or delete a
88493 ** row contained in table pTab.
88494 */
88495 SQLITE_PRIVATE u32 sqlite3FkOldmask(
88496   Parse *pParse,                  /* Parse context */
88497   Table *pTab                     /* Table being modified */
88498 ){
88499   u32 mask = 0;
88500   if( pParse->db->flags&SQLITE_ForeignKeys ){
88501     FKey *p;
88502     int i;
88503     for(p=pTab->pFKey; p; p=p->pNextFrom){
88504       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88505     }
88506     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88507       Index *pIdx = 0;
88508       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
88509       if( pIdx ){
88510         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88511       }
88512     }
88513   }
88514   return mask;
88515 }
88516 
88517 /*
88518 ** This function is called before generating code to update or delete a
88519 ** row contained in table pTab. If the operation is a DELETE, then
88520 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88521 ** to an array of size N, where N is the number of columns in table pTab.
88522 ** If the i'th column is not modified by the UPDATE, then the corresponding
88523 ** entry in the aChange[] array is set to -1. If the column is modified,
88524 ** the value is 0 or greater. Parameter chngRowid is set to true if the
88525 ** UPDATE statement modifies the rowid fields of the table.
88526 **
88527 ** If any foreign key processing will be required, this function returns
88528 ** true. If there is no foreign key related processing, this function
88529 ** returns false.
88530 */
88531 SQLITE_PRIVATE int sqlite3FkRequired(
88532   Parse *pParse,                  /* Parse context */
88533   Table *pTab,                    /* Table being modified */
88534   int *aChange,                   /* Non-NULL for UPDATE operations */
88535   int chngRowid                   /* True for UPDATE that affects rowid */
88536 ){
88537   if( pParse->db->flags&SQLITE_ForeignKeys ){
88538     if( !aChange ){
88539       /* A DELETE operation. Foreign key processing is required if the
88540       ** table in question is either the child or parent table for any
88541       ** foreign key constraint.  */
88542       return (sqlite3FkReferences(pTab) || pTab->pFKey);
88543     }else{
88544       /* This is an UPDATE. Foreign key processing is only required if the
88545       ** operation modifies one or more child or parent key columns. */
88546       int i;
88547       FKey *p;
88548 
88549       /* Check if any child key columns are being modified. */
88550       for(p=pTab->pFKey; p; p=p->pNextFrom){
88551         for(i=0; i<p->nCol; i++){
88552           int iChildKey = p->aCol[i].iFrom;
88553           if( aChange[iChildKey]>=0 ) return 1;
88554           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88555         }
88556       }
88557 
88558       /* Check if any parent key columns are being modified. */
88559       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88560         for(i=0; i<p->nCol; i++){
88561           char *zKey = p->aCol[i].zCol;
88562           int iKey;
88563           for(iKey=0; iKey<pTab->nCol; iKey++){
88564             Column *pCol = &pTab->aCol[iKey];
88565             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
88566                       : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
88567               if( aChange[iKey]>=0 ) return 1;
88568               if( iKey==pTab->iPKey && chngRowid ) return 1;
88569             }
88570           }
88571         }
88572       }
88573     }
88574   }
88575   return 0;
88576 }
88577 
88578 /*
88579 ** This function is called when an UPDATE or DELETE operation is being
88580 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
88581 ** If the current operation is an UPDATE, then the pChanges parameter is
88582 ** passed a pointer to the list of columns being modified. If it is a
88583 ** DELETE, pChanges is passed a NULL pointer.
88584 **
88585 ** It returns a pointer to a Trigger structure containing a trigger
88586 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88587 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88588 ** returned (these actions require no special handling by the triggers
88589 ** sub-system, code for them is created by fkScanChildren()).
88590 **
88591 ** For example, if pFKey is the foreign key and pTab is table "p" in
88592 ** the following schema:
88593 **
88594 **   CREATE TABLE p(pk PRIMARY KEY);
88595 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88596 **
88597 ** then the returned trigger structure is equivalent to:
88598 **
88599 **   CREATE TRIGGER ... DELETE ON p BEGIN
88600 **     DELETE FROM c WHERE ck = old.pk;
88601 **   END;
88602 **
88603 ** The returned pointer is cached as part of the foreign key object. It
88604 ** is eventually freed along with the rest of the foreign key object by
88605 ** sqlite3FkDelete().
88606 */
88607 static Trigger *fkActionTrigger(
88608   Parse *pParse,                  /* Parse context */
88609   Table *pTab,                    /* Table being updated or deleted from */
88610   FKey *pFKey,                    /* Foreign key to get action for */
88611   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88612 ){
88613   sqlite3 *db = pParse->db;       /* Database handle */
88614   int action;                     /* One of OE_None, OE_Cascade etc. */
88615   Trigger *pTrigger;              /* Trigger definition to return */
88616   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88617 
88618   action = pFKey->aAction[iAction];
88619   pTrigger = pFKey->apTrigger[iAction];
88620 
88621   if( action!=OE_None && !pTrigger ){
88622     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88623     char const *zFrom;            /* Name of child table */
88624     int nFrom;                    /* Length in bytes of zFrom */
88625     Index *pIdx = 0;              /* Parent key index for this FK */
88626     int *aiCol = 0;               /* child table cols -> parent key cols */
88627     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88628     Expr *pWhere = 0;             /* WHERE clause of trigger step */
88629     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88630     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88631     int i;                        /* Iterator variable */
88632     Expr *pWhen = 0;              /* WHEN clause for the trigger */
88633 
88634     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88635     assert( aiCol || pFKey->nCol==1 );
88636 
88637     for(i=0; i<pFKey->nCol; i++){
88638       Token tOld = { "old", 3 };  /* Literal "old" token */
88639       Token tNew = { "new", 3 };  /* Literal "new" token */
88640       Token tFromCol;             /* Name of column in child table */
88641       Token tToCol;               /* Name of column in parent table */
88642       int iFromCol;               /* Idx of column in child table */
88643       Expr *pEq;                  /* tFromCol = OLD.tToCol */
88644 
88645       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88646       assert( iFromCol>=0 );
88647       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88648       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88649 
88650       tToCol.n = sqlite3Strlen30(tToCol.z);
88651       tFromCol.n = sqlite3Strlen30(tFromCol.z);
88652 
88653       /* Create the expression "OLD.zToCol = zFromCol". It is important
88654       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88655       ** that the affinity and collation sequence associated with the
88656       ** parent table are used for the comparison. */
88657       pEq = sqlite3PExpr(pParse, TK_EQ,
88658           sqlite3PExpr(pParse, TK_DOT,
88659             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88660             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88661           , 0),
88662           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88663       , 0);
88664       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88665 
88666       /* For ON UPDATE, construct the next term of the WHEN clause.
88667       ** The final WHEN clause will be like this:
88668       **
88669       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88670       */
88671       if( pChanges ){
88672         pEq = sqlite3PExpr(pParse, TK_IS,
88673             sqlite3PExpr(pParse, TK_DOT,
88674               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88675               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88676               0),
88677             sqlite3PExpr(pParse, TK_DOT,
88678               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88679               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88680               0),
88681             0);
88682         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
88683       }
88684 
88685       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88686         Expr *pNew;
88687         if( action==OE_Cascade ){
88688           pNew = sqlite3PExpr(pParse, TK_DOT,
88689             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88690             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88691           , 0);
88692         }else if( action==OE_SetDflt ){
88693           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88694           if( pDflt ){
88695             pNew = sqlite3ExprDup(db, pDflt, 0);
88696           }else{
88697             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88698           }
88699         }else{
88700           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88701         }
88702         pList = sqlite3ExprListAppend(pParse, pList, pNew);
88703         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
88704       }
88705     }
88706     sqlite3DbFree(db, aiCol);
88707 
88708     zFrom = pFKey->pFrom->zName;
88709     nFrom = sqlite3Strlen30(zFrom);
88710 
88711     if( action==OE_Restrict ){
88712       Token tFrom;
88713       Expr *pRaise;
88714 
88715       tFrom.z = zFrom;
88716       tFrom.n = nFrom;
88717       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
88718       if( pRaise ){
88719         pRaise->affinity = OE_Abort;
88720       }
88721       pSelect = sqlite3SelectNew(pParse,
88722           sqlite3ExprListAppend(pParse, 0, pRaise),
88723           sqlite3SrcListAppend(db, 0, &tFrom, 0),
88724           pWhere,
88725           0, 0, 0, 0, 0, 0
88726       );
88727       pWhere = 0;
88728     }
88729 
88730     /* Disable lookaside memory allocation */
88731     enableLookaside = db->lookaside.bEnabled;
88732     db->lookaside.bEnabled = 0;
88733 
88734     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
88735         sizeof(Trigger) +         /* struct Trigger */
88736         sizeof(TriggerStep) +     /* Single step in trigger program */
88737         nFrom + 1                 /* Space for pStep->target.z */
88738     );
88739     if( pTrigger ){
88740       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88741       pStep->target.z = (char *)&pStep[1];
88742       pStep->target.n = nFrom;
88743       memcpy((char *)pStep->target.z, zFrom, nFrom);
88744 
88745       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88746       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
88747       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88748       if( pWhen ){
88749         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88750         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88751       }
88752     }
88753 
88754     /* Re-enable the lookaside buffer, if it was disabled earlier. */
88755     db->lookaside.bEnabled = enableLookaside;
88756 
88757     sqlite3ExprDelete(db, pWhere);
88758     sqlite3ExprDelete(db, pWhen);
88759     sqlite3ExprListDelete(db, pList);
88760     sqlite3SelectDelete(db, pSelect);
88761     if( db->mallocFailed==1 ){
88762       fkTriggerDelete(db, pTrigger);
88763       return 0;
88764     }
88765     assert( pStep!=0 );
88766 
88767     switch( action ){
88768       case OE_Restrict:
88769         pStep->op = TK_SELECT;
88770         break;
88771       case OE_Cascade:
88772         if( !pChanges ){
88773           pStep->op = TK_DELETE;
88774           break;
88775         }
88776       default:
88777         pStep->op = TK_UPDATE;
88778     }
88779     pStep->pTrig = pTrigger;
88780     pTrigger->pSchema = pTab->pSchema;
88781     pTrigger->pTabSchema = pTab->pSchema;
88782     pFKey->apTrigger[iAction] = pTrigger;
88783     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88784   }
88785 
88786   return pTrigger;
88787 }
88788 
88789 /*
88790 ** This function is called when deleting or updating a row to implement
88791 ** any required CASCADE, SET NULL or SET DEFAULT actions.
88792 */
88793 SQLITE_PRIVATE void sqlite3FkActions(
88794   Parse *pParse,                  /* Parse context */
88795   Table *pTab,                    /* Table being updated or deleted from */
88796   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88797   int regOld                      /* Address of array containing old row */
88798 ){
88799   /* If foreign-key support is enabled, iterate through all FKs that
88800   ** refer to table pTab. If there is an action associated with the FK
88801   ** for this operation (either update or delete), invoke the associated
88802   ** trigger sub-program.  */
88803   if( pParse->db->flags&SQLITE_ForeignKeys ){
88804     FKey *pFKey;                  /* Iterator variable */
88805     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88806       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88807       if( pAction ){
88808         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88809       }
88810     }
88811   }
88812 }
88813 
88814 #endif /* ifndef SQLITE_OMIT_TRIGGER */
88815 
88816 /*
88817 ** Free all memory associated with foreign key definitions attached to
88818 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88819 ** hash table.
88820 */
88821 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
88822   FKey *pFKey;                    /* Iterator variable */
88823   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88824 
88825   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
88826   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88827 
88828     /* Remove the FK from the fkeyHash hash table. */
88829     if( !db || db->pnBytesFreed==0 ){
88830       if( pFKey->pPrevTo ){
88831         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88832       }else{
88833         void *p = (void *)pFKey->pNextTo;
88834         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88835         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
88836       }
88837       if( pFKey->pNextTo ){
88838         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88839       }
88840     }
88841 
88842     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88843     ** classified as either immediate or deferred.
88844     */
88845     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88846 
88847     /* Delete any triggers created to implement actions for this FK. */
88848 #ifndef SQLITE_OMIT_TRIGGER
88849     fkTriggerDelete(db, pFKey->apTrigger[0]);
88850     fkTriggerDelete(db, pFKey->apTrigger[1]);
88851 #endif
88852 
88853     pNext = pFKey->pNextFrom;
88854     sqlite3DbFree(db, pFKey);
88855   }
88856 }
88857 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
88858 
88859 /************** End of fkey.c ************************************************/
88860 /************** Begin file insert.c ******************************************/
88861 /*
88862 ** 2001 September 15
88863 **
88864 ** The author disclaims copyright to this source code.  In place of
88865 ** a legal notice, here is a blessing:
88866 **
88867 **    May you do good and not evil.
88868 **    May you find forgiveness for yourself and forgive others.
88869 **    May you share freely, never taking more than you give.
88870 **
88871 *************************************************************************
88872 ** This file contains C code routines that are called by the parser
88873 ** to handle INSERT statements in SQLite.
88874 */
88875 
88876 /*
88877 ** Generate code that will open a table for reading.
88878 */
88879 SQLITE_PRIVATE void sqlite3OpenTable(
88880   Parse *p,       /* Generate code into this VDBE */
88881   int iCur,       /* The cursor number of the table */
88882   int iDb,        /* The database index in sqlite3.aDb[] */
88883   Table *pTab,    /* The table to be opened */
88884   int opcode      /* OP_OpenRead or OP_OpenWrite */
88885 ){
88886   Vdbe *v;
88887   assert( !IsVirtual(pTab) );
88888   v = sqlite3GetVdbe(p);
88889   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
88890   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
88891   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
88892   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
88893   VdbeComment((v, "%s", pTab->zName));
88894 }
88895 
88896 /*
88897 ** Return a pointer to the column affinity string associated with index
88898 ** pIdx. A column affinity string has one character for each column in
88899 ** the table, according to the affinity of the column:
88900 **
88901 **  Character      Column affinity
88902 **  ------------------------------
88903 **  'a'            TEXT
88904 **  'b'            NONE
88905 **  'c'            NUMERIC
88906 **  'd'            INTEGER
88907 **  'e'            REAL
88908 **
88909 ** An extra 'd' is appended to the end of the string to cover the
88910 ** rowid that appears as the last column in every index.
88911 **
88912 ** Memory for the buffer containing the column index affinity string
88913 ** is managed along with the rest of the Index structure. It will be
88914 ** released when sqlite3DeleteIndex() is called.
88915 */
88916 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
88917   if( !pIdx->zColAff ){
88918     /* The first time a column affinity string for a particular index is
88919     ** required, it is allocated and populated here. It is then stored as
88920     ** a member of the Index structure for subsequent use.
88921     **
88922     ** The column affinity string will eventually be deleted by
88923     ** sqliteDeleteIndex() when the Index structure itself is cleaned
88924     ** up.
88925     */
88926     int n;
88927     Table *pTab = pIdx->pTable;
88928     sqlite3 *db = sqlite3VdbeDb(v);
88929     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
88930     if( !pIdx->zColAff ){
88931       db->mallocFailed = 1;
88932       return 0;
88933     }
88934     for(n=0; n<pIdx->nColumn; n++){
88935       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
88936     }
88937     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
88938     pIdx->zColAff[n] = 0;
88939   }
88940 
88941   return pIdx->zColAff;
88942 }
88943 
88944 /*
88945 ** Set P4 of the most recently inserted opcode to a column affinity
88946 ** string for table pTab. A column affinity string has one character
88947 ** for each column indexed by the index, according to the affinity of the
88948 ** column:
88949 **
88950 **  Character      Column affinity
88951 **  ------------------------------
88952 **  'a'            TEXT
88953 **  'b'            NONE
88954 **  'c'            NUMERIC
88955 **  'd'            INTEGER
88956 **  'e'            REAL
88957 */
88958 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
88959   /* The first time a column affinity string for a particular table
88960   ** is required, it is allocated and populated here. It is then
88961   ** stored as a member of the Table structure for subsequent use.
88962   **
88963   ** The column affinity string will eventually be deleted by
88964   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
88965   */
88966   if( !pTab->zColAff ){
88967     char *zColAff;
88968     int i;
88969     sqlite3 *db = sqlite3VdbeDb(v);
88970 
88971     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
88972     if( !zColAff ){
88973       db->mallocFailed = 1;
88974       return;
88975     }
88976 
88977     for(i=0; i<pTab->nCol; i++){
88978       zColAff[i] = pTab->aCol[i].affinity;
88979     }
88980     zColAff[pTab->nCol] = '\0';
88981 
88982     pTab->zColAff = zColAff;
88983   }
88984 
88985   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
88986 }
88987 
88988 /*
88989 ** Return non-zero if the table pTab in database iDb or any of its indices
88990 ** have been opened at any point in the VDBE program beginning at location
88991 ** iStartAddr throught the end of the program.  This is used to see if
88992 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
88993 ** run without using temporary table for the results of the SELECT.
88994 */
88995 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
88996   Vdbe *v = sqlite3GetVdbe(p);
88997   int i;
88998   int iEnd = sqlite3VdbeCurrentAddr(v);
88999 #ifndef SQLITE_OMIT_VIRTUALTABLE
89000   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
89001 #endif
89002 
89003   for(i=iStartAddr; i<iEnd; i++){
89004     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
89005     assert( pOp!=0 );
89006     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
89007       Index *pIndex;
89008       int tnum = pOp->p2;
89009       if( tnum==pTab->tnum ){
89010         return 1;
89011       }
89012       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
89013         if( tnum==pIndex->tnum ){
89014           return 1;
89015         }
89016       }
89017     }
89018 #ifndef SQLITE_OMIT_VIRTUALTABLE
89019     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
89020       assert( pOp->p4.pVtab!=0 );
89021       assert( pOp->p4type==P4_VTAB );
89022       return 1;
89023     }
89024 #endif
89025   }
89026   return 0;
89027 }
89028 
89029 #ifndef SQLITE_OMIT_AUTOINCREMENT
89030 /*
89031 ** Locate or create an AutoincInfo structure associated with table pTab
89032 ** which is in database iDb.  Return the register number for the register
89033 ** that holds the maximum rowid.
89034 **
89035 ** There is at most one AutoincInfo structure per table even if the
89036 ** same table is autoincremented multiple times due to inserts within
89037 ** triggers.  A new AutoincInfo structure is created if this is the
89038 ** first use of table pTab.  On 2nd and subsequent uses, the original
89039 ** AutoincInfo structure is used.
89040 **
89041 ** Three memory locations are allocated:
89042 **
89043 **   (1)  Register to hold the name of the pTab table.
89044 **   (2)  Register to hold the maximum ROWID of pTab.
89045 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
89046 **
89047 ** The 2nd register is the one that is returned.  That is all the
89048 ** insert routine needs to know about.
89049 */
89050 static int autoIncBegin(
89051   Parse *pParse,      /* Parsing context */
89052   int iDb,            /* Index of the database holding pTab */
89053   Table *pTab         /* The table we are writing to */
89054 ){
89055   int memId = 0;      /* Register holding maximum rowid */
89056   if( pTab->tabFlags & TF_Autoincrement ){
89057     Parse *pToplevel = sqlite3ParseToplevel(pParse);
89058     AutoincInfo *pInfo;
89059 
89060     pInfo = pToplevel->pAinc;
89061     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
89062     if( pInfo==0 ){
89063       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
89064       if( pInfo==0 ) return 0;
89065       pInfo->pNext = pToplevel->pAinc;
89066       pToplevel->pAinc = pInfo;
89067       pInfo->pTab = pTab;
89068       pInfo->iDb = iDb;
89069       pToplevel->nMem++;                  /* Register to hold name of table */
89070       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
89071       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
89072     }
89073     memId = pInfo->regCtr;
89074   }
89075   return memId;
89076 }
89077 
89078 /*
89079 ** This routine generates code that will initialize all of the
89080 ** register used by the autoincrement tracker.
89081 */
89082 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
89083   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
89084   sqlite3 *db = pParse->db;  /* The database connection */
89085   Db *pDb;                   /* Database only autoinc table */
89086   int memId;                 /* Register holding max rowid */
89087   int addr;                  /* A VDBE address */
89088   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
89089 
89090   /* This routine is never called during trigger-generation.  It is
89091   ** only called from the top-level */
89092   assert( pParse->pTriggerTab==0 );
89093   assert( pParse==sqlite3ParseToplevel(pParse) );
89094 
89095   assert( v );   /* We failed long ago if this is not so */
89096   for(p = pParse->pAinc; p; p = p->pNext){
89097     pDb = &db->aDb[p->iDb];
89098     memId = p->regCtr;
89099     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89100     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
89101     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
89102     addr = sqlite3VdbeCurrentAddr(v);
89103     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
89104     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
89105     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
89106     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
89107     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89108     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89109     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
89110     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
89111     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
89112     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
89113     sqlite3VdbeAddOp0(v, OP_Close);
89114   }
89115 }
89116 
89117 /*
89118 ** Update the maximum rowid for an autoincrement calculation.
89119 **
89120 ** This routine should be called when the top of the stack holds a
89121 ** new rowid that is about to be inserted.  If that new rowid is
89122 ** larger than the maximum rowid in the memId memory cell, then the
89123 ** memory cell is updated.  The stack is unchanged.
89124 */
89125 static void autoIncStep(Parse *pParse, int memId, int regRowid){
89126   if( memId>0 ){
89127     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
89128   }
89129 }
89130 
89131 /*
89132 ** This routine generates the code needed to write autoincrement
89133 ** maximum rowid values back into the sqlite_sequence register.
89134 ** Every statement that might do an INSERT into an autoincrement
89135 ** table (either directly or through triggers) needs to call this
89136 ** routine just before the "exit" code.
89137 */
89138 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
89139   AutoincInfo *p;
89140   Vdbe *v = pParse->pVdbe;
89141   sqlite3 *db = pParse->db;
89142 
89143   assert( v );
89144   for(p = pParse->pAinc; p; p = p->pNext){
89145     Db *pDb = &db->aDb[p->iDb];
89146     int j1, j2, j3, j4, j5;
89147     int iRec;
89148     int memId = p->regCtr;
89149 
89150     iRec = sqlite3GetTempReg(pParse);
89151     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89152     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
89153     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
89154     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
89155     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
89156     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
89157     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
89158     sqlite3VdbeJumpHere(v, j2);
89159     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
89160     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
89161     sqlite3VdbeJumpHere(v, j4);
89162     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89163     sqlite3VdbeJumpHere(v, j1);
89164     sqlite3VdbeJumpHere(v, j5);
89165     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
89166     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
89167     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89168     sqlite3VdbeAddOp0(v, OP_Close);
89169     sqlite3ReleaseTempReg(pParse, iRec);
89170   }
89171 }
89172 #else
89173 /*
89174 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
89175 ** above are all no-ops
89176 */
89177 # define autoIncBegin(A,B,C) (0)
89178 # define autoIncStep(A,B,C)
89179 #endif /* SQLITE_OMIT_AUTOINCREMENT */
89180 
89181 
89182 /*
89183 ** Generate code for a co-routine that will evaluate a subquery one
89184 ** row at a time.
89185 **
89186 ** The pSelect parameter is the subquery that the co-routine will evaluation.
89187 ** Information about the location of co-routine and the registers it will use
89188 ** is returned by filling in the pDest object.
89189 **
89190 ** Registers are allocated as follows:
89191 **
89192 **   pDest->iSDParm      The register holding the next entry-point of the
89193 **                       co-routine.  Run the co-routine to its next breakpoint
89194 **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
89195 **
89196 **   pDest->iSDParm+1    The register holding the "completed" flag for the
89197 **                       co-routine. This register is 0 if the previous Yield
89198 **                       generated a new result row, or 1 if the subquery
89199 **                       has completed.  If the Yield is called again
89200 **                       after this register becomes 1, then the VDBE will
89201 **                       halt with an SQLITE_INTERNAL error.
89202 **
89203 **   pDest->iSdst        First result register.
89204 **
89205 **   pDest->nSdst        Number of result registers.
89206 **
89207 ** This routine handles all of the register allocation and fills in the
89208 ** pDest structure appropriately.
89209 **
89210 ** Here is a schematic of the generated code assuming that X is the
89211 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
89212 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
89213 ** registers that hold the result set, reg[pDest->iSdst] through
89214 ** reg[pDest->iSdst+pDest->nSdst-1]:
89215 **
89216 **         X <- A
89217 **         EOF <- 0
89218 **         goto B
89219 **      A: setup for the SELECT
89220 **         loop rows in the SELECT
89221 **           load results into registers R..S
89222 **           yield X
89223 **         end loop
89224 **         cleanup after the SELECT
89225 **         EOF <- 1
89226 **         yield X
89227 **         halt-error
89228 **      B:
89229 **
89230 ** To use this subroutine, the caller generates code as follows:
89231 **
89232 **         [ Co-routine generated by this subroutine, shown above ]
89233 **      S: yield X
89234 **         if EOF goto E
89235 **         if skip this row, goto C
89236 **         if terminate loop, goto E
89237 **         deal with this row
89238 **      C: goto S
89239 **      E:
89240 */
89241 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
89242   int regYield;       /* Register holding co-routine entry-point */
89243   int regEof;         /* Register holding co-routine completion flag */
89244   int addrTop;        /* Top of the co-routine */
89245   int j1;             /* Jump instruction */
89246   int rc;             /* Result code */
89247   Vdbe *v;            /* VDBE under construction */
89248 
89249   regYield = ++pParse->nMem;
89250   regEof = ++pParse->nMem;
89251   v = sqlite3GetVdbe(pParse);
89252   addrTop = sqlite3VdbeCurrentAddr(v);
89253   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
89254   VdbeComment((v, "Co-routine entry point"));
89255   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
89256   VdbeComment((v, "Co-routine completion flag"));
89257   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
89258   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
89259   rc = sqlite3Select(pParse, pSelect, pDest);
89260   assert( pParse->nErr==0 || rc );
89261   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
89262   if( rc ) return rc;
89263   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
89264   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
89265   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
89266   VdbeComment((v, "End of coroutine"));
89267   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
89268   return rc;
89269 }
89270 
89271 
89272 
89273 /* Forward declaration */
89274 static int xferOptimization(
89275   Parse *pParse,        /* Parser context */
89276   Table *pDest,         /* The table we are inserting into */
89277   Select *pSelect,      /* A SELECT statement to use as the data source */
89278   int onError,          /* How to handle constraint errors */
89279   int iDbDest           /* The database of pDest */
89280 );
89281 
89282 /*
89283 ** This routine is call to handle SQL of the following forms:
89284 **
89285 **    insert into TABLE (IDLIST) values(EXPRLIST)
89286 **    insert into TABLE (IDLIST) select
89287 **
89288 ** The IDLIST following the table name is always optional.  If omitted,
89289 ** then a list of all columns for the table is substituted.  The IDLIST
89290 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
89291 **
89292 ** The pList parameter holds EXPRLIST in the first form of the INSERT
89293 ** statement above, and pSelect is NULL.  For the second form, pList is
89294 ** NULL and pSelect is a pointer to the select statement used to generate
89295 ** data for the insert.
89296 **
89297 ** The code generated follows one of four templates.  For a simple
89298 ** select with data coming from a VALUES clause, the code executes
89299 ** once straight down through.  Pseudo-code follows (we call this
89300 ** the "1st template"):
89301 **
89302 **         open write cursor to <table> and its indices
89303 **         puts VALUES clause expressions onto the stack
89304 **         write the resulting record into <table>
89305 **         cleanup
89306 **
89307 ** The three remaining templates assume the statement is of the form
89308 **
89309 **   INSERT INTO <table> SELECT ...
89310 **
89311 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
89312 ** in other words if the SELECT pulls all columns from a single table
89313 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
89314 ** if <table2> and <table1> are distinct tables but have identical
89315 ** schemas, including all the same indices, then a special optimization
89316 ** is invoked that copies raw records from <table2> over to <table1>.
89317 ** See the xferOptimization() function for the implementation of this
89318 ** template.  This is the 2nd template.
89319 **
89320 **         open a write cursor to <table>
89321 **         open read cursor on <table2>
89322 **         transfer all records in <table2> over to <table>
89323 **         close cursors
89324 **         foreach index on <table>
89325 **           open a write cursor on the <table> index
89326 **           open a read cursor on the corresponding <table2> index
89327 **           transfer all records from the read to the write cursors
89328 **           close cursors
89329 **         end foreach
89330 **
89331 ** The 3rd template is for when the second template does not apply
89332 ** and the SELECT clause does not read from <table> at any time.
89333 ** The generated code follows this template:
89334 **
89335 **         EOF <- 0
89336 **         X <- A
89337 **         goto B
89338 **      A: setup for the SELECT
89339 **         loop over the rows in the SELECT
89340 **           load values into registers R..R+n
89341 **           yield X
89342 **         end loop
89343 **         cleanup after the SELECT
89344 **         EOF <- 1
89345 **         yield X
89346 **         goto A
89347 **      B: open write cursor to <table> and its indices
89348 **      C: yield X
89349 **         if EOF goto D
89350 **         insert the select result into <table> from R..R+n
89351 **         goto C
89352 **      D: cleanup
89353 **
89354 ** The 4th template is used if the insert statement takes its
89355 ** values from a SELECT but the data is being inserted into a table
89356 ** that is also read as part of the SELECT.  In the third form,
89357 ** we have to use a intermediate table to store the results of
89358 ** the select.  The template is like this:
89359 **
89360 **         EOF <- 0
89361 **         X <- A
89362 **         goto B
89363 **      A: setup for the SELECT
89364 **         loop over the tables in the SELECT
89365 **           load value into register R..R+n
89366 **           yield X
89367 **         end loop
89368 **         cleanup after the SELECT
89369 **         EOF <- 1
89370 **         yield X
89371 **         halt-error
89372 **      B: open temp table
89373 **      L: yield X
89374 **         if EOF goto M
89375 **         insert row from R..R+n into temp table
89376 **         goto L
89377 **      M: open write cursor to <table> and its indices
89378 **         rewind temp table
89379 **      C: loop over rows of intermediate table
89380 **           transfer values form intermediate table into <table>
89381 **         end loop
89382 **      D: cleanup
89383 */
89384 SQLITE_PRIVATE void sqlite3Insert(
89385   Parse *pParse,        /* Parser context */
89386   SrcList *pTabList,    /* Name of table into which we are inserting */
89387   ExprList *pList,      /* List of values to be inserted */
89388   Select *pSelect,      /* A SELECT statement to use as the data source */
89389   IdList *pColumn,      /* Column names corresponding to IDLIST. */
89390   int onError           /* How to handle constraint errors */
89391 ){
89392   sqlite3 *db;          /* The main database structure */
89393   Table *pTab;          /* The table to insert into.  aka TABLE */
89394   char *zTab;           /* Name of the table into which we are inserting */
89395   const char *zDb;      /* Name of the database holding this table */
89396   int i, j, idx;        /* Loop counters */
89397   Vdbe *v;              /* Generate code into this virtual machine */
89398   Index *pIdx;          /* For looping over indices of the table */
89399   int nColumn;          /* Number of columns in the data */
89400   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89401   int baseCur = 0;      /* VDBE Cursor number for pTab */
89402   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89403   int endOfLoop;        /* Label for the end of the insertion loop */
89404   int useTempTable = 0; /* Store SELECT results in intermediate table */
89405   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89406   int addrInsTop = 0;   /* Jump to label "D" */
89407   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89408   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89409   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89410   int iDb;              /* Index of database holding TABLE */
89411   Db *pDb;              /* The database containing table being inserted into */
89412   int appendFlag = 0;   /* True if the insert is likely to be an append */
89413 
89414   /* Register allocations */
89415   int regFromSelect = 0;/* Base register for data coming from SELECT */
89416   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89417   int regRowCount = 0;  /* Memory cell used for the row counter */
89418   int regIns;           /* Block of regs holding rowid+data being inserted */
89419   int regRowid;         /* registers holding insert rowid */
89420   int regData;          /* register holding first column to insert */
89421   int regEof = 0;       /* Register recording end of SELECT data */
89422   int *aRegIdx = 0;     /* One register allocated to each index */
89423 
89424 #ifndef SQLITE_OMIT_TRIGGER
89425   int isView;                 /* True if attempting to insert into a view */
89426   Trigger *pTrigger;          /* List of triggers on pTab, if required */
89427   int tmask;                  /* Mask of trigger times */
89428 #endif
89429 
89430   db = pParse->db;
89431   memset(&dest, 0, sizeof(dest));
89432   if( pParse->nErr || db->mallocFailed ){
89433     goto insert_cleanup;
89434   }
89435 
89436   /* Locate the table into which we will be inserting new information.
89437   */
89438   assert( pTabList->nSrc==1 );
89439   zTab = pTabList->a[0].zName;
89440   if( NEVER(zTab==0) ) goto insert_cleanup;
89441   pTab = sqlite3SrcListLookup(pParse, pTabList);
89442   if( pTab==0 ){
89443     goto insert_cleanup;
89444   }
89445   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89446   assert( iDb<db->nDb );
89447   pDb = &db->aDb[iDb];
89448   zDb = pDb->zName;
89449   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
89450     goto insert_cleanup;
89451   }
89452 
89453   /* Figure out if we have any triggers and if the table being
89454   ** inserted into is a view
89455   */
89456 #ifndef SQLITE_OMIT_TRIGGER
89457   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89458   isView = pTab->pSelect!=0;
89459 #else
89460 # define pTrigger 0
89461 # define tmask 0
89462 # define isView 0
89463 #endif
89464 #ifdef SQLITE_OMIT_VIEW
89465 # undef isView
89466 # define isView 0
89467 #endif
89468   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89469 
89470   /* If pTab is really a view, make sure it has been initialized.
89471   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
89472   ** module table).
89473   */
89474   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89475     goto insert_cleanup;
89476   }
89477 
89478   /* Ensure that:
89479   *  (a) the table is not read-only,
89480   *  (b) that if it is a view then ON INSERT triggers exist
89481   */
89482   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
89483     goto insert_cleanup;
89484   }
89485 
89486   /* Allocate a VDBE
89487   */
89488   v = sqlite3GetVdbe(pParse);
89489   if( v==0 ) goto insert_cleanup;
89490   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
89491   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89492 
89493 #ifndef SQLITE_OMIT_XFER_OPT
89494   /* If the statement is of the form
89495   **
89496   **       INSERT INTO <table1> SELECT * FROM <table2>;
89497   **
89498   ** Then special optimizations can be applied that make the transfer
89499   ** very fast and which reduce fragmentation of indices.
89500   **
89501   ** This is the 2nd template.
89502   */
89503   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89504     assert( !pTrigger );
89505     assert( pList==0 );
89506     goto insert_end;
89507   }
89508 #endif /* SQLITE_OMIT_XFER_OPT */
89509 
89510   /* If this is an AUTOINCREMENT table, look up the sequence number in the
89511   ** sqlite_sequence table and store it in memory cell regAutoinc.
89512   */
89513   regAutoinc = autoIncBegin(pParse, iDb, pTab);
89514 
89515   /* Figure out how many columns of data are supplied.  If the data
89516   ** is coming from a SELECT statement, then generate a co-routine that
89517   ** produces a single row of the SELECT on each invocation.  The
89518   ** co-routine is the common header to the 3rd and 4th templates.
89519   */
89520   if( pSelect ){
89521     /* Data is coming from a SELECT.  Generate a co-routine to run that
89522     ** SELECT. */
89523     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
89524     if( rc ) goto insert_cleanup;
89525 
89526     regEof = dest.iSDParm + 1;
89527     regFromSelect = dest.iSdst;
89528     assert( pSelect->pEList );
89529     nColumn = pSelect->pEList->nExpr;
89530     assert( dest.nSdst==nColumn );
89531 
89532     /* Set useTempTable to TRUE if the result of the SELECT statement
89533     ** should be written into a temporary table (template 4).  Set to
89534     ** FALSE if each* row of the SELECT can be written directly into
89535     ** the destination table (template 3).
89536     **
89537     ** A temp table must be used if the table being updated is also one
89538     ** of the tables being read by the SELECT statement.  Also use a
89539     ** temp table in the case of row triggers.
89540     */
89541     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89542       useTempTable = 1;
89543     }
89544 
89545     if( useTempTable ){
89546       /* Invoke the coroutine to extract information from the SELECT
89547       ** and add it to a transient table srcTab.  The code generated
89548       ** here is from the 4th template:
89549       **
89550       **      B: open temp table
89551       **      L: yield X
89552       **         if EOF goto M
89553       **         insert row from R..R+n into temp table
89554       **         goto L
89555       **      M: ...
89556       */
89557       int regRec;          /* Register to hold packed record */
89558       int regTempRowid;    /* Register to hold temp table ROWID */
89559       int addrTop;         /* Label "L" */
89560       int addrIf;          /* Address of jump to M */
89561 
89562       srcTab = pParse->nTab++;
89563       regRec = sqlite3GetTempReg(pParse);
89564       regTempRowid = sqlite3GetTempReg(pParse);
89565       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89566       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
89567       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
89568       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89569       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89570       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89571       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89572       sqlite3VdbeJumpHere(v, addrIf);
89573       sqlite3ReleaseTempReg(pParse, regRec);
89574       sqlite3ReleaseTempReg(pParse, regTempRowid);
89575     }
89576   }else{
89577     /* This is the case if the data for the INSERT is coming from a VALUES
89578     ** clause
89579     */
89580     NameContext sNC;
89581     memset(&sNC, 0, sizeof(sNC));
89582     sNC.pParse = pParse;
89583     srcTab = -1;
89584     assert( useTempTable==0 );
89585     nColumn = pList ? pList->nExpr : 0;
89586     for(i=0; i<nColumn; i++){
89587       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89588         goto insert_cleanup;
89589       }
89590     }
89591   }
89592 
89593   /* Make sure the number of columns in the source data matches the number
89594   ** of columns to be inserted into the table.
89595   */
89596   if( IsVirtual(pTab) ){
89597     for(i=0; i<pTab->nCol; i++){
89598       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89599     }
89600   }
89601   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89602     sqlite3ErrorMsg(pParse,
89603        "table %S has %d columns but %d values were supplied",
89604        pTabList, 0, pTab->nCol-nHidden, nColumn);
89605     goto insert_cleanup;
89606   }
89607   if( pColumn!=0 && nColumn!=pColumn->nId ){
89608     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89609     goto insert_cleanup;
89610   }
89611 
89612   /* If the INSERT statement included an IDLIST term, then make sure
89613   ** all elements of the IDLIST really are columns of the table and
89614   ** remember the column indices.
89615   **
89616   ** If the table has an INTEGER PRIMARY KEY column and that column
89617   ** is named in the IDLIST, then record in the keyColumn variable
89618   ** the index into IDLIST of the primary key column.  keyColumn is
89619   ** the index of the primary key as it appears in IDLIST, not as
89620   ** is appears in the original table.  (The index of the primary
89621   ** key in the original table is pTab->iPKey.)
89622   */
89623   if( pColumn ){
89624     for(i=0; i<pColumn->nId; i++){
89625       pColumn->a[i].idx = -1;
89626     }
89627     for(i=0; i<pColumn->nId; i++){
89628       for(j=0; j<pTab->nCol; j++){
89629         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89630           pColumn->a[i].idx = j;
89631           if( j==pTab->iPKey ){
89632             keyColumn = i;
89633           }
89634           break;
89635         }
89636       }
89637       if( j>=pTab->nCol ){
89638         if( sqlite3IsRowid(pColumn->a[i].zName) ){
89639           keyColumn = i;
89640         }else{
89641           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
89642               pTabList, 0, pColumn->a[i].zName);
89643           pParse->checkSchema = 1;
89644           goto insert_cleanup;
89645         }
89646       }
89647     }
89648   }
89649 
89650   /* If there is no IDLIST term but the table has an integer primary
89651   ** key, the set the keyColumn variable to the primary key column index
89652   ** in the original table definition.
89653   */
89654   if( pColumn==0 && nColumn>0 ){
89655     keyColumn = pTab->iPKey;
89656   }
89657 
89658   /* Initialize the count of rows to be inserted
89659   */
89660   if( db->flags & SQLITE_CountRows ){
89661     regRowCount = ++pParse->nMem;
89662     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89663   }
89664 
89665   /* If this is not a view, open the table and and all indices */
89666   if( !isView ){
89667     int nIdx;
89668 
89669     baseCur = pParse->nTab;
89670     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89671     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89672     if( aRegIdx==0 ){
89673       goto insert_cleanup;
89674     }
89675     for(i=0; i<nIdx; i++){
89676       aRegIdx[i] = ++pParse->nMem;
89677     }
89678   }
89679 
89680   /* This is the top of the main insertion loop */
89681   if( useTempTable ){
89682     /* This block codes the top of loop only.  The complete loop is the
89683     ** following pseudocode (template 4):
89684     **
89685     **         rewind temp table
89686     **      C: loop over rows of intermediate table
89687     **           transfer values form intermediate table into <table>
89688     **         end loop
89689     **      D: ...
89690     */
89691     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
89692     addrCont = sqlite3VdbeCurrentAddr(v);
89693   }else if( pSelect ){
89694     /* This block codes the top of loop only.  The complete loop is the
89695     ** following pseudocode (template 3):
89696     **
89697     **      C: yield X
89698     **         if EOF goto D
89699     **         insert the select result into <table> from R..R+n
89700     **         goto C
89701     **      D: ...
89702     */
89703     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
89704     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
89705   }
89706 
89707   /* Allocate registers for holding the rowid of the new row,
89708   ** the content of the new row, and the assemblied row record.
89709   */
89710   regRowid = regIns = pParse->nMem+1;
89711   pParse->nMem += pTab->nCol + 1;
89712   if( IsVirtual(pTab) ){
89713     regRowid++;
89714     pParse->nMem++;
89715   }
89716   regData = regRowid+1;
89717 
89718   /* Run the BEFORE and INSTEAD OF triggers, if there are any
89719   */
89720   endOfLoop = sqlite3VdbeMakeLabel(v);
89721   if( tmask & TRIGGER_BEFORE ){
89722     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
89723 
89724     /* build the NEW.* reference row.  Note that if there is an INTEGER
89725     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89726     ** translated into a unique ID for the row.  But on a BEFORE trigger,
89727     ** we do not know what the unique ID will be (because the insert has
89728     ** not happened yet) so we substitute a rowid of -1
89729     */
89730     if( keyColumn<0 ){
89731       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89732     }else{
89733       int j1;
89734       if( useTempTable ){
89735         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89736       }else{
89737         assert( pSelect==0 );  /* Otherwise useTempTable is true */
89738         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89739       }
89740       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89741       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89742       sqlite3VdbeJumpHere(v, j1);
89743       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89744     }
89745 
89746     /* Cannot have triggers on a virtual table. If it were possible,
89747     ** this block would have to account for hidden column.
89748     */
89749     assert( !IsVirtual(pTab) );
89750 
89751     /* Create the new column data
89752     */
89753     for(i=0; i<pTab->nCol; i++){
89754       if( pColumn==0 ){
89755         j = i;
89756       }else{
89757         for(j=0; j<pColumn->nId; j++){
89758           if( pColumn->a[j].idx==i ) break;
89759         }
89760       }
89761       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89762         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89763       }else if( useTempTable ){
89764         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
89765       }else{
89766         assert( pSelect==0 ); /* Otherwise useTempTable is true */
89767         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89768       }
89769     }
89770 
89771     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89772     ** do not attempt any conversions before assembling the record.
89773     ** If this is a real table, attempt conversions as required by the
89774     ** table column affinities.
89775     */
89776     if( !isView ){
89777       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89778       sqlite3TableAffinityStr(v, pTab);
89779     }
89780 
89781     /* Fire BEFORE or INSTEAD OF triggers */
89782     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
89783         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89784 
89785     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89786   }
89787 
89788   /* Push the record number for the new entry onto the stack.  The
89789   ** record number is a randomly generate integer created by NewRowid
89790   ** except when the table has an INTEGER PRIMARY KEY column, in which
89791   ** case the record number is the same as that column.
89792   */
89793   if( !isView ){
89794     if( IsVirtual(pTab) ){
89795       /* The row that the VUpdate opcode will delete: none */
89796       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
89797     }
89798     if( keyColumn>=0 ){
89799       if( useTempTable ){
89800         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89801       }else if( pSelect ){
89802         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89803       }else{
89804         VdbeOp *pOp;
89805         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89806         pOp = sqlite3VdbeGetOp(v, -1);
89807         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89808           appendFlag = 1;
89809           pOp->opcode = OP_NewRowid;
89810           pOp->p1 = baseCur;
89811           pOp->p2 = regRowid;
89812           pOp->p3 = regAutoinc;
89813         }
89814       }
89815       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89816       ** to generate a unique primary key value.
89817       */
89818       if( !appendFlag ){
89819         int j1;
89820         if( !IsVirtual(pTab) ){
89821           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
89822           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89823           sqlite3VdbeJumpHere(v, j1);
89824         }else{
89825           j1 = sqlite3VdbeCurrentAddr(v);
89826           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89827         }
89828         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89829       }
89830     }else if( IsVirtual(pTab) ){
89831       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
89832     }else{
89833       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89834       appendFlag = 1;
89835     }
89836     autoIncStep(pParse, regAutoinc, regRowid);
89837 
89838     /* Push onto the stack, data for all columns of the new entry, beginning
89839     ** with the first column.
89840     */
89841     nHidden = 0;
89842     for(i=0; i<pTab->nCol; i++){
89843       int iRegStore = regRowid+1+i;
89844       if( i==pTab->iPKey ){
89845         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89846         ** Whenever this column is read, the record number will be substituted
89847         ** in its place.  So will fill this column with a NULL to avoid
89848         ** taking up data space with information that will never be used. */
89849         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89850         continue;
89851       }
89852       if( pColumn==0 ){
89853         if( IsHiddenColumn(&pTab->aCol[i]) ){
89854           assert( IsVirtual(pTab) );
89855           j = -1;
89856           nHidden++;
89857         }else{
89858           j = i - nHidden;
89859         }
89860       }else{
89861         for(j=0; j<pColumn->nId; j++){
89862           if( pColumn->a[j].idx==i ) break;
89863         }
89864       }
89865       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89866         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89867       }else if( useTempTable ){
89868         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
89869       }else if( pSelect ){
89870         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89871       }else{
89872         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89873       }
89874     }
89875 
89876     /* Generate code to check constraints and generate index keys and
89877     ** do the insertion.
89878     */
89879 #ifndef SQLITE_OMIT_VIRTUALTABLE
89880     if( IsVirtual(pTab) ){
89881       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
89882       sqlite3VtabMakeWritable(pParse, pTab);
89883       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89884       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89885       sqlite3MayAbort(pParse);
89886     }else
89887 #endif
89888     {
89889       int isReplace;    /* Set to true if constraints may cause a replace */
89890       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89891           keyColumn>=0, 0, onError, endOfLoop, &isReplace
89892       );
89893       sqlite3FkCheck(pParse, pTab, 0, regIns);
89894       sqlite3CompleteInsertion(
89895           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89896       );
89897     }
89898   }
89899 
89900   /* Update the count of rows that are inserted
89901   */
89902   if( (db->flags & SQLITE_CountRows)!=0 ){
89903     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89904   }
89905 
89906   if( pTrigger ){
89907     /* Code AFTER triggers */
89908     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
89909         pTab, regData-2-pTab->nCol, onError, endOfLoop);
89910   }
89911 
89912   /* The bottom of the main insertion loop, if the data source
89913   ** is a SELECT statement.
89914   */
89915   sqlite3VdbeResolveLabel(v, endOfLoop);
89916   if( useTempTable ){
89917     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89918     sqlite3VdbeJumpHere(v, addrInsTop);
89919     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
89920   }else if( pSelect ){
89921     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89922     sqlite3VdbeJumpHere(v, addrInsTop);
89923   }
89924 
89925   if( !IsVirtual(pTab) && !isView ){
89926     /* Close all tables opened */
89927     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
89928     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89929       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
89930     }
89931   }
89932 
89933 insert_end:
89934   /* Update the sqlite_sequence table by storing the content of the
89935   ** maximum rowid counter values recorded while inserting into
89936   ** autoincrement tables.
89937   */
89938   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89939     sqlite3AutoincrementEnd(pParse);
89940   }
89941 
89942   /*
89943   ** Return the number of rows inserted. If this routine is
89944   ** generating code because of a call to sqlite3NestedParse(), do not
89945   ** invoke the callback function.
89946   */
89947   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89948     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
89949     sqlite3VdbeSetNumCols(v, 1);
89950     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
89951   }
89952 
89953 insert_cleanup:
89954   sqlite3SrcListDelete(db, pTabList);
89955   sqlite3ExprListDelete(db, pList);
89956   sqlite3SelectDelete(db, pSelect);
89957   sqlite3IdListDelete(db, pColumn);
89958   sqlite3DbFree(db, aRegIdx);
89959 }
89960 
89961 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89962 ** thely may interfere with compilation of other functions in this file
89963 ** (or in another file, if this file becomes part of the amalgamation).  */
89964 #ifdef isView
89965  #undef isView
89966 #endif
89967 #ifdef pTrigger
89968  #undef pTrigger
89969 #endif
89970 #ifdef tmask
89971  #undef tmask
89972 #endif
89973 
89974 
89975 /*
89976 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
89977 **
89978 ** The input is a range of consecutive registers as follows:
89979 **
89980 **    1.  The rowid of the row after the update.
89981 **
89982 **    2.  The data in the first column of the entry after the update.
89983 **
89984 **    i.  Data from middle columns...
89985 **
89986 **    N.  The data in the last column of the entry after the update.
89987 **
89988 ** The regRowid parameter is the index of the register containing (1).
89989 **
89990 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
89991 ** the address of a register containing the rowid before the update takes
89992 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
89993 ** is false, indicating an INSERT statement, then a non-zero rowidChng
89994 ** indicates that the rowid was explicitly specified as part of the
89995 ** INSERT statement. If rowidChng is false, it means that  the rowid is
89996 ** computed automatically in an insert or that the rowid value is not
89997 ** modified by an update.
89998 **
89999 ** The code generated by this routine store new index entries into
90000 ** registers identified by aRegIdx[].  No index entry is created for
90001 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
90002 ** the same as the order of indices on the linked list of indices
90003 ** attached to the table.
90004 **
90005 ** This routine also generates code to check constraints.  NOT NULL,
90006 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
90007 ** then the appropriate action is performed.  There are five possible
90008 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
90009 **
90010 **  Constraint type  Action       What Happens
90011 **  ---------------  ----------   ----------------------------------------
90012 **  any              ROLLBACK     The current transaction is rolled back and
90013 **                                sqlite3_exec() returns immediately with a
90014 **                                return code of SQLITE_CONSTRAINT.
90015 **
90016 **  any              ABORT        Back out changes from the current command
90017 **                                only (do not do a complete rollback) then
90018 **                                cause sqlite3_exec() to return immediately
90019 **                                with SQLITE_CONSTRAINT.
90020 **
90021 **  any              FAIL         Sqlite3_exec() returns immediately with a
90022 **                                return code of SQLITE_CONSTRAINT.  The
90023 **                                transaction is not rolled back and any
90024 **                                prior changes are retained.
90025 **
90026 **  any              IGNORE       The record number and data is popped from
90027 **                                the stack and there is an immediate jump
90028 **                                to label ignoreDest.
90029 **
90030 **  NOT NULL         REPLACE      The NULL value is replace by the default
90031 **                                value for that column.  If the default value
90032 **                                is NULL, the action is the same as ABORT.
90033 **
90034 **  UNIQUE           REPLACE      The other row that conflicts with the row
90035 **                                being inserted is removed.
90036 **
90037 **  CHECK            REPLACE      Illegal.  The results in an exception.
90038 **
90039 ** Which action to take is determined by the overrideError parameter.
90040 ** Or if overrideError==OE_Default, then the pParse->onError parameter
90041 ** is used.  Or if pParse->onError==OE_Default then the onError value
90042 ** for the constraint is used.
90043 **
90044 ** The calling routine must open a read/write cursor for pTab with
90045 ** cursor number "baseCur".  All indices of pTab must also have open
90046 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
90047 ** Except, if there is no possibility of a REPLACE action then
90048 ** cursors do not need to be open for indices where aRegIdx[i]==0.
90049 */
90050 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
90051   Parse *pParse,      /* The parser context */
90052   Table *pTab,        /* the table into which we are inserting */
90053   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90054   int regRowid,       /* Index of the range of input registers */
90055   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90056   int rowidChng,      /* True if the rowid might collide with existing entry */
90057   int isUpdate,       /* True for UPDATE, False for INSERT */
90058   int overrideError,  /* Override onError to this if not OE_Default */
90059   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
90060   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
90061 ){
90062   int i;              /* loop counter */
90063   Vdbe *v;            /* VDBE under constrution */
90064   int nCol;           /* Number of columns */
90065   int onError;        /* Conflict resolution strategy */
90066   int j1;             /* Addresss of jump instruction */
90067   int j2 = 0, j3;     /* Addresses of jump instructions */
90068   int regData;        /* Register containing first data column */
90069   int iCur;           /* Table cursor number */
90070   Index *pIdx;         /* Pointer to one of the indices */
90071   sqlite3 *db;         /* Database connection */
90072   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
90073   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
90074 
90075   db = pParse->db;
90076   v = sqlite3GetVdbe(pParse);
90077   assert( v!=0 );
90078   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90079   nCol = pTab->nCol;
90080   regData = regRowid + 1;
90081 
90082   /* Test all NOT NULL constraints.
90083   */
90084   for(i=0; i<nCol; i++){
90085     if( i==pTab->iPKey ){
90086       continue;
90087     }
90088     onError = pTab->aCol[i].notNull;
90089     if( onError==OE_None ) continue;
90090     if( overrideError!=OE_Default ){
90091       onError = overrideError;
90092     }else if( onError==OE_Default ){
90093       onError = OE_Abort;
90094     }
90095     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
90096       onError = OE_Abort;
90097     }
90098     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90099         || onError==OE_Ignore || onError==OE_Replace );
90100     switch( onError ){
90101       case OE_Abort:
90102         sqlite3MayAbort(pParse);
90103       case OE_Rollback:
90104       case OE_Fail: {
90105         char *zMsg;
90106         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
90107                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
90108         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
90109                               pTab->zName, pTab->aCol[i].zName);
90110         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
90111         break;
90112       }
90113       case OE_Ignore: {
90114         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
90115         break;
90116       }
90117       default: {
90118         assert( onError==OE_Replace );
90119         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
90120         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
90121         sqlite3VdbeJumpHere(v, j1);
90122         break;
90123       }
90124     }
90125   }
90126 
90127   /* Test all CHECK constraints
90128   */
90129 #ifndef SQLITE_OMIT_CHECK
90130   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
90131     ExprList *pCheck = pTab->pCheck;
90132     pParse->ckBase = regData;
90133     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
90134     for(i=0; i<pCheck->nExpr; i++){
90135       int allOk = sqlite3VdbeMakeLabel(v);
90136       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
90137       if( onError==OE_Ignore ){
90138         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90139       }else{
90140         char *zConsName = pCheck->a[i].zName;
90141         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
90142         if( zConsName ){
90143           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
90144         }else{
90145           zConsName = 0;
90146         }
90147         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
90148                               onError, zConsName, P4_DYNAMIC);
90149       }
90150       sqlite3VdbeResolveLabel(v, allOk);
90151     }
90152   }
90153 #endif /* !defined(SQLITE_OMIT_CHECK) */
90154 
90155   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
90156   ** of the new record does not previously exist.  Except, if this
90157   ** is an UPDATE and the primary key is not changing, that is OK.
90158   */
90159   if( rowidChng ){
90160     onError = pTab->keyConf;
90161     if( overrideError!=OE_Default ){
90162       onError = overrideError;
90163     }else if( onError==OE_Default ){
90164       onError = OE_Abort;
90165     }
90166 
90167     if( isUpdate ){
90168       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
90169     }
90170     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
90171     switch( onError ){
90172       default: {
90173         onError = OE_Abort;
90174         /* Fall thru into the next case */
90175       }
90176       case OE_Rollback:
90177       case OE_Abort:
90178       case OE_Fail: {
90179         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
90180            onError, "PRIMARY KEY must be unique", P4_STATIC);
90181         break;
90182       }
90183       case OE_Replace: {
90184         /* If there are DELETE triggers on this table and the
90185         ** recursive-triggers flag is set, call GenerateRowDelete() to
90186         ** remove the conflicting row from the table. This will fire
90187         ** the triggers and remove both the table and index b-tree entries.
90188         **
90189         ** Otherwise, if there are no triggers or the recursive-triggers
90190         ** flag is not set, but the table has one or more indexes, call
90191         ** GenerateRowIndexDelete(). This removes the index b-tree entries
90192         ** only. The table b-tree entry will be replaced by the new entry
90193         ** when it is inserted.
90194         **
90195         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
90196         ** also invoke MultiWrite() to indicate that this VDBE may require
90197         ** statement rollback (if the statement is aborted after the delete
90198         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
90199         ** but being more selective here allows statements like:
90200         **
90201         **   REPLACE INTO t(rowid) VALUES($newrowid)
90202         **
90203         ** to run without a statement journal if there are no indexes on the
90204         ** table.
90205         */
90206         Trigger *pTrigger = 0;
90207         if( db->flags&SQLITE_RecTriggers ){
90208           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90209         }
90210         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
90211           sqlite3MultiWrite(pParse);
90212           sqlite3GenerateRowDelete(
90213               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
90214           );
90215         }else if( pTab->pIndex ){
90216           sqlite3MultiWrite(pParse);
90217           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
90218         }
90219         seenReplace = 1;
90220         break;
90221       }
90222       case OE_Ignore: {
90223         assert( seenReplace==0 );
90224         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90225         break;
90226       }
90227     }
90228     sqlite3VdbeJumpHere(v, j3);
90229     if( isUpdate ){
90230       sqlite3VdbeJumpHere(v, j2);
90231     }
90232   }
90233 
90234   /* Test all UNIQUE constraints by creating entries for each UNIQUE
90235   ** index and making sure that duplicate entries do not already exist.
90236   ** Add the new records to the indices as we go.
90237   */
90238   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
90239     int regIdx;
90240     int regR;
90241 
90242     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
90243 
90244     /* Create a key for accessing the index entry */
90245     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
90246     for(i=0; i<pIdx->nColumn; i++){
90247       int idx = pIdx->aiColumn[i];
90248       if( idx==pTab->iPKey ){
90249         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90250       }else{
90251         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
90252       }
90253     }
90254     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90255     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
90256     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
90257     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
90258 
90259     /* Find out what action to take in case there is an indexing conflict */
90260     onError = pIdx->onError;
90261     if( onError==OE_None ){
90262       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90263       continue;  /* pIdx is not a UNIQUE index */
90264     }
90265     if( overrideError!=OE_Default ){
90266       onError = overrideError;
90267     }else if( onError==OE_Default ){
90268       onError = OE_Abort;
90269     }
90270     if( seenReplace ){
90271       if( onError==OE_Ignore ) onError = OE_Replace;
90272       else if( onError==OE_Fail ) onError = OE_Abort;
90273     }
90274 
90275     /* Check to see if the new index entry will be unique */
90276     regR = sqlite3GetTempReg(pParse);
90277     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
90278     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
90279                            regR, SQLITE_INT_TO_PTR(regIdx),
90280                            P4_INT32);
90281     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90282 
90283     /* Generate code that executes if the new index entry is not unique */
90284     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90285         || onError==OE_Ignore || onError==OE_Replace );
90286     switch( onError ){
90287       case OE_Rollback:
90288       case OE_Abort:
90289       case OE_Fail: {
90290         int j;
90291         StrAccum errMsg;
90292         const char *zSep;
90293         char *zErr;
90294 
90295         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
90296         errMsg.db = db;
90297         zSep = pIdx->nColumn>1 ? "columns " : "column ";
90298         for(j=0; j<pIdx->nColumn; j++){
90299           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90300           sqlite3StrAccumAppend(&errMsg, zSep, -1);
90301           zSep = ", ";
90302           sqlite3StrAccumAppend(&errMsg, zCol, -1);
90303         }
90304         sqlite3StrAccumAppend(&errMsg,
90305             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
90306         zErr = sqlite3StrAccumFinish(&errMsg);
90307         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
90308                               onError, zErr, 0);
90309         sqlite3DbFree(errMsg.db, zErr);
90310         break;
90311       }
90312       case OE_Ignore: {
90313         assert( seenReplace==0 );
90314         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90315         break;
90316       }
90317       default: {
90318         Trigger *pTrigger = 0;
90319         assert( onError==OE_Replace );
90320         sqlite3MultiWrite(pParse);
90321         if( db->flags&SQLITE_RecTriggers ){
90322           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90323         }
90324         sqlite3GenerateRowDelete(
90325             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90326         );
90327         seenReplace = 1;
90328         break;
90329       }
90330     }
90331     sqlite3VdbeJumpHere(v, j3);
90332     sqlite3ReleaseTempReg(pParse, regR);
90333   }
90334 
90335   if( pbMayReplace ){
90336     *pbMayReplace = seenReplace;
90337   }
90338 }
90339 
90340 /*
90341 ** This routine generates code to finish the INSERT or UPDATE operation
90342 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
90343 ** A consecutive range of registers starting at regRowid contains the
90344 ** rowid and the content to be inserted.
90345 **
90346 ** The arguments to this routine should be the same as the first six
90347 ** arguments to sqlite3GenerateConstraintChecks.
90348 */
90349 SQLITE_PRIVATE void sqlite3CompleteInsertion(
90350   Parse *pParse,      /* The parser context */
90351   Table *pTab,        /* the table into which we are inserting */
90352   int baseCur,        /* Index of a read/write cursor pointing at pTab */
90353   int regRowid,       /* Range of content */
90354   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90355   int isUpdate,       /* True for UPDATE, False for INSERT */
90356   int appendBias,     /* True if this is likely to be an append */
90357   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90358 ){
90359   int i;
90360   Vdbe *v;
90361   int nIdx;
90362   Index *pIdx;
90363   u8 pik_flags;
90364   int regData;
90365   int regRec;
90366 
90367   v = sqlite3GetVdbe(pParse);
90368   assert( v!=0 );
90369   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90370   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90371   for(i=nIdx-1; i>=0; i--){
90372     if( aRegIdx[i]==0 ) continue;
90373     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90374     if( useSeekResult ){
90375       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90376     }
90377   }
90378   regData = regRowid + 1;
90379   regRec = sqlite3GetTempReg(pParse);
90380   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90381   sqlite3TableAffinityStr(v, pTab);
90382   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90383   if( pParse->nested ){
90384     pik_flags = 0;
90385   }else{
90386     pik_flags = OPFLAG_NCHANGE;
90387     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90388   }
90389   if( appendBias ){
90390     pik_flags |= OPFLAG_APPEND;
90391   }
90392   if( useSeekResult ){
90393     pik_flags |= OPFLAG_USESEEKRESULT;
90394   }
90395   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90396   if( !pParse->nested ){
90397     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90398   }
90399   sqlite3VdbeChangeP5(v, pik_flags);
90400 }
90401 
90402 /*
90403 ** Generate code that will open cursors for a table and for all
90404 ** indices of that table.  The "baseCur" parameter is the cursor number used
90405 ** for the table.  Indices are opened on subsequent cursors.
90406 **
90407 ** Return the number of indices on the table.
90408 */
90409 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
90410   Parse *pParse,   /* Parsing context */
90411   Table *pTab,     /* Table to be opened */
90412   int baseCur,     /* Cursor number assigned to the table */
90413   int op           /* OP_OpenRead or OP_OpenWrite */
90414 ){
90415   int i;
90416   int iDb;
90417   Index *pIdx;
90418   Vdbe *v;
90419 
90420   if( IsVirtual(pTab) ) return 0;
90421   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90422   v = sqlite3GetVdbe(pParse);
90423   assert( v!=0 );
90424   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
90425   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90426     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
90427     assert( pIdx->pSchema==pTab->pSchema );
90428     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90429                       (char*)pKey, P4_KEYINFO_HANDOFF);
90430     VdbeComment((v, "%s", pIdx->zName));
90431   }
90432   if( pParse->nTab<baseCur+i ){
90433     pParse->nTab = baseCur+i;
90434   }
90435   return i-1;
90436 }
90437 
90438 
90439 #ifdef SQLITE_TEST
90440 /*
90441 ** The following global variable is incremented whenever the
90442 ** transfer optimization is used.  This is used for testing
90443 ** purposes only - to make sure the transfer optimization really
90444 ** is happening when it is suppose to.
90445 */
90446 SQLITE_API int sqlite3_xferopt_count;
90447 #endif /* SQLITE_TEST */
90448 
90449 
90450 #ifndef SQLITE_OMIT_XFER_OPT
90451 /*
90452 ** Check to collation names to see if they are compatible.
90453 */
90454 static int xferCompatibleCollation(const char *z1, const char *z2){
90455   if( z1==0 ){
90456     return z2==0;
90457   }
90458   if( z2==0 ){
90459     return 0;
90460   }
90461   return sqlite3StrICmp(z1, z2)==0;
90462 }
90463 
90464 
90465 /*
90466 ** Check to see if index pSrc is compatible as a source of data
90467 ** for index pDest in an insert transfer optimization.  The rules
90468 ** for a compatible index:
90469 **
90470 **    *   The index is over the same set of columns
90471 **    *   The same DESC and ASC markings occurs on all columns
90472 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90473 **    *   The same collating sequence on each column
90474 */
90475 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90476   int i;
90477   assert( pDest && pSrc );
90478   assert( pDest->pTable!=pSrc->pTable );
90479   if( pDest->nColumn!=pSrc->nColumn ){
90480     return 0;   /* Different number of columns */
90481   }
90482   if( pDest->onError!=pSrc->onError ){
90483     return 0;   /* Different conflict resolution strategies */
90484   }
90485   for(i=0; i<pSrc->nColumn; i++){
90486     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90487       return 0;   /* Different columns indexed */
90488     }
90489     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90490       return 0;   /* Different sort orders */
90491     }
90492     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90493       return 0;   /* Different collating sequences */
90494     }
90495   }
90496 
90497   /* If no test above fails then the indices must be compatible */
90498   return 1;
90499 }
90500 
90501 /*
90502 ** Attempt the transfer optimization on INSERTs of the form
90503 **
90504 **     INSERT INTO tab1 SELECT * FROM tab2;
90505 **
90506 ** The xfer optimization transfers raw records from tab2 over to tab1.
90507 ** Columns are not decoded and reassemblied, which greatly improves
90508 ** performance.  Raw index records are transferred in the same way.
90509 **
90510 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
90511 ** There are lots of rules for determining compatibility - see comments
90512 ** embedded in the code for details.
90513 **
90514 ** This routine returns TRUE if the optimization is guaranteed to be used.
90515 ** Sometimes the xfer optimization will only work if the destination table
90516 ** is empty - a factor that can only be determined at run-time.  In that
90517 ** case, this routine generates code for the xfer optimization but also
90518 ** does a test to see if the destination table is empty and jumps over the
90519 ** xfer optimization code if the test fails.  In that case, this routine
90520 ** returns FALSE so that the caller will know to go ahead and generate
90521 ** an unoptimized transfer.  This routine also returns FALSE if there
90522 ** is no chance that the xfer optimization can be applied.
90523 **
90524 ** This optimization is particularly useful at making VACUUM run faster.
90525 */
90526 static int xferOptimization(
90527   Parse *pParse,        /* Parser context */
90528   Table *pDest,         /* The table we are inserting into */
90529   Select *pSelect,      /* A SELECT statement to use as the data source */
90530   int onError,          /* How to handle constraint errors */
90531   int iDbDest           /* The database of pDest */
90532 ){
90533   ExprList *pEList;                /* The result set of the SELECT */
90534   Table *pSrc;                     /* The table in the FROM clause of SELECT */
90535   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90536   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90537   int i;                           /* Loop counter */
90538   int iDbSrc;                      /* The database of pSrc */
90539   int iSrc, iDest;                 /* Cursors from source and destination */
90540   int addr1, addr2;                /* Loop addresses */
90541   int emptyDestTest;               /* Address of test for empty pDest */
90542   int emptySrcTest;                /* Address of test for empty pSrc */
90543   Vdbe *v;                         /* The VDBE we are building */
90544   KeyInfo *pKey;                   /* Key information for an index */
90545   int regAutoinc;                  /* Memory register used by AUTOINC */
90546   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90547   int regData, regRowid;           /* Registers holding data and rowid */
90548 
90549   if( pSelect==0 ){
90550     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90551   }
90552   if( sqlite3TriggerList(pParse, pDest) ){
90553     return 0;   /* tab1 must not have triggers */
90554   }
90555 #ifndef SQLITE_OMIT_VIRTUALTABLE
90556   if( pDest->tabFlags & TF_Virtual ){
90557     return 0;   /* tab1 must not be a virtual table */
90558   }
90559 #endif
90560   if( onError==OE_Default ){
90561     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
90562     if( onError==OE_Default ) onError = OE_Abort;
90563   }
90564   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90565   if( pSelect->pSrc->nSrc!=1 ){
90566     return 0;   /* FROM clause must have exactly one term */
90567   }
90568   if( pSelect->pSrc->a[0].pSelect ){
90569     return 0;   /* FROM clause cannot contain a subquery */
90570   }
90571   if( pSelect->pWhere ){
90572     return 0;   /* SELECT may not have a WHERE clause */
90573   }
90574   if( pSelect->pOrderBy ){
90575     return 0;   /* SELECT may not have an ORDER BY clause */
90576   }
90577   /* Do not need to test for a HAVING clause.  If HAVING is present but
90578   ** there is no ORDER BY, we will get an error. */
90579   if( pSelect->pGroupBy ){
90580     return 0;   /* SELECT may not have a GROUP BY clause */
90581   }
90582   if( pSelect->pLimit ){
90583     return 0;   /* SELECT may not have a LIMIT clause */
90584   }
90585   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90586   if( pSelect->pPrior ){
90587     return 0;   /* SELECT may not be a compound query */
90588   }
90589   if( pSelect->selFlags & SF_Distinct ){
90590     return 0;   /* SELECT may not be DISTINCT */
90591   }
90592   pEList = pSelect->pEList;
90593   assert( pEList!=0 );
90594   if( pEList->nExpr!=1 ){
90595     return 0;   /* The result set must have exactly one column */
90596   }
90597   assert( pEList->a[0].pExpr );
90598   if( pEList->a[0].pExpr->op!=TK_ALL ){
90599     return 0;   /* The result set must be the special operator "*" */
90600   }
90601 
90602   /* At this point we have established that the statement is of the
90603   ** correct syntactic form to participate in this optimization.  Now
90604   ** we have to check the semantics.
90605   */
90606   pItem = pSelect->pSrc->a;
90607   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
90608   if( pSrc==0 ){
90609     return 0;   /* FROM clause does not contain a real table */
90610   }
90611   if( pSrc==pDest ){
90612     return 0;   /* tab1 and tab2 may not be the same table */
90613   }
90614 #ifndef SQLITE_OMIT_VIRTUALTABLE
90615   if( pSrc->tabFlags & TF_Virtual ){
90616     return 0;   /* tab2 must not be a virtual table */
90617   }
90618 #endif
90619   if( pSrc->pSelect ){
90620     return 0;   /* tab2 may not be a view */
90621   }
90622   if( pDest->nCol!=pSrc->nCol ){
90623     return 0;   /* Number of columns must be the same in tab1 and tab2 */
90624   }
90625   if( pDest->iPKey!=pSrc->iPKey ){
90626     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90627   }
90628   for(i=0; i<pDest->nCol; i++){
90629     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90630       return 0;    /* Affinity must be the same on all columns */
90631     }
90632     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90633       return 0;    /* Collating sequence must be the same on all columns */
90634     }
90635     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90636       return 0;    /* tab2 must be NOT NULL if tab1 is */
90637     }
90638   }
90639   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90640     if( pDestIdx->onError!=OE_None ){
90641       destHasUniqueIdx = 1;
90642     }
90643     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90644       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90645     }
90646     if( pSrcIdx==0 ){
90647       return 0;    /* pDestIdx has no corresponding index in pSrc */
90648     }
90649   }
90650 #ifndef SQLITE_OMIT_CHECK
90651   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
90652     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90653   }
90654 #endif
90655 #ifndef SQLITE_OMIT_FOREIGN_KEY
90656   /* Disallow the transfer optimization if the destination table constains
90657   ** any foreign key constraints.  This is more restrictive than necessary.
90658   ** But the main beneficiary of the transfer optimization is the VACUUM
90659   ** command, and the VACUUM command disables foreign key constraints.  So
90660   ** the extra complication to make this rule less restrictive is probably
90661   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90662   */
90663   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90664     return 0;
90665   }
90666 #endif
90667   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
90668     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
90669   }
90670 
90671   /* If we get this far, it means that the xfer optimization is at
90672   ** least a possibility, though it might only work if the destination
90673   ** table (tab1) is initially empty.
90674   */
90675 #ifdef SQLITE_TEST
90676   sqlite3_xferopt_count++;
90677 #endif
90678   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
90679   v = sqlite3GetVdbe(pParse);
90680   sqlite3CodeVerifySchema(pParse, iDbSrc);
90681   iSrc = pParse->nTab++;
90682   iDest = pParse->nTab++;
90683   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90684   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90685   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
90686    || destHasUniqueIdx                              /* (2) */
90687    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
90688   ){
90689     /* In some circumstances, we are able to run the xfer optimization
90690     ** only if the destination table is initially empty.  This code makes
90691     ** that determination.  Conditions under which the destination must
90692     ** be empty:
90693     **
90694     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
90695     **     (If the destination is not initially empty, the rowid fields
90696     **     of index entries might need to change.)
90697     **
90698     ** (2) The destination has a unique index.  (The xfer optimization
90699     **     is unable to test uniqueness.)
90700     **
90701     ** (3) onError is something other than OE_Abort and OE_Rollback.
90702     */
90703     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90704     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90705     sqlite3VdbeJumpHere(v, addr1);
90706   }else{
90707     emptyDestTest = 0;
90708   }
90709   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90710   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90711   regData = sqlite3GetTempReg(pParse);
90712   regRowid = sqlite3GetTempReg(pParse);
90713   if( pDest->iPKey>=0 ){
90714     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90715     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90716     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
90717         onError, "PRIMARY KEY must be unique", P4_STATIC);
90718     sqlite3VdbeJumpHere(v, addr2);
90719     autoIncStep(pParse, regAutoinc, regRowid);
90720   }else if( pDest->pIndex==0 ){
90721     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90722   }else{
90723     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90724     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90725   }
90726   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90727   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90728   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90729   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
90730   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90731   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90732     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90733       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90734     }
90735     assert( pSrcIdx );
90736     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90737     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90738     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
90739     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90740                       (char*)pKey, P4_KEYINFO_HANDOFF);
90741     VdbeComment((v, "%s", pSrcIdx->zName));
90742     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
90743     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90744                       (char*)pKey, P4_KEYINFO_HANDOFF);
90745     VdbeComment((v, "%s", pDestIdx->zName));
90746     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90747     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90748     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90749     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90750     sqlite3VdbeJumpHere(v, addr1);
90751   }
90752   sqlite3VdbeJumpHere(v, emptySrcTest);
90753   sqlite3ReleaseTempReg(pParse, regRowid);
90754   sqlite3ReleaseTempReg(pParse, regData);
90755   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90756   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90757   if( emptyDestTest ){
90758     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
90759     sqlite3VdbeJumpHere(v, emptyDestTest);
90760     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90761     return 0;
90762   }else{
90763     return 1;
90764   }
90765 }
90766 #endif /* SQLITE_OMIT_XFER_OPT */
90767 
90768 /************** End of insert.c **********************************************/
90769 /************** Begin file legacy.c ******************************************/
90770 /*
90771 ** 2001 September 15
90772 **
90773 ** The author disclaims copyright to this source code.  In place of
90774 ** a legal notice, here is a blessing:
90775 **
90776 **    May you do good and not evil.
90777 **    May you find forgiveness for yourself and forgive others.
90778 **    May you share freely, never taking more than you give.
90779 **
90780 *************************************************************************
90781 ** Main file for the SQLite library.  The routines in this file
90782 ** implement the programmer interface to the library.  Routines in
90783 ** other files are for internal use by SQLite and should not be
90784 ** accessed by users of the library.
90785 */
90786 
90787 
90788 /*
90789 ** Execute SQL code.  Return one of the SQLITE_ success/failure
90790 ** codes.  Also write an error message into memory obtained from
90791 ** malloc() and make *pzErrMsg point to that message.
90792 **
90793 ** If the SQL is a query, then for each row in the query result
90794 ** the xCallback() function is called.  pArg becomes the first
90795 ** argument to xCallback().  If xCallback=NULL then no callback
90796 ** is invoked, even for queries.
90797 */
90798 SQLITE_API int sqlite3_exec(
90799   sqlite3 *db,                /* The database on which the SQL executes */
90800   const char *zSql,           /* The SQL to be executed */
90801   sqlite3_callback xCallback, /* Invoke this callback routine */
90802   void *pArg,                 /* First argument to xCallback() */
90803   char **pzErrMsg             /* Write error messages here */
90804 ){
90805   int rc = SQLITE_OK;         /* Return code */
90806   const char *zLeftover;      /* Tail of unprocessed SQL */
90807   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
90808   char **azCols = 0;          /* Names of result columns */
90809   int nRetry = 0;             /* Number of retry attempts */
90810   int callbackIsInit;         /* True if callback data is initialized */
90811 
90812   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90813   if( zSql==0 ) zSql = "";
90814 
90815   sqlite3_mutex_enter(db->mutex);
90816   sqlite3Error(db, SQLITE_OK, 0);
90817   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90818     int nCol;
90819     char **azVals = 0;
90820 
90821     pStmt = 0;
90822     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90823     assert( rc==SQLITE_OK || pStmt==0 );
90824     if( rc!=SQLITE_OK ){
90825       continue;
90826     }
90827     if( !pStmt ){
90828       /* this happens for a comment or white-space */
90829       zSql = zLeftover;
90830       continue;
90831     }
90832 
90833     callbackIsInit = 0;
90834     nCol = sqlite3_column_count(pStmt);
90835 
90836     while( 1 ){
90837       int i;
90838       rc = sqlite3_step(pStmt);
90839 
90840       /* Invoke the callback function if required */
90841       if( xCallback && (SQLITE_ROW==rc ||
90842           (SQLITE_DONE==rc && !callbackIsInit
90843                            && db->flags&SQLITE_NullCallback)) ){
90844         if( !callbackIsInit ){
90845           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90846           if( azCols==0 ){
90847             goto exec_out;
90848           }
90849           for(i=0; i<nCol; i++){
90850             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
90851             /* sqlite3VdbeSetColName() installs column names as UTF8
90852             ** strings so there is no way for sqlite3_column_name() to fail. */
90853             assert( azCols[i]!=0 );
90854           }
90855           callbackIsInit = 1;
90856         }
90857         if( rc==SQLITE_ROW ){
90858           azVals = &azCols[nCol];
90859           for(i=0; i<nCol; i++){
90860             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
90861             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
90862               db->mallocFailed = 1;
90863               goto exec_out;
90864             }
90865           }
90866         }
90867         if( xCallback(pArg, nCol, azVals, azCols) ){
90868           rc = SQLITE_ABORT;
90869           sqlite3VdbeFinalize((Vdbe *)pStmt);
90870           pStmt = 0;
90871           sqlite3Error(db, SQLITE_ABORT, 0);
90872           goto exec_out;
90873         }
90874       }
90875 
90876       if( rc!=SQLITE_ROW ){
90877         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
90878         pStmt = 0;
90879         if( rc!=SQLITE_SCHEMA ){
90880           nRetry = 0;
90881           zSql = zLeftover;
90882           while( sqlite3Isspace(zSql[0]) ) zSql++;
90883         }
90884         break;
90885       }
90886     }
90887 
90888     sqlite3DbFree(db, azCols);
90889     azCols = 0;
90890   }
90891 
90892 exec_out:
90893   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
90894   sqlite3DbFree(db, azCols);
90895 
90896   rc = sqlite3ApiExit(db, rc);
90897   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
90898     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
90899     *pzErrMsg = sqlite3Malloc(nErrMsg);
90900     if( *pzErrMsg ){
90901       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
90902     }else{
90903       rc = SQLITE_NOMEM;
90904       sqlite3Error(db, SQLITE_NOMEM, 0);
90905     }
90906   }else if( pzErrMsg ){
90907     *pzErrMsg = 0;
90908   }
90909 
90910   assert( (rc&db->errMask)==rc );
90911   sqlite3_mutex_leave(db->mutex);
90912   return rc;
90913 }
90914 
90915 /************** End of legacy.c **********************************************/
90916 /************** Begin file loadext.c *****************************************/
90917 /*
90918 ** 2006 June 7
90919 **
90920 ** The author disclaims copyright to this source code.  In place of
90921 ** a legal notice, here is a blessing:
90922 **
90923 **    May you do good and not evil.
90924 **    May you find forgiveness for yourself and forgive others.
90925 **    May you share freely, never taking more than you give.
90926 **
90927 *************************************************************************
90928 ** This file contains code used to dynamically load extensions into
90929 ** the SQLite library.
90930 */
90931 
90932 #ifndef SQLITE_CORE
90933   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
90934 #endif
90935 /************** Include sqlite3ext.h in the middle of loadext.c **************/
90936 /************** Begin file sqlite3ext.h **************************************/
90937 /*
90938 ** 2006 June 7
90939 **
90940 ** The author disclaims copyright to this source code.  In place of
90941 ** a legal notice, here is a blessing:
90942 **
90943 **    May you do good and not evil.
90944 **    May you find forgiveness for yourself and forgive others.
90945 **    May you share freely, never taking more than you give.
90946 **
90947 *************************************************************************
90948 ** This header file defines the SQLite interface for use by
90949 ** shared libraries that want to be imported as extensions into
90950 ** an SQLite instance.  Shared libraries that intend to be loaded
90951 ** as extensions by SQLite should #include this file instead of
90952 ** sqlite3.h.
90953 */
90954 #ifndef _SQLITE3EXT_H_
90955 #define _SQLITE3EXT_H_
90956 
90957 typedef struct sqlite3_api_routines sqlite3_api_routines;
90958 
90959 /*
90960 ** The following structure holds pointers to all of the SQLite API
90961 ** routines.
90962 **
90963 ** WARNING:  In order to maintain backwards compatibility, add new
90964 ** interfaces to the end of this structure only.  If you insert new
90965 ** interfaces in the middle of this structure, then older different
90966 ** versions of SQLite will not be able to load each others' shared
90967 ** libraries!
90968 */
90969 struct sqlite3_api_routines {
90970   void * (*aggregate_context)(sqlite3_context*,int nBytes);
90971   int  (*aggregate_count)(sqlite3_context*);
90972   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
90973   int  (*bind_double)(sqlite3_stmt*,int,double);
90974   int  (*bind_int)(sqlite3_stmt*,int,int);
90975   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
90976   int  (*bind_null)(sqlite3_stmt*,int);
90977   int  (*bind_parameter_count)(sqlite3_stmt*);
90978   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
90979   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
90980   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
90981   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
90982   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
90983   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
90984   int  (*busy_timeout)(sqlite3*,int ms);
90985   int  (*changes)(sqlite3*);
90986   int  (*close)(sqlite3*);
90987   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
90988                            int eTextRep,const char*));
90989   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
90990                              int eTextRep,const void*));
90991   const void * (*column_blob)(sqlite3_stmt*,int iCol);
90992   int  (*column_bytes)(sqlite3_stmt*,int iCol);
90993   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
90994   int  (*column_count)(sqlite3_stmt*pStmt);
90995   const char * (*column_database_name)(sqlite3_stmt*,int);
90996   const void * (*column_database_name16)(sqlite3_stmt*,int);
90997   const char * (*column_decltype)(sqlite3_stmt*,int i);
90998   const void * (*column_decltype16)(sqlite3_stmt*,int);
90999   double  (*column_double)(sqlite3_stmt*,int iCol);
91000   int  (*column_int)(sqlite3_stmt*,int iCol);
91001   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
91002   const char * (*column_name)(sqlite3_stmt*,int);
91003   const void * (*column_name16)(sqlite3_stmt*,int);
91004   const char * (*column_origin_name)(sqlite3_stmt*,int);
91005   const void * (*column_origin_name16)(sqlite3_stmt*,int);
91006   const char * (*column_table_name)(sqlite3_stmt*,int);
91007   const void * (*column_table_name16)(sqlite3_stmt*,int);
91008   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
91009   const void * (*column_text16)(sqlite3_stmt*,int iCol);
91010   int  (*column_type)(sqlite3_stmt*,int iCol);
91011   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
91012   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
91013   int  (*complete)(const char*sql);
91014   int  (*complete16)(const void*sql);
91015   int  (*create_collation)(sqlite3*,const char*,int,void*,
91016                            int(*)(void*,int,const void*,int,const void*));
91017   int  (*create_collation16)(sqlite3*,const void*,int,void*,
91018                              int(*)(void*,int,const void*,int,const void*));
91019   int  (*create_function)(sqlite3*,const char*,int,int,void*,
91020                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91021                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91022                           void (*xFinal)(sqlite3_context*));
91023   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
91024                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91025                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91026                             void (*xFinal)(sqlite3_context*));
91027   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
91028   int  (*data_count)(sqlite3_stmt*pStmt);
91029   sqlite3 * (*db_handle)(sqlite3_stmt*);
91030   int (*declare_vtab)(sqlite3*,const char*);
91031   int  (*enable_shared_cache)(int);
91032   int  (*errcode)(sqlite3*db);
91033   const char * (*errmsg)(sqlite3*);
91034   const void * (*errmsg16)(sqlite3*);
91035   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
91036   int  (*expired)(sqlite3_stmt*);
91037   int  (*finalize)(sqlite3_stmt*pStmt);
91038   void  (*free)(void*);
91039   void  (*free_table)(char**result);
91040   int  (*get_autocommit)(sqlite3*);
91041   void * (*get_auxdata)(sqlite3_context*,int);
91042   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
91043   int  (*global_recover)(void);
91044   void  (*interruptx)(sqlite3*);
91045   sqlite_int64  (*last_insert_rowid)(sqlite3*);
91046   const char * (*libversion)(void);
91047   int  (*libversion_number)(void);
91048   void *(*malloc)(int);
91049   char * (*mprintf)(const char*,...);
91050   int  (*open)(const char*,sqlite3**);
91051   int  (*open16)(const void*,sqlite3**);
91052   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91053   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91054   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
91055   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
91056   void *(*realloc)(void*,int);
91057   int  (*reset)(sqlite3_stmt*pStmt);
91058   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
91059   void  (*result_double)(sqlite3_context*,double);
91060   void  (*result_error)(sqlite3_context*,const char*,int);
91061   void  (*result_error16)(sqlite3_context*,const void*,int);
91062   void  (*result_int)(sqlite3_context*,int);
91063   void  (*result_int64)(sqlite3_context*,sqlite_int64);
91064   void  (*result_null)(sqlite3_context*);
91065   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
91066   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
91067   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
91068   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
91069   void  (*result_value)(sqlite3_context*,sqlite3_value*);
91070   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
91071   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
91072                          const char*,const char*),void*);
91073   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
91074   char * (*snprintf)(int,char*,const char*,...);
91075   int  (*step)(sqlite3_stmt*);
91076   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
91077                                 char const**,char const**,int*,int*,int*);
91078   void  (*thread_cleanup)(void);
91079   int  (*total_changes)(sqlite3*);
91080   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
91081   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
91082   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
91083                                          sqlite_int64),void*);
91084   void * (*user_data)(sqlite3_context*);
91085   const void * (*value_blob)(sqlite3_value*);
91086   int  (*value_bytes)(sqlite3_value*);
91087   int  (*value_bytes16)(sqlite3_value*);
91088   double  (*value_double)(sqlite3_value*);
91089   int  (*value_int)(sqlite3_value*);
91090   sqlite_int64  (*value_int64)(sqlite3_value*);
91091   int  (*value_numeric_type)(sqlite3_value*);
91092   const unsigned char * (*value_text)(sqlite3_value*);
91093   const void * (*value_text16)(sqlite3_value*);
91094   const void * (*value_text16be)(sqlite3_value*);
91095   const void * (*value_text16le)(sqlite3_value*);
91096   int  (*value_type)(sqlite3_value*);
91097   char *(*vmprintf)(const char*,va_list);
91098   /* Added ??? */
91099   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
91100   /* Added by 3.3.13 */
91101   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91102   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91103   int (*clear_bindings)(sqlite3_stmt*);
91104   /* Added by 3.4.1 */
91105   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
91106                           void (*xDestroy)(void *));
91107   /* Added by 3.5.0 */
91108   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
91109   int (*blob_bytes)(sqlite3_blob*);
91110   int (*blob_close)(sqlite3_blob*);
91111   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
91112                    int,sqlite3_blob**);
91113   int (*blob_read)(sqlite3_blob*,void*,int,int);
91114   int (*blob_write)(sqlite3_blob*,const void*,int,int);
91115   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
91116                              int(*)(void*,int,const void*,int,const void*),
91117                              void(*)(void*));
91118   int (*file_control)(sqlite3*,const char*,int,void*);
91119   sqlite3_int64 (*memory_highwater)(int);
91120   sqlite3_int64 (*memory_used)(void);
91121   sqlite3_mutex *(*mutex_alloc)(int);
91122   void (*mutex_enter)(sqlite3_mutex*);
91123   void (*mutex_free)(sqlite3_mutex*);
91124   void (*mutex_leave)(sqlite3_mutex*);
91125   int (*mutex_try)(sqlite3_mutex*);
91126   int (*open_v2)(const char*,sqlite3**,int,const char*);
91127   int (*release_memory)(int);
91128   void (*result_error_nomem)(sqlite3_context*);
91129   void (*result_error_toobig)(sqlite3_context*);
91130   int (*sleep)(int);
91131   void (*soft_heap_limit)(int);
91132   sqlite3_vfs *(*vfs_find)(const char*);
91133   int (*vfs_register)(sqlite3_vfs*,int);
91134   int (*vfs_unregister)(sqlite3_vfs*);
91135   int (*xthreadsafe)(void);
91136   void (*result_zeroblob)(sqlite3_context*,int);
91137   void (*result_error_code)(sqlite3_context*,int);
91138   int (*test_control)(int, ...);
91139   void (*randomness)(int,void*);
91140   sqlite3 *(*context_db_handle)(sqlite3_context*);
91141   int (*extended_result_codes)(sqlite3*,int);
91142   int (*limit)(sqlite3*,int,int);
91143   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
91144   const char *(*sql)(sqlite3_stmt*);
91145   int (*status)(int,int*,int*,int);
91146   int (*backup_finish)(sqlite3_backup*);
91147   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
91148   int (*backup_pagecount)(sqlite3_backup*);
91149   int (*backup_remaining)(sqlite3_backup*);
91150   int (*backup_step)(sqlite3_backup*,int);
91151   const char *(*compileoption_get)(int);
91152   int (*compileoption_used)(const char*);
91153   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
91154                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91155                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91156                             void (*xFinal)(sqlite3_context*),
91157                             void(*xDestroy)(void*));
91158   int (*db_config)(sqlite3*,int,...);
91159   sqlite3_mutex *(*db_mutex)(sqlite3*);
91160   int (*db_status)(sqlite3*,int,int*,int*,int);
91161   int (*extended_errcode)(sqlite3*);
91162   void (*log)(int,const char*,...);
91163   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
91164   const char *(*sourceid)(void);
91165   int (*stmt_status)(sqlite3_stmt*,int,int);
91166   int (*strnicmp)(const char*,const char*,int);
91167   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
91168   int (*wal_autocheckpoint)(sqlite3*,int);
91169   int (*wal_checkpoint)(sqlite3*,const char*);
91170   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
91171   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
91172   int (*vtab_config)(sqlite3*,int op,...);
91173   int (*vtab_on_conflict)(sqlite3*);
91174   /* Version 3.7.16 and later */
91175   int (*close_v2)(sqlite3*);
91176   const char *(*db_filename)(sqlite3*,const char*);
91177   int (*db_readonly)(sqlite3*,const char*);
91178   int (*db_release_memory)(sqlite3*);
91179   const char *(*errstr)(int);
91180   int (*stmt_busy)(sqlite3_stmt*);
91181   int (*stmt_readonly)(sqlite3_stmt*);
91182   int (*stricmp)(const char*,const char*);
91183   int (*uri_boolean)(const char*,const char*,int);
91184   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
91185   const char *(*uri_parameter)(const char*,const char*);
91186   char *(*vsnprintf)(int,char*,const char*,va_list);
91187   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
91188 };
91189 
91190 /*
91191 ** The following macros redefine the API routines so that they are
91192 ** redirected throught the global sqlite3_api structure.
91193 **
91194 ** This header file is also used by the loadext.c source file
91195 ** (part of the main SQLite library - not an extension) so that
91196 ** it can get access to the sqlite3_api_routines structure
91197 ** definition.  But the main library does not want to redefine
91198 ** the API.  So the redefinition macros are only valid if the
91199 ** SQLITE_CORE macros is undefined.
91200 */
91201 #ifndef SQLITE_CORE
91202 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
91203 #ifndef SQLITE_OMIT_DEPRECATED
91204 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
91205 #endif
91206 #define sqlite3_bind_blob              sqlite3_api->bind_blob
91207 #define sqlite3_bind_double            sqlite3_api->bind_double
91208 #define sqlite3_bind_int               sqlite3_api->bind_int
91209 #define sqlite3_bind_int64             sqlite3_api->bind_int64
91210 #define sqlite3_bind_null              sqlite3_api->bind_null
91211 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
91212 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
91213 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
91214 #define sqlite3_bind_text              sqlite3_api->bind_text
91215 #define sqlite3_bind_text16            sqlite3_api->bind_text16
91216 #define sqlite3_bind_value             sqlite3_api->bind_value
91217 #define sqlite3_busy_handler           sqlite3_api->busy_handler
91218 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
91219 #define sqlite3_changes                sqlite3_api->changes
91220 #define sqlite3_close                  sqlite3_api->close
91221 #define sqlite3_collation_needed       sqlite3_api->collation_needed
91222 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
91223 #define sqlite3_column_blob            sqlite3_api->column_blob
91224 #define sqlite3_column_bytes           sqlite3_api->column_bytes
91225 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
91226 #define sqlite3_column_count           sqlite3_api->column_count
91227 #define sqlite3_column_database_name   sqlite3_api->column_database_name
91228 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
91229 #define sqlite3_column_decltype        sqlite3_api->column_decltype
91230 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
91231 #define sqlite3_column_double          sqlite3_api->column_double
91232 #define sqlite3_column_int             sqlite3_api->column_int
91233 #define sqlite3_column_int64           sqlite3_api->column_int64
91234 #define sqlite3_column_name            sqlite3_api->column_name
91235 #define sqlite3_column_name16          sqlite3_api->column_name16
91236 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
91237 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
91238 #define sqlite3_column_table_name      sqlite3_api->column_table_name
91239 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
91240 #define sqlite3_column_text            sqlite3_api->column_text
91241 #define sqlite3_column_text16          sqlite3_api->column_text16
91242 #define sqlite3_column_type            sqlite3_api->column_type
91243 #define sqlite3_column_value           sqlite3_api->column_value
91244 #define sqlite3_commit_hook            sqlite3_api->commit_hook
91245 #define sqlite3_complete               sqlite3_api->complete
91246 #define sqlite3_complete16             sqlite3_api->complete16
91247 #define sqlite3_create_collation       sqlite3_api->create_collation
91248 #define sqlite3_create_collation16     sqlite3_api->create_collation16
91249 #define sqlite3_create_function        sqlite3_api->create_function
91250 #define sqlite3_create_function16      sqlite3_api->create_function16
91251 #define sqlite3_create_module          sqlite3_api->create_module
91252 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
91253 #define sqlite3_data_count             sqlite3_api->data_count
91254 #define sqlite3_db_handle              sqlite3_api->db_handle
91255 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
91256 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
91257 #define sqlite3_errcode                sqlite3_api->errcode
91258 #define sqlite3_errmsg                 sqlite3_api->errmsg
91259 #define sqlite3_errmsg16               sqlite3_api->errmsg16
91260 #define sqlite3_exec                   sqlite3_api->exec
91261 #ifndef SQLITE_OMIT_DEPRECATED
91262 #define sqlite3_expired                sqlite3_api->expired
91263 #endif
91264 #define sqlite3_finalize               sqlite3_api->finalize
91265 #define sqlite3_free                   sqlite3_api->free
91266 #define sqlite3_free_table             sqlite3_api->free_table
91267 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
91268 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
91269 #define sqlite3_get_table              sqlite3_api->get_table
91270 #ifndef SQLITE_OMIT_DEPRECATED
91271 #define sqlite3_global_recover         sqlite3_api->global_recover
91272 #endif
91273 #define sqlite3_interrupt              sqlite3_api->interruptx
91274 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
91275 #define sqlite3_libversion             sqlite3_api->libversion
91276 #define sqlite3_libversion_number      sqlite3_api->libversion_number
91277 #define sqlite3_malloc                 sqlite3_api->malloc
91278 #define sqlite3_mprintf                sqlite3_api->mprintf
91279 #define sqlite3_open                   sqlite3_api->open
91280 #define sqlite3_open16                 sqlite3_api->open16
91281 #define sqlite3_prepare                sqlite3_api->prepare
91282 #define sqlite3_prepare16              sqlite3_api->prepare16
91283 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91284 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91285 #define sqlite3_profile                sqlite3_api->profile
91286 #define sqlite3_progress_handler       sqlite3_api->progress_handler
91287 #define sqlite3_realloc                sqlite3_api->realloc
91288 #define sqlite3_reset                  sqlite3_api->reset
91289 #define sqlite3_result_blob            sqlite3_api->result_blob
91290 #define sqlite3_result_double          sqlite3_api->result_double
91291 #define sqlite3_result_error           sqlite3_api->result_error
91292 #define sqlite3_result_error16         sqlite3_api->result_error16
91293 #define sqlite3_result_int             sqlite3_api->result_int
91294 #define sqlite3_result_int64           sqlite3_api->result_int64
91295 #define sqlite3_result_null            sqlite3_api->result_null
91296 #define sqlite3_result_text            sqlite3_api->result_text
91297 #define sqlite3_result_text16          sqlite3_api->result_text16
91298 #define sqlite3_result_text16be        sqlite3_api->result_text16be
91299 #define sqlite3_result_text16le        sqlite3_api->result_text16le
91300 #define sqlite3_result_value           sqlite3_api->result_value
91301 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
91302 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
91303 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
91304 #define sqlite3_snprintf               sqlite3_api->snprintf
91305 #define sqlite3_step                   sqlite3_api->step
91306 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
91307 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
91308 #define sqlite3_total_changes          sqlite3_api->total_changes
91309 #define sqlite3_trace                  sqlite3_api->trace
91310 #ifndef SQLITE_OMIT_DEPRECATED
91311 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
91312 #endif
91313 #define sqlite3_update_hook            sqlite3_api->update_hook
91314 #define sqlite3_user_data              sqlite3_api->user_data
91315 #define sqlite3_value_blob             sqlite3_api->value_blob
91316 #define sqlite3_value_bytes            sqlite3_api->value_bytes
91317 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
91318 #define sqlite3_value_double           sqlite3_api->value_double
91319 #define sqlite3_value_int              sqlite3_api->value_int
91320 #define sqlite3_value_int64            sqlite3_api->value_int64
91321 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
91322 #define sqlite3_value_text             sqlite3_api->value_text
91323 #define sqlite3_value_text16           sqlite3_api->value_text16
91324 #define sqlite3_value_text16be         sqlite3_api->value_text16be
91325 #define sqlite3_value_text16le         sqlite3_api->value_text16le
91326 #define sqlite3_value_type             sqlite3_api->value_type
91327 #define sqlite3_vmprintf               sqlite3_api->vmprintf
91328 #define sqlite3_overload_function      sqlite3_api->overload_function
91329 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91330 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91331 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
91332 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
91333 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
91334 #define sqlite3_blob_close             sqlite3_api->blob_close
91335 #define sqlite3_blob_open              sqlite3_api->blob_open
91336 #define sqlite3_blob_read              sqlite3_api->blob_read
91337 #define sqlite3_blob_write             sqlite3_api->blob_write
91338 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
91339 #define sqlite3_file_control           sqlite3_api->file_control
91340 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
91341 #define sqlite3_memory_used            sqlite3_api->memory_used
91342 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
91343 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
91344 #define sqlite3_mutex_free             sqlite3_api->mutex_free
91345 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
91346 #define sqlite3_mutex_try              sqlite3_api->mutex_try
91347 #define sqlite3_open_v2                sqlite3_api->open_v2
91348 #define sqlite3_release_memory         sqlite3_api->release_memory
91349 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
91350 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
91351 #define sqlite3_sleep                  sqlite3_api->sleep
91352 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
91353 #define sqlite3_vfs_find               sqlite3_api->vfs_find
91354 #define sqlite3_vfs_register           sqlite3_api->vfs_register
91355 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
91356 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
91357 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
91358 #define sqlite3_result_error_code      sqlite3_api->result_error_code
91359 #define sqlite3_test_control           sqlite3_api->test_control
91360 #define sqlite3_randomness             sqlite3_api->randomness
91361 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
91362 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
91363 #define sqlite3_limit                  sqlite3_api->limit
91364 #define sqlite3_next_stmt              sqlite3_api->next_stmt
91365 #define sqlite3_sql                    sqlite3_api->sql
91366 #define sqlite3_status                 sqlite3_api->status
91367 #define sqlite3_backup_finish          sqlite3_api->backup_finish
91368 #define sqlite3_backup_init            sqlite3_api->backup_init
91369 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
91370 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
91371 #define sqlite3_backup_step            sqlite3_api->backup_step
91372 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
91373 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
91374 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
91375 #define sqlite3_db_config              sqlite3_api->db_config
91376 #define sqlite3_db_mutex               sqlite3_api->db_mutex
91377 #define sqlite3_db_status              sqlite3_api->db_status
91378 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
91379 #define sqlite3_log                    sqlite3_api->log
91380 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
91381 #define sqlite3_sourceid               sqlite3_api->sourceid
91382 #define sqlite3_stmt_status            sqlite3_api->stmt_status
91383 #define sqlite3_strnicmp               sqlite3_api->strnicmp
91384 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
91385 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
91386 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
91387 #define sqlite3_wal_hook               sqlite3_api->wal_hook
91388 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
91389 #define sqlite3_vtab_config            sqlite3_api->vtab_config
91390 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
91391 /* Version 3.7.16 and later */
91392 #define sqlite3_close_v2               sqlite3_api->close_v2
91393 #define sqlite3_db_filename            sqlite3_api->db_filename
91394 #define sqlite3_db_readonly            sqlite3_api->db_readonly
91395 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
91396 #define sqlite3_errstr                 sqlite3_api->errstr
91397 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
91398 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
91399 #define sqlite3_stricmp                sqlite3_api->stricmp
91400 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
91401 #define sqlite3_uri_int64              sqlite3_api->uri_int64
91402 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
91403 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
91404 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
91405 #endif /* SQLITE_CORE */
91406 
91407 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
91408 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
91409 
91410 #endif /* _SQLITE3EXT_H_ */
91411 
91412 /************** End of sqlite3ext.h ******************************************/
91413 /************** Continuing where we left off in loadext.c ********************/
91414 /* #include <string.h> */
91415 
91416 #ifndef SQLITE_OMIT_LOAD_EXTENSION
91417 
91418 /*
91419 ** Some API routines are omitted when various features are
91420 ** excluded from a build of SQLite.  Substitute a NULL pointer
91421 ** for any missing APIs.
91422 */
91423 #ifndef SQLITE_ENABLE_COLUMN_METADATA
91424 # define sqlite3_column_database_name   0
91425 # define sqlite3_column_database_name16 0
91426 # define sqlite3_column_table_name      0
91427 # define sqlite3_column_table_name16    0
91428 # define sqlite3_column_origin_name     0
91429 # define sqlite3_column_origin_name16   0
91430 # define sqlite3_table_column_metadata  0
91431 #endif
91432 
91433 #ifdef SQLITE_OMIT_AUTHORIZATION
91434 # define sqlite3_set_authorizer         0
91435 #endif
91436 
91437 #ifdef SQLITE_OMIT_UTF16
91438 # define sqlite3_bind_text16            0
91439 # define sqlite3_collation_needed16     0
91440 # define sqlite3_column_decltype16      0
91441 # define sqlite3_column_name16          0
91442 # define sqlite3_column_text16          0
91443 # define sqlite3_complete16             0
91444 # define sqlite3_create_collation16     0
91445 # define sqlite3_create_function16      0
91446 # define sqlite3_errmsg16               0
91447 # define sqlite3_open16                 0
91448 # define sqlite3_prepare16              0
91449 # define sqlite3_prepare16_v2           0
91450 # define sqlite3_result_error16         0
91451 # define sqlite3_result_text16          0
91452 # define sqlite3_result_text16be        0
91453 # define sqlite3_result_text16le        0
91454 # define sqlite3_value_text16           0
91455 # define sqlite3_value_text16be         0
91456 # define sqlite3_value_text16le         0
91457 # define sqlite3_column_database_name16 0
91458 # define sqlite3_column_table_name16    0
91459 # define sqlite3_column_origin_name16   0
91460 #endif
91461 
91462 #ifdef SQLITE_OMIT_COMPLETE
91463 # define sqlite3_complete 0
91464 # define sqlite3_complete16 0
91465 #endif
91466 
91467 #ifdef SQLITE_OMIT_DECLTYPE
91468 # define sqlite3_column_decltype16      0
91469 # define sqlite3_column_decltype        0
91470 #endif
91471 
91472 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
91473 # define sqlite3_progress_handler 0
91474 #endif
91475 
91476 #ifdef SQLITE_OMIT_VIRTUALTABLE
91477 # define sqlite3_create_module 0
91478 # define sqlite3_create_module_v2 0
91479 # define sqlite3_declare_vtab 0
91480 # define sqlite3_vtab_config 0
91481 # define sqlite3_vtab_on_conflict 0
91482 #endif
91483 
91484 #ifdef SQLITE_OMIT_SHARED_CACHE
91485 # define sqlite3_enable_shared_cache 0
91486 #endif
91487 
91488 #ifdef SQLITE_OMIT_TRACE
91489 # define sqlite3_profile       0
91490 # define sqlite3_trace         0
91491 #endif
91492 
91493 #ifdef SQLITE_OMIT_GET_TABLE
91494 # define sqlite3_free_table    0
91495 # define sqlite3_get_table     0
91496 #endif
91497 
91498 #ifdef SQLITE_OMIT_INCRBLOB
91499 #define sqlite3_bind_zeroblob  0
91500 #define sqlite3_blob_bytes     0
91501 #define sqlite3_blob_close     0
91502 #define sqlite3_blob_open      0
91503 #define sqlite3_blob_read      0
91504 #define sqlite3_blob_write     0
91505 #define sqlite3_blob_reopen    0
91506 #endif
91507 
91508 /*
91509 ** The following structure contains pointers to all SQLite API routines.
91510 ** A pointer to this structure is passed into extensions when they are
91511 ** loaded so that the extension can make calls back into the SQLite
91512 ** library.
91513 **
91514 ** When adding new APIs, add them to the bottom of this structure
91515 ** in order to preserve backwards compatibility.
91516 **
91517 ** Extensions that use newer APIs should first call the
91518 ** sqlite3_libversion_number() to make sure that the API they
91519 ** intend to use is supported by the library.  Extensions should
91520 ** also check to make sure that the pointer to the function is
91521 ** not NULL before calling it.
91522 */
91523 static const sqlite3_api_routines sqlite3Apis = {
91524   sqlite3_aggregate_context,
91525 #ifndef SQLITE_OMIT_DEPRECATED
91526   sqlite3_aggregate_count,
91527 #else
91528   0,
91529 #endif
91530   sqlite3_bind_blob,
91531   sqlite3_bind_double,
91532   sqlite3_bind_int,
91533   sqlite3_bind_int64,
91534   sqlite3_bind_null,
91535   sqlite3_bind_parameter_count,
91536   sqlite3_bind_parameter_index,
91537   sqlite3_bind_parameter_name,
91538   sqlite3_bind_text,
91539   sqlite3_bind_text16,
91540   sqlite3_bind_value,
91541   sqlite3_busy_handler,
91542   sqlite3_busy_timeout,
91543   sqlite3_changes,
91544   sqlite3_close,
91545   sqlite3_collation_needed,
91546   sqlite3_collation_needed16,
91547   sqlite3_column_blob,
91548   sqlite3_column_bytes,
91549   sqlite3_column_bytes16,
91550   sqlite3_column_count,
91551   sqlite3_column_database_name,
91552   sqlite3_column_database_name16,
91553   sqlite3_column_decltype,
91554   sqlite3_column_decltype16,
91555   sqlite3_column_double,
91556   sqlite3_column_int,
91557   sqlite3_column_int64,
91558   sqlite3_column_name,
91559   sqlite3_column_name16,
91560   sqlite3_column_origin_name,
91561   sqlite3_column_origin_name16,
91562   sqlite3_column_table_name,
91563   sqlite3_column_table_name16,
91564   sqlite3_column_text,
91565   sqlite3_column_text16,
91566   sqlite3_column_type,
91567   sqlite3_column_value,
91568   sqlite3_commit_hook,
91569   sqlite3_complete,
91570   sqlite3_complete16,
91571   sqlite3_create_collation,
91572   sqlite3_create_collation16,
91573   sqlite3_create_function,
91574   sqlite3_create_function16,
91575   sqlite3_create_module,
91576   sqlite3_data_count,
91577   sqlite3_db_handle,
91578   sqlite3_declare_vtab,
91579   sqlite3_enable_shared_cache,
91580   sqlite3_errcode,
91581   sqlite3_errmsg,
91582   sqlite3_errmsg16,
91583   sqlite3_exec,
91584 #ifndef SQLITE_OMIT_DEPRECATED
91585   sqlite3_expired,
91586 #else
91587   0,
91588 #endif
91589   sqlite3_finalize,
91590   sqlite3_free,
91591   sqlite3_free_table,
91592   sqlite3_get_autocommit,
91593   sqlite3_get_auxdata,
91594   sqlite3_get_table,
91595   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
91596   sqlite3_interrupt,
91597   sqlite3_last_insert_rowid,
91598   sqlite3_libversion,
91599   sqlite3_libversion_number,
91600   sqlite3_malloc,
91601   sqlite3_mprintf,
91602   sqlite3_open,
91603   sqlite3_open16,
91604   sqlite3_prepare,
91605   sqlite3_prepare16,
91606   sqlite3_profile,
91607   sqlite3_progress_handler,
91608   sqlite3_realloc,
91609   sqlite3_reset,
91610   sqlite3_result_blob,
91611   sqlite3_result_double,
91612   sqlite3_result_error,
91613   sqlite3_result_error16,
91614   sqlite3_result_int,
91615   sqlite3_result_int64,
91616   sqlite3_result_null,
91617   sqlite3_result_text,
91618   sqlite3_result_text16,
91619   sqlite3_result_text16be,
91620   sqlite3_result_text16le,
91621   sqlite3_result_value,
91622   sqlite3_rollback_hook,
91623   sqlite3_set_authorizer,
91624   sqlite3_set_auxdata,
91625   sqlite3_snprintf,
91626   sqlite3_step,
91627   sqlite3_table_column_metadata,
91628 #ifndef SQLITE_OMIT_DEPRECATED
91629   sqlite3_thread_cleanup,
91630 #else
91631   0,
91632 #endif
91633   sqlite3_total_changes,
91634   sqlite3_trace,
91635 #ifndef SQLITE_OMIT_DEPRECATED
91636   sqlite3_transfer_bindings,
91637 #else
91638   0,
91639 #endif
91640   sqlite3_update_hook,
91641   sqlite3_user_data,
91642   sqlite3_value_blob,
91643   sqlite3_value_bytes,
91644   sqlite3_value_bytes16,
91645   sqlite3_value_double,
91646   sqlite3_value_int,
91647   sqlite3_value_int64,
91648   sqlite3_value_numeric_type,
91649   sqlite3_value_text,
91650   sqlite3_value_text16,
91651   sqlite3_value_text16be,
91652   sqlite3_value_text16le,
91653   sqlite3_value_type,
91654   sqlite3_vmprintf,
91655   /*
91656   ** The original API set ends here.  All extensions can call any
91657   ** of the APIs above provided that the pointer is not NULL.  But
91658   ** before calling APIs that follow, extension should check the
91659   ** sqlite3_libversion_number() to make sure they are dealing with
91660   ** a library that is new enough to support that API.
91661   *************************************************************************
91662   */
91663   sqlite3_overload_function,
91664 
91665   /*
91666   ** Added after 3.3.13
91667   */
91668   sqlite3_prepare_v2,
91669   sqlite3_prepare16_v2,
91670   sqlite3_clear_bindings,
91671 
91672   /*
91673   ** Added for 3.4.1
91674   */
91675   sqlite3_create_module_v2,
91676 
91677   /*
91678   ** Added for 3.5.0
91679   */
91680   sqlite3_bind_zeroblob,
91681   sqlite3_blob_bytes,
91682   sqlite3_blob_close,
91683   sqlite3_blob_open,
91684   sqlite3_blob_read,
91685   sqlite3_blob_write,
91686   sqlite3_create_collation_v2,
91687   sqlite3_file_control,
91688   sqlite3_memory_highwater,
91689   sqlite3_memory_used,
91690 #ifdef SQLITE_MUTEX_OMIT
91691   0,
91692   0,
91693   0,
91694   0,
91695   0,
91696 #else
91697   sqlite3_mutex_alloc,
91698   sqlite3_mutex_enter,
91699   sqlite3_mutex_free,
91700   sqlite3_mutex_leave,
91701   sqlite3_mutex_try,
91702 #endif
91703   sqlite3_open_v2,
91704   sqlite3_release_memory,
91705   sqlite3_result_error_nomem,
91706   sqlite3_result_error_toobig,
91707   sqlite3_sleep,
91708   sqlite3_soft_heap_limit,
91709   sqlite3_vfs_find,
91710   sqlite3_vfs_register,
91711   sqlite3_vfs_unregister,
91712 
91713   /*
91714   ** Added for 3.5.8
91715   */
91716   sqlite3_threadsafe,
91717   sqlite3_result_zeroblob,
91718   sqlite3_result_error_code,
91719   sqlite3_test_control,
91720   sqlite3_randomness,
91721   sqlite3_context_db_handle,
91722 
91723   /*
91724   ** Added for 3.6.0
91725   */
91726   sqlite3_extended_result_codes,
91727   sqlite3_limit,
91728   sqlite3_next_stmt,
91729   sqlite3_sql,
91730   sqlite3_status,
91731 
91732   /*
91733   ** Added for 3.7.4
91734   */
91735   sqlite3_backup_finish,
91736   sqlite3_backup_init,
91737   sqlite3_backup_pagecount,
91738   sqlite3_backup_remaining,
91739   sqlite3_backup_step,
91740 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91741   sqlite3_compileoption_get,
91742   sqlite3_compileoption_used,
91743 #else
91744   0,
91745   0,
91746 #endif
91747   sqlite3_create_function_v2,
91748   sqlite3_db_config,
91749   sqlite3_db_mutex,
91750   sqlite3_db_status,
91751   sqlite3_extended_errcode,
91752   sqlite3_log,
91753   sqlite3_soft_heap_limit64,
91754   sqlite3_sourceid,
91755   sqlite3_stmt_status,
91756   sqlite3_strnicmp,
91757 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
91758   sqlite3_unlock_notify,
91759 #else
91760   0,
91761 #endif
91762 #ifndef SQLITE_OMIT_WAL
91763   sqlite3_wal_autocheckpoint,
91764   sqlite3_wal_checkpoint,
91765   sqlite3_wal_hook,
91766 #else
91767   0,
91768   0,
91769   0,
91770 #endif
91771   sqlite3_blob_reopen,
91772   sqlite3_vtab_config,
91773   sqlite3_vtab_on_conflict,
91774   sqlite3_close_v2,
91775   sqlite3_db_filename,
91776   sqlite3_db_readonly,
91777   sqlite3_db_release_memory,
91778   sqlite3_errstr,
91779   sqlite3_stmt_busy,
91780   sqlite3_stmt_readonly,
91781   sqlite3_stricmp,
91782   sqlite3_uri_boolean,
91783   sqlite3_uri_int64,
91784   sqlite3_uri_parameter,
91785   sqlite3_vsnprintf,
91786   sqlite3_wal_checkpoint_v2
91787 };
91788 
91789 /*
91790 ** Attempt to load an SQLite extension library contained in the file
91791 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91792 ** default entry point name (sqlite3_extension_init) is used.  Use
91793 ** of the default name is recommended.
91794 **
91795 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
91796 **
91797 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
91798 ** error message text.  The calling function should free this memory
91799 ** by calling sqlite3DbFree(db, ).
91800 */
91801 static int sqlite3LoadExtension(
91802   sqlite3 *db,          /* Load the extension into this database connection */
91803   const char *zFile,    /* Name of the shared library containing extension */
91804   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91805   char **pzErrMsg       /* Put error message here if not 0 */
91806 ){
91807   sqlite3_vfs *pVfs = db->pVfs;
91808   void *handle;
91809   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91810   char *zErrmsg = 0;
91811   void **aHandle;
91812   int nMsg = 300 + sqlite3Strlen30(zFile);
91813 
91814   if( pzErrMsg ) *pzErrMsg = 0;
91815 
91816   /* Ticket #1863.  To avoid a creating security problems for older
91817   ** applications that relink against newer versions of SQLite, the
91818   ** ability to run load_extension is turned off by default.  One
91819   ** must call sqlite3_enable_load_extension() to turn on extension
91820   ** loading.  Otherwise you get the following error.
91821   */
91822   if( (db->flags & SQLITE_LoadExtension)==0 ){
91823     if( pzErrMsg ){
91824       *pzErrMsg = sqlite3_mprintf("not authorized");
91825     }
91826     return SQLITE_ERROR;
91827   }
91828 
91829   if( zProc==0 ){
91830     zProc = "sqlite3_extension_init";
91831   }
91832 
91833   handle = sqlite3OsDlOpen(pVfs, zFile);
91834   if( handle==0 ){
91835     if( pzErrMsg ){
91836       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91837       if( zErrmsg ){
91838         sqlite3_snprintf(nMsg, zErrmsg,
91839             "unable to open shared library [%s]", zFile);
91840         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91841       }
91842     }
91843     return SQLITE_ERROR;
91844   }
91845   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91846                    sqlite3OsDlSym(pVfs, handle, zProc);
91847   if( xInit==0 ){
91848     if( pzErrMsg ){
91849       nMsg += sqlite3Strlen30(zProc);
91850       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91851       if( zErrmsg ){
91852         sqlite3_snprintf(nMsg, zErrmsg,
91853             "no entry point [%s] in shared library [%s]", zProc,zFile);
91854         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91855       }
91856       sqlite3OsDlClose(pVfs, handle);
91857     }
91858     return SQLITE_ERROR;
91859   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
91860     if( pzErrMsg ){
91861       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
91862     }
91863     sqlite3_free(zErrmsg);
91864     sqlite3OsDlClose(pVfs, handle);
91865     return SQLITE_ERROR;
91866   }
91867 
91868   /* Append the new shared library handle to the db->aExtension array. */
91869   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91870   if( aHandle==0 ){
91871     return SQLITE_NOMEM;
91872   }
91873   if( db->nExtension>0 ){
91874     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91875   }
91876   sqlite3DbFree(db, db->aExtension);
91877   db->aExtension = aHandle;
91878 
91879   db->aExtension[db->nExtension++] = handle;
91880   return SQLITE_OK;
91881 }
91882 SQLITE_API int sqlite3_load_extension(
91883   sqlite3 *db,          /* Load the extension into this database connection */
91884   const char *zFile,    /* Name of the shared library containing extension */
91885   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91886   char **pzErrMsg       /* Put error message here if not 0 */
91887 ){
91888   int rc;
91889   sqlite3_mutex_enter(db->mutex);
91890   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
91891   rc = sqlite3ApiExit(db, rc);
91892   sqlite3_mutex_leave(db->mutex);
91893   return rc;
91894 }
91895 
91896 /*
91897 ** Call this routine when the database connection is closing in order
91898 ** to clean up loaded extensions
91899 */
91900 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
91901   int i;
91902   assert( sqlite3_mutex_held(db->mutex) );
91903   for(i=0; i<db->nExtension; i++){
91904     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
91905   }
91906   sqlite3DbFree(db, db->aExtension);
91907 }
91908 
91909 /*
91910 ** Enable or disable extension loading.  Extension loading is disabled by
91911 ** default so as not to open security holes in older applications.
91912 */
91913 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
91914   sqlite3_mutex_enter(db->mutex);
91915   if( onoff ){
91916     db->flags |= SQLITE_LoadExtension;
91917   }else{
91918     db->flags &= ~SQLITE_LoadExtension;
91919   }
91920   sqlite3_mutex_leave(db->mutex);
91921   return SQLITE_OK;
91922 }
91923 
91924 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
91925 
91926 /*
91927 ** The auto-extension code added regardless of whether or not extension
91928 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
91929 ** code if regular extension loading is not available.  This is that
91930 ** dummy pointer.
91931 */
91932 #ifdef SQLITE_OMIT_LOAD_EXTENSION
91933 static const sqlite3_api_routines sqlite3Apis = { 0 };
91934 #endif
91935 
91936 
91937 /*
91938 ** The following object holds the list of automatically loaded
91939 ** extensions.
91940 **
91941 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
91942 ** mutex must be held while accessing this list.
91943 */
91944 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
91945 static SQLITE_WSD struct sqlite3AutoExtList {
91946   int nExt;              /* Number of entries in aExt[] */
91947   void (**aExt)(void);   /* Pointers to the extension init functions */
91948 } sqlite3Autoext = { 0, 0 };
91949 
91950 /* The "wsdAutoext" macro will resolve to the autoextension
91951 ** state vector.  If writable static data is unsupported on the target,
91952 ** we have to locate the state vector at run-time.  In the more common
91953 ** case where writable static data is supported, wsdStat can refer directly
91954 ** to the "sqlite3Autoext" state vector declared above.
91955 */
91956 #ifdef SQLITE_OMIT_WSD
91957 # define wsdAutoextInit \
91958   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
91959 # define wsdAutoext x[0]
91960 #else
91961 # define wsdAutoextInit
91962 # define wsdAutoext sqlite3Autoext
91963 #endif
91964 
91965 
91966 /*
91967 ** Register a statically linked extension that is automatically
91968 ** loaded by every new database connection.
91969 */
91970 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
91971   int rc = SQLITE_OK;
91972 #ifndef SQLITE_OMIT_AUTOINIT
91973   rc = sqlite3_initialize();
91974   if( rc ){
91975     return rc;
91976   }else
91977 #endif
91978   {
91979     int i;
91980 #if SQLITE_THREADSAFE
91981     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91982 #endif
91983     wsdAutoextInit;
91984     sqlite3_mutex_enter(mutex);
91985     for(i=0; i<wsdAutoext.nExt; i++){
91986       if( wsdAutoext.aExt[i]==xInit ) break;
91987     }
91988     if( i==wsdAutoext.nExt ){
91989       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
91990       void (**aNew)(void);
91991       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
91992       if( aNew==0 ){
91993         rc = SQLITE_NOMEM;
91994       }else{
91995         wsdAutoext.aExt = aNew;
91996         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
91997         wsdAutoext.nExt++;
91998       }
91999     }
92000     sqlite3_mutex_leave(mutex);
92001     assert( (rc&0xff)==rc );
92002     return rc;
92003   }
92004 }
92005 
92006 /*
92007 ** Reset the automatic extension loading mechanism.
92008 */
92009 SQLITE_API void sqlite3_reset_auto_extension(void){
92010 #ifndef SQLITE_OMIT_AUTOINIT
92011   if( sqlite3_initialize()==SQLITE_OK )
92012 #endif
92013   {
92014 #if SQLITE_THREADSAFE
92015     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92016 #endif
92017     wsdAutoextInit;
92018     sqlite3_mutex_enter(mutex);
92019     sqlite3_free(wsdAutoext.aExt);
92020     wsdAutoext.aExt = 0;
92021     wsdAutoext.nExt = 0;
92022     sqlite3_mutex_leave(mutex);
92023   }
92024 }
92025 
92026 /*
92027 ** Load all automatic extensions.
92028 **
92029 ** If anything goes wrong, set an error in the database connection.
92030 */
92031 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
92032   int i;
92033   int go = 1;
92034   int rc;
92035   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
92036 
92037   wsdAutoextInit;
92038   if( wsdAutoext.nExt==0 ){
92039     /* Common case: early out without every having to acquire a mutex */
92040     return;
92041   }
92042   for(i=0; go; i++){
92043     char *zErrmsg;
92044 #if SQLITE_THREADSAFE
92045     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92046 #endif
92047     sqlite3_mutex_enter(mutex);
92048     if( i>=wsdAutoext.nExt ){
92049       xInit = 0;
92050       go = 0;
92051     }else{
92052       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
92053               wsdAutoext.aExt[i];
92054     }
92055     sqlite3_mutex_leave(mutex);
92056     zErrmsg = 0;
92057     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
92058       sqlite3Error(db, rc,
92059             "automatic extension loading failed: %s", zErrmsg);
92060       go = 0;
92061     }
92062     sqlite3_free(zErrmsg);
92063   }
92064 }
92065 
92066 /************** End of loadext.c *********************************************/
92067 /************** Begin file pragma.c ******************************************/
92068 /*
92069 ** 2003 April 6
92070 **
92071 ** The author disclaims copyright to this source code.  In place of
92072 ** a legal notice, here is a blessing:
92073 **
92074 **    May you do good and not evil.
92075 **    May you find forgiveness for yourself and forgive others.
92076 **    May you share freely, never taking more than you give.
92077 **
92078 *************************************************************************
92079 ** This file contains code used to implement the PRAGMA command.
92080 */
92081 
92082 /*
92083 ** Interpret the given string as a safety level.  Return 0 for OFF,
92084 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
92085 ** unrecognized string argument.  The FULL option is disallowed
92086 ** if the omitFull parameter it 1.
92087 **
92088 ** Note that the values returned are one less that the values that
92089 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
92090 ** to support legacy SQL code.  The safety level used to be boolean
92091 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
92092 */
92093 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
92094                              /* 123456789 123456789 */
92095   static const char zText[] = "onoffalseyestruefull";
92096   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
92097   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
92098   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
92099   int i, n;
92100   if( sqlite3Isdigit(*z) ){
92101     return (u8)sqlite3Atoi(z);
92102   }
92103   n = sqlite3Strlen30(z);
92104   for(i=0; i<ArraySize(iLength)-omitFull; i++){
92105     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
92106       return iValue[i];
92107     }
92108   }
92109   return dflt;
92110 }
92111 
92112 /*
92113 ** Interpret the given string as a boolean value.
92114 */
92115 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
92116   return getSafetyLevel(z,1,dflt)!=0;
92117 }
92118 
92119 /* The sqlite3GetBoolean() function is used by other modules but the
92120 ** remainder of this file is specific to PRAGMA processing.  So omit
92121 ** the rest of the file if PRAGMAs are omitted from the build.
92122 */
92123 #if !defined(SQLITE_OMIT_PRAGMA)
92124 
92125 /*
92126 ** Interpret the given string as a locking mode value.
92127 */
92128 static int getLockingMode(const char *z){
92129   if( z ){
92130     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
92131     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
92132   }
92133   return PAGER_LOCKINGMODE_QUERY;
92134 }
92135 
92136 #ifndef SQLITE_OMIT_AUTOVACUUM
92137 /*
92138 ** Interpret the given string as an auto-vacuum mode value.
92139 **
92140 ** The following strings, "none", "full" and "incremental" are
92141 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
92142 */
92143 static int getAutoVacuum(const char *z){
92144   int i;
92145   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
92146   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
92147   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
92148   i = sqlite3Atoi(z);
92149   return (u8)((i>=0&&i<=2)?i:0);
92150 }
92151 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
92152 
92153 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92154 /*
92155 ** Interpret the given string as a temp db location. Return 1 for file
92156 ** backed temporary databases, 2 for the Red-Black tree in memory database
92157 ** and 0 to use the compile-time default.
92158 */
92159 static int getTempStore(const char *z){
92160   if( z[0]>='0' && z[0]<='2' ){
92161     return z[0] - '0';
92162   }else if( sqlite3StrICmp(z, "file")==0 ){
92163     return 1;
92164   }else if( sqlite3StrICmp(z, "memory")==0 ){
92165     return 2;
92166   }else{
92167     return 0;
92168   }
92169 }
92170 #endif /* SQLITE_PAGER_PRAGMAS */
92171 
92172 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92173 /*
92174 ** Invalidate temp storage, either when the temp storage is changed
92175 ** from default, or when 'file' and the temp_store_directory has changed
92176 */
92177 static int invalidateTempStorage(Parse *pParse){
92178   sqlite3 *db = pParse->db;
92179   if( db->aDb[1].pBt!=0 ){
92180     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
92181       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
92182         "from within a transaction");
92183       return SQLITE_ERROR;
92184     }
92185     sqlite3BtreeClose(db->aDb[1].pBt);
92186     db->aDb[1].pBt = 0;
92187     sqlite3ResetAllSchemasOfConnection(db);
92188   }
92189   return SQLITE_OK;
92190 }
92191 #endif /* SQLITE_PAGER_PRAGMAS */
92192 
92193 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92194 /*
92195 ** If the TEMP database is open, close it and mark the database schema
92196 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
92197 ** or DEFAULT_TEMP_STORE pragmas.
92198 */
92199 static int changeTempStorage(Parse *pParse, const char *zStorageType){
92200   int ts = getTempStore(zStorageType);
92201   sqlite3 *db = pParse->db;
92202   if( db->temp_store==ts ) return SQLITE_OK;
92203   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
92204     return SQLITE_ERROR;
92205   }
92206   db->temp_store = (u8)ts;
92207   return SQLITE_OK;
92208 }
92209 #endif /* SQLITE_PAGER_PRAGMAS */
92210 
92211 /*
92212 ** Generate code to return a single integer value.
92213 */
92214 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
92215   Vdbe *v = sqlite3GetVdbe(pParse);
92216   int mem = ++pParse->nMem;
92217   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
92218   if( pI64 ){
92219     memcpy(pI64, &value, sizeof(value));
92220   }
92221   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
92222   sqlite3VdbeSetNumCols(v, 1);
92223   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
92224   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92225 }
92226 
92227 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
92228 /*
92229 ** Check to see if zRight and zLeft refer to a pragma that queries
92230 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
92231 ** Also, implement the pragma.
92232 */
92233 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
92234   static const struct sPragmaType {
92235     const char *zName;  /* Name of the pragma */
92236     int mask;           /* Mask for the db->flags value */
92237   } aPragma[] = {
92238     { "full_column_names",        SQLITE_FullColNames  },
92239     { "short_column_names",       SQLITE_ShortColNames },
92240     { "count_changes",            SQLITE_CountRows     },
92241     { "empty_result_callbacks",   SQLITE_NullCallback  },
92242     { "legacy_file_format",       SQLITE_LegacyFileFmt },
92243     { "fullfsync",                SQLITE_FullFSync     },
92244     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
92245     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
92246 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
92247     { "automatic_index",          SQLITE_AutoIndex     },
92248 #endif
92249 #ifdef SQLITE_DEBUG
92250     { "sql_trace",                SQLITE_SqlTrace      },
92251     { "vdbe_listing",             SQLITE_VdbeListing   },
92252     { "vdbe_trace",               SQLITE_VdbeTrace     },
92253     { "vdbe_addoptrace",          SQLITE_VdbeAddopTrace},
92254     { "vdbe_debug",    SQLITE_SqlTrace | SQLITE_VdbeListing
92255                                | SQLITE_VdbeTrace      },
92256 #endif
92257 #ifndef SQLITE_OMIT_CHECK
92258     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
92259 #endif
92260     /* The following is VERY experimental */
92261     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
92262 
92263     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
92264     ** flag if there are any active statements. */
92265     { "read_uncommitted",         SQLITE_ReadUncommitted },
92266     { "recursive_triggers",       SQLITE_RecTriggers },
92267 
92268     /* This flag may only be set if both foreign-key and trigger support
92269     ** are present in the build.  */
92270 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
92271     { "foreign_keys",             SQLITE_ForeignKeys },
92272 #endif
92273   };
92274   int i;
92275   const struct sPragmaType *p;
92276   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
92277     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
92278       sqlite3 *db = pParse->db;
92279       Vdbe *v;
92280       v = sqlite3GetVdbe(pParse);
92281       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
92282       if( ALWAYS(v) ){
92283         if( zRight==0 ){
92284           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
92285         }else{
92286           int mask = p->mask;          /* Mask of bits to set or clear. */
92287           if( db->autoCommit==0 ){
92288             /* Foreign key support may not be enabled or disabled while not
92289             ** in auto-commit mode.  */
92290             mask &= ~(SQLITE_ForeignKeys);
92291           }
92292 
92293           if( sqlite3GetBoolean(zRight, 0) ){
92294             db->flags |= mask;
92295           }else{
92296             db->flags &= ~mask;
92297           }
92298 
92299           /* Many of the flag-pragmas modify the code generated by the SQL
92300           ** compiler (eg. count_changes). So add an opcode to expire all
92301           ** compiled SQL statements after modifying a pragma value.
92302           */
92303           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92304         }
92305       }
92306 
92307       return 1;
92308     }
92309   }
92310   return 0;
92311 }
92312 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92313 
92314 /*
92315 ** Return a human-readable name for a constraint resolution action.
92316 */
92317 #ifndef SQLITE_OMIT_FOREIGN_KEY
92318 static const char *actionName(u8 action){
92319   const char *zName;
92320   switch( action ){
92321     case OE_SetNull:  zName = "SET NULL";        break;
92322     case OE_SetDflt:  zName = "SET DEFAULT";     break;
92323     case OE_Cascade:  zName = "CASCADE";         break;
92324     case OE_Restrict: zName = "RESTRICT";        break;
92325     default:          zName = "NO ACTION";
92326                       assert( action==OE_None ); break;
92327   }
92328   return zName;
92329 }
92330 #endif
92331 
92332 
92333 /*
92334 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
92335 ** defined in pager.h. This function returns the associated lowercase
92336 ** journal-mode name.
92337 */
92338 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
92339   static char * const azModeName[] = {
92340     "delete", "persist", "off", "truncate", "memory"
92341 #ifndef SQLITE_OMIT_WAL
92342      , "wal"
92343 #endif
92344   };
92345   assert( PAGER_JOURNALMODE_DELETE==0 );
92346   assert( PAGER_JOURNALMODE_PERSIST==1 );
92347   assert( PAGER_JOURNALMODE_OFF==2 );
92348   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
92349   assert( PAGER_JOURNALMODE_MEMORY==4 );
92350   assert( PAGER_JOURNALMODE_WAL==5 );
92351   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92352 
92353   if( eMode==ArraySize(azModeName) ) return 0;
92354   return azModeName[eMode];
92355 }
92356 
92357 /*
92358 ** Process a pragma statement.
92359 **
92360 ** Pragmas are of this form:
92361 **
92362 **      PRAGMA [database.]id [= value]
92363 **
92364 ** The identifier might also be a string.  The value is a string, and
92365 ** identifier, or a number.  If minusFlag is true, then the value is
92366 ** a number that was preceded by a minus sign.
92367 **
92368 ** If the left side is "database.id" then pId1 is the database name
92369 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
92370 ** id and pId2 is any empty string.
92371 */
92372 SQLITE_PRIVATE void sqlite3Pragma(
92373   Parse *pParse,
92374   Token *pId1,        /* First part of [database.]id field */
92375   Token *pId2,        /* Second part of [database.]id field, or NULL */
92376   Token *pValue,      /* Token for <value>, or NULL */
92377   int minusFlag       /* True if a '-' sign preceded <value> */
92378 ){
92379   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92380   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92381   const char *zDb = 0;   /* The database name */
92382   Token *pId;            /* Pointer to <id> token */
92383   int iDb;               /* Database index for <database> */
92384   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
92385   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
92386   sqlite3 *db = pParse->db;    /* The database connection */
92387   Db *pDb;                     /* The specific database being pragmaed */
92388   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
92389 
92390   if( v==0 ) return;
92391   sqlite3VdbeRunOnlyOnce(v);
92392   pParse->nMem = 2;
92393 
92394   /* Interpret the [database.] part of the pragma statement. iDb is the
92395   ** index of the database this pragma is being applied to in db.aDb[]. */
92396   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
92397   if( iDb<0 ) return;
92398   pDb = &db->aDb[iDb];
92399 
92400   /* If the temp database has been explicitly named as part of the
92401   ** pragma, make sure it is open.
92402   */
92403   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
92404     return;
92405   }
92406 
92407   zLeft = sqlite3NameFromToken(db, pId);
92408   if( !zLeft ) return;
92409   if( minusFlag ){
92410     zRight = sqlite3MPrintf(db, "-%T", pValue);
92411   }else{
92412     zRight = sqlite3NameFromToken(db, pValue);
92413   }
92414 
92415   assert( pId2 );
92416   zDb = pId2->n>0 ? pDb->zName : 0;
92417   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
92418     goto pragma_out;
92419   }
92420 
92421   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
92422   ** connection.  If it returns SQLITE_OK, then assume that the VFS
92423   ** handled the pragma and generate a no-op prepared statement.
92424   */
92425   aFcntl[0] = 0;
92426   aFcntl[1] = zLeft;
92427   aFcntl[2] = zRight;
92428   aFcntl[3] = 0;
92429   db->busyHandler.nBusy = 0;
92430   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
92431   if( rc==SQLITE_OK ){
92432     if( aFcntl[0] ){
92433       int mem = ++pParse->nMem;
92434       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
92435       sqlite3VdbeSetNumCols(v, 1);
92436       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
92437       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92438       sqlite3_free(aFcntl[0]);
92439     }
92440   }else if( rc!=SQLITE_NOTFOUND ){
92441     if( aFcntl[0] ){
92442       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
92443       sqlite3_free(aFcntl[0]);
92444     }
92445     pParse->nErr++;
92446     pParse->rc = rc;
92447   }else
92448 
92449 
92450 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
92451   /*
92452   **  PRAGMA [database.]default_cache_size
92453   **  PRAGMA [database.]default_cache_size=N
92454   **
92455   ** The first form reports the current persistent setting for the
92456   ** page cache size.  The value returned is the maximum number of
92457   ** pages in the page cache.  The second form sets both the current
92458   ** page cache size value and the persistent page cache size value
92459   ** stored in the database file.
92460   **
92461   ** Older versions of SQLite would set the default cache size to a
92462   ** negative number to indicate synchronous=OFF.  These days, synchronous
92463   ** is always on by default regardless of the sign of the default cache
92464   ** size.  But continue to take the absolute value of the default cache
92465   ** size of historical compatibility.
92466   */
92467   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
92468     static const VdbeOpList getCacheSize[] = {
92469       { OP_Transaction, 0, 0,        0},                         /* 0 */
92470       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92471       { OP_IfPos,       1, 7,        0},
92472       { OP_Integer,     0, 2,        0},
92473       { OP_Subtract,    1, 2,        1},
92474       { OP_IfPos,       1, 7,        0},
92475       { OP_Integer,     0, 1,        0},                         /* 6 */
92476       { OP_ResultRow,   1, 1,        0},
92477     };
92478     int addr;
92479     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92480     sqlite3VdbeUsesBtree(v, iDb);
92481     if( !zRight ){
92482       sqlite3VdbeSetNumCols(v, 1);
92483       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
92484       pParse->nMem += 2;
92485       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92486       sqlite3VdbeChangeP1(v, addr, iDb);
92487       sqlite3VdbeChangeP1(v, addr+1, iDb);
92488       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
92489     }else{
92490       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
92491       sqlite3BeginWriteOperation(pParse, 0, iDb);
92492       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
92493       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92494       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92495       pDb->pSchema->cache_size = size;
92496       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92497     }
92498   }else
92499 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
92500 
92501 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
92502   /*
92503   **  PRAGMA [database.]page_size
92504   **  PRAGMA [database.]page_size=N
92505   **
92506   ** The first form reports the current setting for the
92507   ** database page size in bytes.  The second form sets the
92508   ** database page size value.  The value can only be set if
92509   ** the database has not yet been created.
92510   */
92511   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
92512     Btree *pBt = pDb->pBt;
92513     assert( pBt!=0 );
92514     if( !zRight ){
92515       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
92516       returnSingleInt(pParse, "page_size", size);
92517     }else{
92518       /* Malloc may fail when setting the page-size, as there is an internal
92519       ** buffer that the pager module resizes using sqlite3_realloc().
92520       */
92521       db->nextPagesize = sqlite3Atoi(zRight);
92522       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
92523         db->mallocFailed = 1;
92524       }
92525     }
92526   }else
92527 
92528   /*
92529   **  PRAGMA [database.]secure_delete
92530   **  PRAGMA [database.]secure_delete=ON/OFF
92531   **
92532   ** The first form reports the current setting for the
92533   ** secure_delete flag.  The second form changes the secure_delete
92534   ** flag setting and reports thenew value.
92535   */
92536   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
92537     Btree *pBt = pDb->pBt;
92538     int b = -1;
92539     assert( pBt!=0 );
92540     if( zRight ){
92541       b = sqlite3GetBoolean(zRight, 0);
92542     }
92543     if( pId2->n==0 && b>=0 ){
92544       int ii;
92545       for(ii=0; ii<db->nDb; ii++){
92546         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
92547       }
92548     }
92549     b = sqlite3BtreeSecureDelete(pBt, b);
92550     returnSingleInt(pParse, "secure_delete", b);
92551   }else
92552 
92553   /*
92554   **  PRAGMA [database.]max_page_count
92555   **  PRAGMA [database.]max_page_count=N
92556   **
92557   ** The first form reports the current setting for the
92558   ** maximum number of pages in the database file.  The
92559   ** second form attempts to change this setting.  Both
92560   ** forms return the current setting.
92561   **
92562   ** The absolute value of N is used.  This is undocumented and might
92563   ** change.  The only purpose is to provide an easy way to test
92564   ** the sqlite3AbsInt32() function.
92565   **
92566   **  PRAGMA [database.]page_count
92567   **
92568   ** Return the number of pages in the specified database.
92569   */
92570   if( sqlite3StrICmp(zLeft,"page_count")==0
92571    || sqlite3StrICmp(zLeft,"max_page_count")==0
92572   ){
92573     int iReg;
92574     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92575     sqlite3CodeVerifySchema(pParse, iDb);
92576     iReg = ++pParse->nMem;
92577     if( sqlite3Tolower(zLeft[0])=='p' ){
92578       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92579     }else{
92580       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
92581                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
92582     }
92583     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92584     sqlite3VdbeSetNumCols(v, 1);
92585     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
92586   }else
92587 
92588   /*
92589   **  PRAGMA [database.]locking_mode
92590   **  PRAGMA [database.]locking_mode = (normal|exclusive)
92591   */
92592   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
92593     const char *zRet = "normal";
92594     int eMode = getLockingMode(zRight);
92595 
92596     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92597       /* Simple "PRAGMA locking_mode;" statement. This is a query for
92598       ** the current default locking mode (which may be different to
92599       ** the locking-mode of the main database).
92600       */
92601       eMode = db->dfltLockMode;
92602     }else{
92603       Pager *pPager;
92604       if( pId2->n==0 ){
92605         /* This indicates that no database name was specified as part
92606         ** of the PRAGMA command. In this case the locking-mode must be
92607         ** set on all attached databases, as well as the main db file.
92608         **
92609         ** Also, the sqlite3.dfltLockMode variable is set so that
92610         ** any subsequently attached databases also use the specified
92611         ** locking mode.
92612         */
92613         int ii;
92614         assert(pDb==&db->aDb[0]);
92615         for(ii=2; ii<db->nDb; ii++){
92616           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
92617           sqlite3PagerLockingMode(pPager, eMode);
92618         }
92619         db->dfltLockMode = (u8)eMode;
92620       }
92621       pPager = sqlite3BtreePager(pDb->pBt);
92622       eMode = sqlite3PagerLockingMode(pPager, eMode);
92623     }
92624 
92625     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92626     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92627       zRet = "exclusive";
92628     }
92629     sqlite3VdbeSetNumCols(v, 1);
92630     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
92631     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92632     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92633   }else
92634 
92635   /*
92636   **  PRAGMA [database.]journal_mode
92637   **  PRAGMA [database.]journal_mode =
92638   **                      (delete|persist|off|truncate|memory|wal|off)
92639   */
92640   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
92641     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92642     int ii;           /* Loop counter */
92643 
92644     /* Force the schema to be loaded on all databases.  This causes all
92645     ** database files to be opened and the journal_modes set.  This is
92646     ** necessary because subsequent processing must know if the databases
92647     ** are in WAL mode. */
92648     if( sqlite3ReadSchema(pParse) ){
92649       goto pragma_out;
92650     }
92651 
92652     sqlite3VdbeSetNumCols(v, 1);
92653     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
92654 
92655     if( zRight==0 ){
92656       /* If there is no "=MODE" part of the pragma, do a query for the
92657       ** current mode */
92658       eMode = PAGER_JOURNALMODE_QUERY;
92659     }else{
92660       const char *zMode;
92661       int n = sqlite3Strlen30(zRight);
92662       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
92663         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
92664       }
92665       if( !zMode ){
92666         /* If the "=MODE" part does not match any known journal mode,
92667         ** then do a query */
92668         eMode = PAGER_JOURNALMODE_QUERY;
92669       }
92670     }
92671     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92672       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92673       iDb = 0;
92674       pId2->n = 1;
92675     }
92676     for(ii=db->nDb-1; ii>=0; ii--){
92677       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92678         sqlite3VdbeUsesBtree(v, ii);
92679         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92680       }
92681     }
92682     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92683   }else
92684 
92685   /*
92686   **  PRAGMA [database.]journal_size_limit
92687   **  PRAGMA [database.]journal_size_limit=N
92688   **
92689   ** Get or set the size limit on rollback journal files.
92690   */
92691   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
92692     Pager *pPager = sqlite3BtreePager(pDb->pBt);
92693     i64 iLimit = -2;
92694     if( zRight ){
92695       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
92696       if( iLimit<-1 ) iLimit = -1;
92697     }
92698     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
92699     returnSingleInt(pParse, "journal_size_limit", iLimit);
92700   }else
92701 
92702 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92703 
92704   /*
92705   **  PRAGMA [database.]auto_vacuum
92706   **  PRAGMA [database.]auto_vacuum=N
92707   **
92708   ** Get or set the value of the database 'auto-vacuum' parameter.
92709   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92710   */
92711 #ifndef SQLITE_OMIT_AUTOVACUUM
92712   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
92713     Btree *pBt = pDb->pBt;
92714     assert( pBt!=0 );
92715     if( sqlite3ReadSchema(pParse) ){
92716       goto pragma_out;
92717     }
92718     if( !zRight ){
92719       int auto_vacuum;
92720       if( ALWAYS(pBt) ){
92721          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
92722       }else{
92723          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
92724       }
92725       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92726     }else{
92727       int eAuto = getAutoVacuum(zRight);
92728       assert( eAuto>=0 && eAuto<=2 );
92729       db->nextAutovac = (u8)eAuto;
92730       if( ALWAYS(eAuto>=0) ){
92731         /* Call SetAutoVacuum() to set initialize the internal auto and
92732         ** incr-vacuum flags. This is required in case this connection
92733         ** creates the database file. It is important that it is created
92734         ** as an auto-vacuum capable db.
92735         */
92736         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
92737         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
92738           /* When setting the auto_vacuum mode to either "full" or
92739           ** "incremental", write the value of meta[6] in the database
92740           ** file. Before writing to meta[6], check that meta[3] indicates
92741           ** that this really is an auto-vacuum capable database.
92742           */
92743           static const VdbeOpList setMeta6[] = {
92744             { OP_Transaction,    0,         1,                 0},    /* 0 */
92745             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92746             { OP_If,             1,         0,                 0},    /* 2 */
92747             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
92748             { OP_Integer,        0,         1,                 0},    /* 4 */
92749             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92750           };
92751           int iAddr;
92752           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92753           sqlite3VdbeChangeP1(v, iAddr, iDb);
92754           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
92755           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
92756           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
92757           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
92758           sqlite3VdbeUsesBtree(v, iDb);
92759         }
92760       }
92761     }
92762   }else
92763 #endif
92764 
92765   /*
92766   **  PRAGMA [database.]incremental_vacuum(N)
92767   **
92768   ** Do N steps of incremental vacuuming on a database.
92769   */
92770 #ifndef SQLITE_OMIT_AUTOVACUUM
92771   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
92772     int iLimit, addr;
92773     if( sqlite3ReadSchema(pParse) ){
92774       goto pragma_out;
92775     }
92776     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92777       iLimit = 0x7fffffff;
92778     }
92779     sqlite3BeginWriteOperation(pParse, 0, iDb);
92780     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92781     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92782     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
92783     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
92784     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
92785     sqlite3VdbeJumpHere(v, addr);
92786   }else
92787 #endif
92788 
92789 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
92790   /*
92791   **  PRAGMA [database.]cache_size
92792   **  PRAGMA [database.]cache_size=N
92793   **
92794   ** The first form reports the current local setting for the
92795   ** page cache size. The second form sets the local
92796   ** page cache size value.  If N is positive then that is the
92797   ** number of pages in the cache.  If N is negative, then the
92798   ** number of pages is adjusted so that the cache uses -N kibibytes
92799   ** of memory.
92800   */
92801   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
92802     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92803     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92804     if( !zRight ){
92805       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92806     }else{
92807       int size = sqlite3Atoi(zRight);
92808       pDb->pSchema->cache_size = size;
92809       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92810     }
92811   }else
92812 
92813   /*
92814   **   PRAGMA temp_store
92815   **   PRAGMA temp_store = "default"|"memory"|"file"
92816   **
92817   ** Return or set the local value of the temp_store flag.  Changing
92818   ** the local value does not make changes to the disk file and the default
92819   ** value will be restored the next time the database is opened.
92820   **
92821   ** Note that it is possible for the library compile-time options to
92822   ** override this setting
92823   */
92824   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
92825     if( !zRight ){
92826       returnSingleInt(pParse, "temp_store", db->temp_store);
92827     }else{
92828       changeTempStorage(pParse, zRight);
92829     }
92830   }else
92831 
92832   /*
92833   **   PRAGMA temp_store_directory
92834   **   PRAGMA temp_store_directory = ""|"directory_name"
92835   **
92836   ** Return or set the local value of the temp_store_directory flag.  Changing
92837   ** the value sets a specific directory to be used for temporary files.
92838   ** Setting to a null string reverts to the default temporary directory search.
92839   ** If temporary directory is changed, then invalidateTempStorage.
92840   **
92841   */
92842   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
92843     if( !zRight ){
92844       if( sqlite3_temp_directory ){
92845         sqlite3VdbeSetNumCols(v, 1);
92846         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92847             "temp_store_directory", SQLITE_STATIC);
92848         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
92849         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92850       }
92851     }else{
92852 #ifndef SQLITE_OMIT_WSD
92853       if( zRight[0] ){
92854         int res;
92855         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92856         if( rc!=SQLITE_OK || res==0 ){
92857           sqlite3ErrorMsg(pParse, "not a writable directory");
92858           goto pragma_out;
92859         }
92860       }
92861       if( SQLITE_TEMP_STORE==0
92862        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
92863        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
92864       ){
92865         invalidateTempStorage(pParse);
92866       }
92867       sqlite3_free(sqlite3_temp_directory);
92868       if( zRight[0] ){
92869         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
92870       }else{
92871         sqlite3_temp_directory = 0;
92872       }
92873 #endif /* SQLITE_OMIT_WSD */
92874     }
92875   }else
92876 
92877 #if SQLITE_OS_WIN
92878   /*
92879   **   PRAGMA data_store_directory
92880   **   PRAGMA data_store_directory = ""|"directory_name"
92881   **
92882   ** Return or set the local value of the data_store_directory flag.  Changing
92883   ** the value sets a specific directory to be used for database files that
92884   ** were specified with a relative pathname.  Setting to a null string reverts
92885   ** to the default database directory, which for database files specified with
92886   ** a relative path will probably be based on the current directory for the
92887   ** process.  Database file specified with an absolute path are not impacted
92888   ** by this setting, regardless of its value.
92889   **
92890   */
92891   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
92892     if( !zRight ){
92893       if( sqlite3_data_directory ){
92894         sqlite3VdbeSetNumCols(v, 1);
92895         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92896             "data_store_directory", SQLITE_STATIC);
92897         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
92898         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92899       }
92900     }else{
92901 #ifndef SQLITE_OMIT_WSD
92902       if( zRight[0] ){
92903         int res;
92904         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92905         if( rc!=SQLITE_OK || res==0 ){
92906           sqlite3ErrorMsg(pParse, "not a writable directory");
92907           goto pragma_out;
92908         }
92909       }
92910       sqlite3_free(sqlite3_data_directory);
92911       if( zRight[0] ){
92912         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
92913       }else{
92914         sqlite3_data_directory = 0;
92915       }
92916 #endif /* SQLITE_OMIT_WSD */
92917     }
92918   }else
92919 #endif
92920 
92921 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
92922 #  if defined(__APPLE__)
92923 #    define SQLITE_ENABLE_LOCKING_STYLE 1
92924 #  else
92925 #    define SQLITE_ENABLE_LOCKING_STYLE 0
92926 #  endif
92927 #endif
92928 #if SQLITE_ENABLE_LOCKING_STYLE
92929   /*
92930    **   PRAGMA [database.]lock_proxy_file
92931    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92932    **
92933    ** Return or set the value of the lock_proxy_file flag.  Changing
92934    ** the value sets a specific file to be used for database access locks.
92935    **
92936    */
92937   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
92938     if( !zRight ){
92939       Pager *pPager = sqlite3BtreePager(pDb->pBt);
92940       char *proxy_file_path = NULL;
92941       sqlite3_file *pFile = sqlite3PagerFile(pPager);
92942       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
92943                            &proxy_file_path);
92944 
92945       if( proxy_file_path ){
92946         sqlite3VdbeSetNumCols(v, 1);
92947         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92948                               "lock_proxy_file", SQLITE_STATIC);
92949         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92950         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92951       }
92952     }else{
92953       Pager *pPager = sqlite3BtreePager(pDb->pBt);
92954       sqlite3_file *pFile = sqlite3PagerFile(pPager);
92955       int res;
92956       if( zRight[0] ){
92957         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
92958                                      zRight);
92959       } else {
92960         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
92961                                      NULL);
92962       }
92963       if( res!=SQLITE_OK ){
92964         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
92965         goto pragma_out;
92966       }
92967     }
92968   }else
92969 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
92970 
92971   /*
92972   **   PRAGMA [database.]synchronous
92973   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92974   **
92975   ** Return or set the local value of the synchronous flag.  Changing
92976   ** the local value does not make changes to the disk file and the
92977   ** default value will be restored the next time the database is
92978   ** opened.
92979   */
92980   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
92981     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92982     if( !zRight ){
92983       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92984     }else{
92985       if( !db->autoCommit ){
92986         sqlite3ErrorMsg(pParse,
92987             "Safety level may not be changed inside a transaction");
92988       }else{
92989         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
92990       }
92991     }
92992   }else
92993 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92994 
92995 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
92996   if( flagPragma(pParse, zLeft, zRight) ){
92997     /* The flagPragma() subroutine also generates any necessary code
92998     ** there is nothing more to do here */
92999   }else
93000 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
93001 
93002 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
93003   /*
93004   **   PRAGMA table_info(<table>)
93005   **
93006   ** Return a single row for each column of the named table. The columns of
93007   ** the returned data set are:
93008   **
93009   ** cid:        Column id (numbered from left to right, starting at 0)
93010   ** name:       Column name
93011   ** type:       Column declaration type.
93012   ** notnull:    True if 'NOT NULL' is part of column declaration
93013   ** dflt_value: The default value for the column, if any.
93014   */
93015   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
93016     Table *pTab;
93017     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93018     pTab = sqlite3FindTable(db, zRight, zDb);
93019     if( pTab ){
93020       int i, k;
93021       int nHidden = 0;
93022       Column *pCol;
93023       Index *pPk;
93024       for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
93025       sqlite3VdbeSetNumCols(v, 6);
93026       pParse->nMem = 6;
93027       sqlite3CodeVerifySchema(pParse, iDb);
93028       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
93029       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93030       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
93031       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
93032       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
93033       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
93034       sqlite3ViewGetColumnNames(pParse, pTab);
93035       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
93036         if( IsHiddenColumn(pCol) ){
93037           nHidden++;
93038           continue;
93039         }
93040         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
93041         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
93042         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93043            pCol->zType ? pCol->zType : "", 0);
93044         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
93045         if( pCol->zDflt ){
93046           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
93047         }else{
93048           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
93049         }
93050         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
93051           k = 0;
93052         }else if( pPk==0 ){
93053           k = 1;
93054         }else{
93055           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
93056         }
93057         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
93058         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
93059       }
93060     }
93061   }else
93062 
93063   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
93064     Index *pIdx;
93065     Table *pTab;
93066     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93067     pIdx = sqlite3FindIndex(db, zRight, zDb);
93068     if( pIdx ){
93069       int i;
93070       pTab = pIdx->pTable;
93071       sqlite3VdbeSetNumCols(v, 3);
93072       pParse->nMem = 3;
93073       sqlite3CodeVerifySchema(pParse, iDb);
93074       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
93075       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
93076       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
93077       for(i=0; i<pIdx->nColumn; i++){
93078         int cnum = pIdx->aiColumn[i];
93079         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93080         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
93081         assert( pTab->nCol>cnum );
93082         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
93083         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93084       }
93085     }
93086   }else
93087 
93088   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
93089     Index *pIdx;
93090     Table *pTab;
93091     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93092     pTab = sqlite3FindTable(db, zRight, zDb);
93093     if( pTab ){
93094       v = sqlite3GetVdbe(pParse);
93095       pIdx = pTab->pIndex;
93096       if( pIdx ){
93097         int i = 0;
93098         sqlite3VdbeSetNumCols(v, 3);
93099         pParse->nMem = 3;
93100         sqlite3CodeVerifySchema(pParse, iDb);
93101         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93102         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93103         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
93104         while(pIdx){
93105           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93106           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
93107           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
93108           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93109           ++i;
93110           pIdx = pIdx->pNext;
93111         }
93112       }
93113     }
93114   }else
93115 
93116   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
93117     int i;
93118     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93119     sqlite3VdbeSetNumCols(v, 3);
93120     pParse->nMem = 3;
93121     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93122     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93123     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
93124     for(i=0; i<db->nDb; i++){
93125       if( db->aDb[i].pBt==0 ) continue;
93126       assert( db->aDb[i].zName!=0 );
93127       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93128       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
93129       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93130            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
93131       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93132     }
93133   }else
93134 
93135   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
93136     int i = 0;
93137     HashElem *p;
93138     sqlite3VdbeSetNumCols(v, 2);
93139     pParse->nMem = 2;
93140     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93141     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93142     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
93143       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
93144       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
93145       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
93146       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93147     }
93148   }else
93149 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
93150 
93151 #ifndef SQLITE_OMIT_FOREIGN_KEY
93152   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
93153     FKey *pFK;
93154     Table *pTab;
93155     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93156     pTab = sqlite3FindTable(db, zRight, zDb);
93157     if( pTab ){
93158       v = sqlite3GetVdbe(pParse);
93159       pFK = pTab->pFKey;
93160       if( pFK ){
93161         int i = 0;
93162         sqlite3VdbeSetNumCols(v, 8);
93163         pParse->nMem = 8;
93164         sqlite3CodeVerifySchema(pParse, iDb);
93165         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
93166         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
93167         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
93168         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
93169         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
93170         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
93171         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
93172         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
93173         while(pFK){
93174           int j;
93175           for(j=0; j<pFK->nCol; j++){
93176             char *zCol = pFK->aCol[j].zCol;
93177             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
93178             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
93179             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93180             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
93181             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
93182             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
93183                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
93184             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
93185             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
93186             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
93187             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
93188             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
93189           }
93190           ++i;
93191           pFK = pFK->pNextFrom;
93192         }
93193       }
93194     }
93195   }else
93196 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93197 
93198 #ifndef SQLITE_OMIT_FOREIGN_KEY
93199 #ifndef SQLITE_OMIT_TRIGGER
93200   if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
93201     FKey *pFK;             /* A foreign key constraint */
93202     Table *pTab;           /* Child table contain "REFERENCES" keyword */
93203     Table *pParent;        /* Parent table that child points to */
93204     Index *pIdx;           /* Index in the parent table */
93205     int i;                 /* Loop counter:  Foreign key number for pTab */
93206     int j;                 /* Loop counter:  Field of the foreign key */
93207     HashElem *k;           /* Loop counter:  Next table in schema */
93208     int x;                 /* result variable */
93209     int regResult;         /* 3 registers to hold a result row */
93210     int regKey;            /* Register to hold key for checking the FK */
93211     int regRow;            /* Registers to hold a row from pTab */
93212     int addrTop;           /* Top of a loop checking foreign keys */
93213     int addrOk;            /* Jump here if the key is OK */
93214     int *aiCols;           /* child to parent column mapping */
93215 
93216     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93217     regResult = pParse->nMem+1;
93218     pParse->nMem += 4;
93219     regKey = ++pParse->nMem;
93220     regRow = ++pParse->nMem;
93221     v = sqlite3GetVdbe(pParse);
93222     sqlite3VdbeSetNumCols(v, 4);
93223     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
93224     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
93225     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
93226     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
93227     sqlite3CodeVerifySchema(pParse, iDb);
93228     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
93229     while( k ){
93230       if( zRight ){
93231         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
93232         k = 0;
93233       }else{
93234         pTab = (Table*)sqliteHashData(k);
93235         k = sqliteHashNext(k);
93236       }
93237       if( pTab==0 || pTab->pFKey==0 ) continue;
93238       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
93239       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
93240       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
93241       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
93242                         P4_TRANSIENT);
93243       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
93244         pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
93245         if( pParent==0 ) break;
93246         pIdx = 0;
93247         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
93248         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
93249         if( x==0 ){
93250           if( pIdx==0 ){
93251             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
93252           }else{
93253             KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
93254             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
93255             sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
93256           }
93257         }else{
93258           k = 0;
93259           break;
93260         }
93261       }
93262       if( pFK ) break;
93263       if( pParse->nTab<i ) pParse->nTab = i;
93264       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
93265       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
93266         pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
93267         assert( pParent!=0 );
93268         pIdx = 0;
93269         aiCols = 0;
93270         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
93271         assert( x==0 );
93272         addrOk = sqlite3VdbeMakeLabel(v);
93273         if( pIdx==0 ){
93274           int iKey = pFK->aCol[0].iFrom;
93275           assert( iKey>=0 && iKey<pTab->nCol );
93276           if( iKey!=pTab->iPKey ){
93277             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
93278             sqlite3ColumnDefault(v, pTab, iKey, regRow);
93279             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
93280             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
93281                sqlite3VdbeCurrentAddr(v)+3);
93282           }else{
93283             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
93284           }
93285           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
93286           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
93287           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
93288         }else{
93289           for(j=0; j<pFK->nCol; j++){
93290             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
93291                             aiCols ? aiCols[j] : pFK->aCol[0].iFrom, regRow+j);
93292             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
93293           }
93294           sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
93295           sqlite3VdbeChangeP4(v, -1,
93296                    sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
93297           sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
93298         }
93299         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
93300         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
93301                           pFK->zTo, P4_TRANSIENT);
93302         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
93303         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
93304         sqlite3VdbeResolveLabel(v, addrOk);
93305         sqlite3DbFree(db, aiCols);
93306       }
93307       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
93308       sqlite3VdbeJumpHere(v, addrTop);
93309     }
93310   }else
93311 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
93312 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93313 
93314 #ifndef NDEBUG
93315   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
93316     if( zRight ){
93317       if( sqlite3GetBoolean(zRight, 0) ){
93318         sqlite3ParserTrace(stderr, "parser: ");
93319       }else{
93320         sqlite3ParserTrace(0, 0);
93321       }
93322     }
93323   }else
93324 #endif
93325 
93326   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
93327   ** used will be case sensitive or not depending on the RHS.
93328   */
93329   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
93330     if( zRight ){
93331       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
93332     }
93333   }else
93334 
93335 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
93336 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
93337 #endif
93338 
93339 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
93340   /* Pragma "quick_check" is an experimental reduced version of
93341   ** integrity_check designed to detect most database corruption
93342   ** without most of the overhead of a full integrity-check.
93343   */
93344   if( sqlite3StrICmp(zLeft, "integrity_check")==0
93345    || sqlite3StrICmp(zLeft, "quick_check")==0
93346   ){
93347     int i, j, addr, mxErr;
93348 
93349     /* Code that appears at the end of the integrity check.  If no error
93350     ** messages have been generated, output OK.  Otherwise output the
93351     ** error message
93352     */
93353     static const VdbeOpList endCode[] = {
93354       { OP_AddImm,      1, 0,        0},    /* 0 */
93355       { OP_IfNeg,       1, 0,        0},    /* 1 */
93356       { OP_String8,     0, 3,        0},    /* 2 */
93357       { OP_ResultRow,   3, 1,        0},
93358     };
93359 
93360     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
93361 
93362     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
93363     ** then iDb is set to the index of the database identified by <db>.
93364     ** In this case, the integrity of database iDb only is verified by
93365     ** the VDBE created below.
93366     **
93367     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
93368     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
93369     ** to -1 here, to indicate that the VDBE should verify the integrity
93370     ** of all attached databases.  */
93371     assert( iDb>=0 );
93372     assert( iDb==0 || pId2->z );
93373     if( pId2->z==0 ) iDb = -1;
93374 
93375     /* Initialize the VDBE program */
93376     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93377     pParse->nMem = 6;
93378     sqlite3VdbeSetNumCols(v, 1);
93379     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
93380 
93381     /* Set the maximum error count */
93382     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93383     if( zRight ){
93384       sqlite3GetInt32(zRight, &mxErr);
93385       if( mxErr<=0 ){
93386         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93387       }
93388     }
93389     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
93390 
93391     /* Do an integrity check on each database file */
93392     for(i=0; i<db->nDb; i++){
93393       HashElem *x;
93394       Hash *pTbls;
93395       int cnt = 0;
93396 
93397       if( OMIT_TEMPDB && i==1 ) continue;
93398       if( iDb>=0 && i!=iDb ) continue;
93399 
93400       sqlite3CodeVerifySchema(pParse, i);
93401       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
93402       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93403       sqlite3VdbeJumpHere(v, addr);
93404 
93405       /* Do an integrity check of the B-Tree
93406       **
93407       ** Begin by filling registers 2, 3, ... with the root pages numbers
93408       ** for all tables and indices in the database.
93409       */
93410       assert( sqlite3SchemaMutexHeld(db, i, 0) );
93411       pTbls = &db->aDb[i].pSchema->tblHash;
93412       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
93413         Table *pTab = sqliteHashData(x);
93414         Index *pIdx;
93415         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
93416         cnt++;
93417         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93418           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
93419           cnt++;
93420         }
93421       }
93422 
93423       /* Make sure sufficient number of registers have been allocated */
93424       if( pParse->nMem < cnt+4 ){
93425         pParse->nMem = cnt+4;
93426       }
93427 
93428       /* Do the b-tree integrity checks */
93429       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
93430       sqlite3VdbeChangeP5(v, (u8)i);
93431       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
93432       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93433          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
93434          P4_DYNAMIC);
93435       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
93436       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
93437       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
93438       sqlite3VdbeJumpHere(v, addr);
93439 
93440       /* Make sure all the indices are constructed correctly.
93441       */
93442       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
93443         Table *pTab = sqliteHashData(x);
93444         Index *pIdx;
93445         int loopTop;
93446 
93447         if( pTab->pIndex==0 ) continue;
93448         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
93449         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93450         sqlite3VdbeJumpHere(v, addr);
93451         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
93452         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
93453         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
93454         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
93455         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93456           int jmp2;
93457           int r1;
93458           static const VdbeOpList idxErr[] = {
93459             { OP_AddImm,      1, -1,  0},
93460             { OP_String8,     0,  3,  0},    /* 1 */
93461             { OP_Rowid,       1,  4,  0},
93462             { OP_String8,     0,  5,  0},    /* 3 */
93463             { OP_String8,     0,  6,  0},    /* 4 */
93464             { OP_Concat,      4,  3,  3},
93465             { OP_Concat,      5,  3,  3},
93466             { OP_Concat,      6,  3,  3},
93467             { OP_ResultRow,   3,  1,  0},
93468             { OP_IfPos,       1,  0,  0},    /* 9 */
93469             { OP_Halt,        0,  0,  0},
93470           };
93471           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
93472           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
93473           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
93474           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
93475           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
93476           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
93477           sqlite3VdbeJumpHere(v, addr+9);
93478           sqlite3VdbeJumpHere(v, jmp2);
93479         }
93480         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
93481         sqlite3VdbeJumpHere(v, loopTop);
93482         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93483           static const VdbeOpList cntIdx[] = {
93484              { OP_Integer,      0,  3,  0},
93485              { OP_Rewind,       0,  0,  0},  /* 1 */
93486              { OP_AddImm,       3,  1,  0},
93487              { OP_Next,         0,  0,  0},  /* 3 */
93488              { OP_Eq,           2,  0,  3},  /* 4 */
93489              { OP_AddImm,       1, -1,  0},
93490              { OP_String8,      0,  2,  0},  /* 6 */
93491              { OP_String8,      0,  3,  0},  /* 7 */
93492              { OP_Concat,       3,  2,  2},
93493              { OP_ResultRow,    2,  1,  0},
93494           };
93495           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
93496           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93497           sqlite3VdbeJumpHere(v, addr);
93498           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
93499           sqlite3VdbeChangeP1(v, addr+1, j+2);
93500           sqlite3VdbeChangeP2(v, addr+1, addr+4);
93501           sqlite3VdbeChangeP1(v, addr+3, j+2);
93502           sqlite3VdbeChangeP2(v, addr+3, addr+2);
93503           sqlite3VdbeJumpHere(v, addr+4);
93504           sqlite3VdbeChangeP4(v, addr+6,
93505                      "wrong # of entries in index ", P4_STATIC);
93506           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
93507         }
93508       }
93509     }
93510     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
93511     sqlite3VdbeChangeP2(v, addr, -mxErr);
93512     sqlite3VdbeJumpHere(v, addr+1);
93513     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
93514   }else
93515 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
93516 
93517 #ifndef SQLITE_OMIT_UTF16
93518   /*
93519   **   PRAGMA encoding
93520   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
93521   **
93522   ** In its first form, this pragma returns the encoding of the main
93523   ** database. If the database is not initialized, it is initialized now.
93524   **
93525   ** The second form of this pragma is a no-op if the main database file
93526   ** has not already been initialized. In this case it sets the default
93527   ** encoding that will be used for the main database file if a new file
93528   ** is created. If an existing main database file is opened, then the
93529   ** default text encoding for the existing database is used.
93530   **
93531   ** In all cases new databases created using the ATTACH command are
93532   ** created to use the same default text encoding as the main database. If
93533   ** the main database has not been initialized and/or created when ATTACH
93534   ** is executed, this is done before the ATTACH operation.
93535   **
93536   ** In the second form this pragma sets the text encoding to be used in
93537   ** new database files created using this database handle. It is only
93538   ** useful if invoked immediately after the main database i
93539   */
93540   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
93541     static const struct EncName {
93542       char *zName;
93543       u8 enc;
93544     } encnames[] = {
93545       { "UTF8",     SQLITE_UTF8        },
93546       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
93547       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
93548       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
93549       { "UTF16le",  SQLITE_UTF16LE     },
93550       { "UTF16be",  SQLITE_UTF16BE     },
93551       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
93552       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
93553       { 0, 0 }
93554     };
93555     const struct EncName *pEnc;
93556     if( !zRight ){    /* "PRAGMA encoding" */
93557       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93558       sqlite3VdbeSetNumCols(v, 1);
93559       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
93560       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
93561       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
93562       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
93563       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
93564       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
93565       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93566     }else{                        /* "PRAGMA encoding = XXX" */
93567       /* Only change the value of sqlite.enc if the database handle is not
93568       ** initialized. If the main database exists, the new sqlite.enc value
93569       ** will be overwritten when the schema is next loaded. If it does not
93570       ** already exists, it will be created to use the new encoding value.
93571       */
93572       if(
93573         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
93574         DbHasProperty(db, 0, DB_Empty)
93575       ){
93576         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93577           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
93578             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
93579             break;
93580           }
93581         }
93582         if( !pEnc->zName ){
93583           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93584         }
93585       }
93586     }
93587   }else
93588 #endif /* SQLITE_OMIT_UTF16 */
93589 
93590 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
93591   /*
93592   **   PRAGMA [database.]schema_version
93593   **   PRAGMA [database.]schema_version = <integer>
93594   **
93595   **   PRAGMA [database.]user_version
93596   **   PRAGMA [database.]user_version = <integer>
93597   **
93598   ** The pragma's schema_version and user_version are used to set or get
93599   ** the value of the schema-version and user-version, respectively. Both
93600   ** the schema-version and the user-version are 32-bit signed integers
93601   ** stored in the database header.
93602   **
93603   ** The schema-cookie is usually only manipulated internally by SQLite. It
93604   ** is incremented by SQLite whenever the database schema is modified (by
93605   ** creating or dropping a table or index). The schema version is used by
93606   ** SQLite each time a query is executed to ensure that the internal cache
93607   ** of the schema used when compiling the SQL query matches the schema of
93608   ** the database against which the compiled query is actually executed.
93609   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93610   ** the schema-version is potentially dangerous and may lead to program
93611   ** crashes or database corruption. Use with caution!
93612   **
93613   ** The user-version is not used internally by SQLite. It may be used by
93614   ** applications for any purpose.
93615   */
93616   if( sqlite3StrICmp(zLeft, "schema_version")==0
93617    || sqlite3StrICmp(zLeft, "user_version")==0
93618    || sqlite3StrICmp(zLeft, "freelist_count")==0
93619   ){
93620     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93621     sqlite3VdbeUsesBtree(v, iDb);
93622     switch( zLeft[0] ){
93623       case 'f': case 'F':
93624         iCookie = BTREE_FREE_PAGE_COUNT;
93625         break;
93626       case 's': case 'S':
93627         iCookie = BTREE_SCHEMA_VERSION;
93628         break;
93629       default:
93630         iCookie = BTREE_USER_VERSION;
93631         break;
93632     }
93633 
93634     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93635       /* Write the specified cookie value */
93636       static const VdbeOpList setCookie[] = {
93637         { OP_Transaction,    0,  1,  0},    /* 0 */
93638         { OP_Integer,        0,  1,  0},    /* 1 */
93639         { OP_SetCookie,      0,  0,  1},    /* 2 */
93640       };
93641       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93642       sqlite3VdbeChangeP1(v, addr, iDb);
93643       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
93644       sqlite3VdbeChangeP1(v, addr+2, iDb);
93645       sqlite3VdbeChangeP2(v, addr+2, iCookie);
93646     }else{
93647       /* Read the specified cookie value */
93648       static const VdbeOpList readCookie[] = {
93649         { OP_Transaction,     0,  0,  0},    /* 0 */
93650         { OP_ReadCookie,      0,  1,  0},    /* 1 */
93651         { OP_ResultRow,       1,  1,  0}
93652       };
93653       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93654       sqlite3VdbeChangeP1(v, addr, iDb);
93655       sqlite3VdbeChangeP1(v, addr+1, iDb);
93656       sqlite3VdbeChangeP3(v, addr+1, iCookie);
93657       sqlite3VdbeSetNumCols(v, 1);
93658       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93659     }
93660   }else
93661 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
93662 
93663 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93664   /*
93665   **   PRAGMA compile_options
93666   **
93667   ** Return the names of all compile-time options used in this build,
93668   ** one option per row.
93669   */
93670   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
93671     int i = 0;
93672     const char *zOpt;
93673     sqlite3VdbeSetNumCols(v, 1);
93674     pParse->nMem = 1;
93675     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
93676     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
93677       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93678       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93679     }
93680   }else
93681 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
93682 
93683 #ifndef SQLITE_OMIT_WAL
93684   /*
93685   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93686   **
93687   ** Checkpoint the database.
93688   */
93689   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
93690     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
93691     int eMode = SQLITE_CHECKPOINT_PASSIVE;
93692     if( zRight ){
93693       if( sqlite3StrICmp(zRight, "full")==0 ){
93694         eMode = SQLITE_CHECKPOINT_FULL;
93695       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
93696         eMode = SQLITE_CHECKPOINT_RESTART;
93697       }
93698     }
93699     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93700     sqlite3VdbeSetNumCols(v, 3);
93701     pParse->nMem = 3;
93702     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
93703     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
93704     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
93705 
93706     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93707     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93708   }else
93709 
93710   /*
93711   **   PRAGMA wal_autocheckpoint
93712   **   PRAGMA wal_autocheckpoint = N
93713   **
93714   ** Configure a database connection to automatically checkpoint a database
93715   ** after accumulating N frames in the log. Or query for the current value
93716   ** of N.
93717   */
93718   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93719     if( zRight ){
93720       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
93721     }
93722     returnSingleInt(pParse, "wal_autocheckpoint",
93723        db->xWalCallback==sqlite3WalDefaultHook ?
93724            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
93725   }else
93726 #endif
93727 
93728   /*
93729   **  PRAGMA shrink_memory
93730   **
93731   ** This pragma attempts to free as much memory as possible from the
93732   ** current database connection.
93733   */
93734   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
93735     sqlite3_db_release_memory(db);
93736   }else
93737 
93738   /*
93739   **   PRAGMA busy_timeout
93740   **   PRAGMA busy_timeout = N
93741   **
93742   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
93743   ** if one is set.  If no busy handler or a different busy handler is set
93744   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
93745   ** disables the timeout.
93746   */
93747   if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
93748     if( zRight ){
93749       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
93750     }
93751     returnSingleInt(pParse, "timeout",  db->busyTimeout);
93752   }else
93753 
93754 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
93755   /*
93756   ** Report the current state of file logs for all databases
93757   */
93758   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
93759     static const char *const azLockName[] = {
93760       "unlocked", "shared", "reserved", "pending", "exclusive"
93761     };
93762     int i;
93763     sqlite3VdbeSetNumCols(v, 2);
93764     pParse->nMem = 2;
93765     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
93766     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
93767     for(i=0; i<db->nDb; i++){
93768       Btree *pBt;
93769       const char *zState = "unknown";
93770       int j;
93771       if( db->aDb[i].zName==0 ) continue;
93772       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93773       pBt = db->aDb[i].pBt;
93774       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
93775         zState = "closed";
93776       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
93777                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
93778          zState = azLockName[j];
93779       }
93780       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93781       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93782     }
93783 
93784   }else
93785 #endif
93786 
93787 #ifdef SQLITE_HAS_CODEC
93788   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
93789     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
93790   }else
93791   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
93792     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
93793   }else
93794   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
93795                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
93796     int i, h1, h2;
93797     char zKey[40];
93798     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93799       h1 += 9*(1&(h1>>6));
93800       h2 += 9*(1&(h2>>6));
93801       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93802     }
93803     if( (zLeft[3] & 0xf)==0xb ){
93804       sqlite3_key(db, zKey, i/2);
93805     }else{
93806       sqlite3_rekey(db, zKey, i/2);
93807     }
93808   }else
93809 #endif
93810 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
93811   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
93812 #ifdef SQLITE_HAS_CODEC
93813     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
93814       sqlite3_activate_see(&zRight[4]);
93815     }
93816 #endif
93817 #ifdef SQLITE_ENABLE_CEROD
93818     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
93819       sqlite3_activate_cerod(&zRight[6]);
93820     }
93821 #endif
93822   }else
93823 #endif
93824 
93825 
93826   {/* Empty ELSE clause */}
93827 
93828   /*
93829   ** Reset the safety level, in case the fullfsync flag or synchronous
93830   ** setting changed.
93831   */
93832 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93833   if( db->autoCommit ){
93834     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93835                (db->flags&SQLITE_FullFSync)!=0,
93836                (db->flags&SQLITE_CkptFullFSync)!=0);
93837   }
93838 #endif
93839 pragma_out:
93840   sqlite3DbFree(db, zLeft);
93841   sqlite3DbFree(db, zRight);
93842 }
93843 
93844 #endif /* SQLITE_OMIT_PRAGMA */
93845 
93846 /************** End of pragma.c **********************************************/
93847 /************** Begin file prepare.c *****************************************/
93848 /*
93849 ** 2005 May 25
93850 **
93851 ** The author disclaims copyright to this source code.  In place of
93852 ** a legal notice, here is a blessing:
93853 **
93854 **    May you do good and not evil.
93855 **    May you find forgiveness for yourself and forgive others.
93856 **    May you share freely, never taking more than you give.
93857 **
93858 *************************************************************************
93859 ** This file contains the implementation of the sqlite3_prepare()
93860 ** interface, and routines that contribute to loading the database schema
93861 ** from disk.
93862 */
93863 
93864 /*
93865 ** Fill the InitData structure with an error message that indicates
93866 ** that the database is corrupt.
93867 */
93868 static void corruptSchema(
93869   InitData *pData,     /* Initialization context */
93870   const char *zObj,    /* Object being parsed at the point of error */
93871   const char *zExtra   /* Error information */
93872 ){
93873   sqlite3 *db = pData->db;
93874   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
93875     if( zObj==0 ) zObj = "?";
93876     sqlite3SetString(pData->pzErrMsg, db,
93877       "malformed database schema (%s)", zObj);
93878     if( zExtra ){
93879       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
93880                                  "%s - %s", *pData->pzErrMsg, zExtra);
93881     }
93882   }
93883   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
93884 }
93885 
93886 /*
93887 ** This is the callback routine for the code that initializes the
93888 ** database.  See sqlite3Init() below for additional information.
93889 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93890 **
93891 ** Each callback contains the following information:
93892 **
93893 **     argv[0] = name of thing being created
93894 **     argv[1] = root page number for table or index. 0 for trigger or view.
93895 **     argv[2] = SQL text for the CREATE statement.
93896 **
93897 */
93898 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93899   InitData *pData = (InitData*)pInit;
93900   sqlite3 *db = pData->db;
93901   int iDb = pData->iDb;
93902 
93903   assert( argc==3 );
93904   UNUSED_PARAMETER2(NotUsed, argc);
93905   assert( sqlite3_mutex_held(db->mutex) );
93906   DbClearProperty(db, iDb, DB_Empty);
93907   if( db->mallocFailed ){
93908     corruptSchema(pData, argv[0], 0);
93909     return 1;
93910   }
93911 
93912   assert( iDb>=0 && iDb<db->nDb );
93913   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93914   if( argv[1]==0 ){
93915     corruptSchema(pData, argv[0], 0);
93916   }else if( argv[2] && argv[2][0] ){
93917     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93918     ** But because db->init.busy is set to 1, no VDBE code is generated
93919     ** or executed.  All the parser does is build the internal data
93920     ** structures that describe the table, index, or view.
93921     */
93922     int rc;
93923     sqlite3_stmt *pStmt;
93924     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
93925 
93926     assert( db->init.busy );
93927     db->init.iDb = iDb;
93928     db->init.newTnum = sqlite3Atoi(argv[1]);
93929     db->init.orphanTrigger = 0;
93930     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
93931     rc = db->errCode;
93932     assert( (rc&0xFF)==(rcp&0xFF) );
93933     db->init.iDb = 0;
93934     if( SQLITE_OK!=rc ){
93935       if( db->init.orphanTrigger ){
93936         assert( iDb==1 );
93937       }else{
93938         pData->rc = rc;
93939         if( rc==SQLITE_NOMEM ){
93940           db->mallocFailed = 1;
93941         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
93942           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
93943         }
93944       }
93945     }
93946     sqlite3_finalize(pStmt);
93947   }else if( argv[0]==0 ){
93948     corruptSchema(pData, 0, 0);
93949   }else{
93950     /* If the SQL column is blank it means this is an index that
93951     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93952     ** constraint for a CREATE TABLE.  The index should have already
93953     ** been created when we processed the CREATE TABLE.  All we have
93954     ** to do here is record the root page number for that index.
93955     */
93956     Index *pIndex;
93957     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
93958     if( pIndex==0 ){
93959       /* This can occur if there exists an index on a TEMP table which
93960       ** has the same name as another index on a permanent index.  Since
93961       ** the permanent table is hidden by the TEMP table, we can also
93962       ** safely ignore the index on the permanent table.
93963       */
93964       /* Do Nothing */;
93965     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
93966       corruptSchema(pData, argv[0], "invalid rootpage");
93967     }
93968   }
93969   return 0;
93970 }
93971 
93972 /*
93973 ** Attempt to read the database schema and initialize internal
93974 ** data structures for a single database file.  The index of the
93975 ** database file is given by iDb.  iDb==0 is used for the main
93976 ** database.  iDb==1 should never be used.  iDb>=2 is used for
93977 ** auxiliary databases.  Return one of the SQLITE_ error codes to
93978 ** indicate success or failure.
93979 */
93980 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
93981   int rc;
93982   int i;
93983 #ifndef SQLITE_OMIT_DEPRECATED
93984   int size;
93985 #endif
93986   Table *pTab;
93987   Db *pDb;
93988   char const *azArg[4];
93989   int meta[5];
93990   InitData initData;
93991   char const *zMasterSchema;
93992   char const *zMasterName;
93993   int openedTransaction = 0;
93994 
93995   /*
93996   ** The master database table has a structure like this
93997   */
93998   static const char master_schema[] =
93999      "CREATE TABLE sqlite_master(\n"
94000      "  type text,\n"
94001      "  name text,\n"
94002      "  tbl_name text,\n"
94003      "  rootpage integer,\n"
94004      "  sql text\n"
94005      ")"
94006   ;
94007 #ifndef SQLITE_OMIT_TEMPDB
94008   static const char temp_master_schema[] =
94009      "CREATE TEMP TABLE sqlite_temp_master(\n"
94010      "  type text,\n"
94011      "  name text,\n"
94012      "  tbl_name text,\n"
94013      "  rootpage integer,\n"
94014      "  sql text\n"
94015      ")"
94016   ;
94017 #else
94018   #define temp_master_schema 0
94019 #endif
94020 
94021   assert( iDb>=0 && iDb<db->nDb );
94022   assert( db->aDb[iDb].pSchema );
94023   assert( sqlite3_mutex_held(db->mutex) );
94024   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
94025 
94026   /* zMasterSchema and zInitScript are set to point at the master schema
94027   ** and initialisation script appropriate for the database being
94028   ** initialized. zMasterName is the name of the master table.
94029   */
94030   if( !OMIT_TEMPDB && iDb==1 ){
94031     zMasterSchema = temp_master_schema;
94032   }else{
94033     zMasterSchema = master_schema;
94034   }
94035   zMasterName = SCHEMA_TABLE(iDb);
94036 
94037   /* Construct the schema tables.  */
94038   azArg[0] = zMasterName;
94039   azArg[1] = "1";
94040   azArg[2] = zMasterSchema;
94041   azArg[3] = 0;
94042   initData.db = db;
94043   initData.iDb = iDb;
94044   initData.rc = SQLITE_OK;
94045   initData.pzErrMsg = pzErrMsg;
94046   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
94047   if( initData.rc ){
94048     rc = initData.rc;
94049     goto error_out;
94050   }
94051   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
94052   if( ALWAYS(pTab) ){
94053     pTab->tabFlags |= TF_Readonly;
94054   }
94055 
94056   /* Create a cursor to hold the database open
94057   */
94058   pDb = &db->aDb[iDb];
94059   if( pDb->pBt==0 ){
94060     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
94061       DbSetProperty(db, 1, DB_SchemaLoaded);
94062     }
94063     return SQLITE_OK;
94064   }
94065 
94066   /* If there is not already a read-only (or read-write) transaction opened
94067   ** on the b-tree database, open one now. If a transaction is opened, it
94068   ** will be closed before this function returns.  */
94069   sqlite3BtreeEnter(pDb->pBt);
94070   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
94071     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
94072     if( rc!=SQLITE_OK ){
94073       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
94074       goto initone_error_out;
94075     }
94076     openedTransaction = 1;
94077   }
94078 
94079   /* Get the database meta information.
94080   **
94081   ** Meta values are as follows:
94082   **    meta[0]   Schema cookie.  Changes with each schema change.
94083   **    meta[1]   File format of schema layer.
94084   **    meta[2]   Size of the page cache.
94085   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
94086   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
94087   **    meta[5]   User version
94088   **    meta[6]   Incremental vacuum mode
94089   **    meta[7]   unused
94090   **    meta[8]   unused
94091   **    meta[9]   unused
94092   **
94093   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
94094   ** the possible values of meta[4].
94095   */
94096   for(i=0; i<ArraySize(meta); i++){
94097     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
94098   }
94099   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
94100 
94101   /* If opening a non-empty database, check the text encoding. For the
94102   ** main database, set sqlite3.enc to the encoding of the main database.
94103   ** For an attached db, it is an error if the encoding is not the same
94104   ** as sqlite3.enc.
94105   */
94106   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
94107     if( iDb==0 ){
94108 #ifndef SQLITE_OMIT_UTF16
94109       u8 encoding;
94110       /* If opening the main database, set ENC(db). */
94111       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
94112       if( encoding==0 ) encoding = SQLITE_UTF8;
94113       ENC(db) = encoding;
94114 #else
94115       ENC(db) = SQLITE_UTF8;
94116 #endif
94117     }else{
94118       /* If opening an attached database, the encoding much match ENC(db) */
94119       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
94120         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
94121             " text encoding as main database");
94122         rc = SQLITE_ERROR;
94123         goto initone_error_out;
94124       }
94125     }
94126   }else{
94127     DbSetProperty(db, iDb, DB_Empty);
94128   }
94129   pDb->pSchema->enc = ENC(db);
94130 
94131   if( pDb->pSchema->cache_size==0 ){
94132 #ifndef SQLITE_OMIT_DEPRECATED
94133     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
94134     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
94135     pDb->pSchema->cache_size = size;
94136 #else
94137     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
94138 #endif
94139     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94140   }
94141 
94142   /*
94143   ** file_format==1    Version 3.0.0.
94144   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
94145   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
94146   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
94147   */
94148   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
94149   if( pDb->pSchema->file_format==0 ){
94150     pDb->pSchema->file_format = 1;
94151   }
94152   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
94153     sqlite3SetString(pzErrMsg, db, "unsupported file format");
94154     rc = SQLITE_ERROR;
94155     goto initone_error_out;
94156   }
94157 
94158   /* Ticket #2804:  When we open a database in the newer file format,
94159   ** clear the legacy_file_format pragma flag so that a VACUUM will
94160   ** not downgrade the database and thus invalidate any descending
94161   ** indices that the user might have created.
94162   */
94163   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
94164     db->flags &= ~SQLITE_LegacyFileFmt;
94165   }
94166 
94167   /* Read the schema information out of the schema tables
94168   */
94169   assert( db->init.busy );
94170   {
94171     char *zSql;
94172     zSql = sqlite3MPrintf(db,
94173         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
94174         db->aDb[iDb].zName, zMasterName);
94175 #ifndef SQLITE_OMIT_AUTHORIZATION
94176     {
94177       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
94178       xAuth = db->xAuth;
94179       db->xAuth = 0;
94180 #endif
94181       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
94182 #ifndef SQLITE_OMIT_AUTHORIZATION
94183       db->xAuth = xAuth;
94184     }
94185 #endif
94186     if( rc==SQLITE_OK ) rc = initData.rc;
94187     sqlite3DbFree(db, zSql);
94188 #ifndef SQLITE_OMIT_ANALYZE
94189     if( rc==SQLITE_OK ){
94190       sqlite3AnalysisLoad(db, iDb);
94191     }
94192 #endif
94193   }
94194   if( db->mallocFailed ){
94195     rc = SQLITE_NOMEM;
94196     sqlite3ResetAllSchemasOfConnection(db);
94197   }
94198   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
94199     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
94200     ** the schema loaded, even if errors occurred. In this situation the
94201     ** current sqlite3_prepare() operation will fail, but the following one
94202     ** will attempt to compile the supplied statement against whatever subset
94203     ** of the schema was loaded before the error occurred. The primary
94204     ** purpose of this is to allow access to the sqlite_master table
94205     ** even when its contents have been corrupted.
94206     */
94207     DbSetProperty(db, iDb, DB_SchemaLoaded);
94208     rc = SQLITE_OK;
94209   }
94210 
94211   /* Jump here for an error that occurs after successfully allocating
94212   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
94213   ** before that point, jump to error_out.
94214   */
94215 initone_error_out:
94216   if( openedTransaction ){
94217     sqlite3BtreeCommit(pDb->pBt);
94218   }
94219   sqlite3BtreeLeave(pDb->pBt);
94220 
94221 error_out:
94222   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94223     db->mallocFailed = 1;
94224   }
94225   return rc;
94226 }
94227 
94228 /*
94229 ** Initialize all database files - the main database file, the file
94230 ** used to store temporary tables, and any additional database files
94231 ** created using ATTACH statements.  Return a success code.  If an
94232 ** error occurs, write an error message into *pzErrMsg.
94233 **
94234 ** After a database is initialized, the DB_SchemaLoaded bit is set
94235 ** bit is set in the flags field of the Db structure. If the database
94236 ** file was of zero-length, then the DB_Empty flag is also set.
94237 */
94238 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
94239   int i, rc;
94240   int commit_internal = !(db->flags&SQLITE_InternChanges);
94241 
94242   assert( sqlite3_mutex_held(db->mutex) );
94243   rc = SQLITE_OK;
94244   db->init.busy = 1;
94245   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
94246     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
94247     rc = sqlite3InitOne(db, i, pzErrMsg);
94248     if( rc ){
94249       sqlite3ResetOneSchema(db, i);
94250     }
94251   }
94252 
94253   /* Once all the other databases have been initialized, load the schema
94254   ** for the TEMP database. This is loaded last, as the TEMP database
94255   ** schema may contain references to objects in other databases.
94256   */
94257 #ifndef SQLITE_OMIT_TEMPDB
94258   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
94259                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
94260     rc = sqlite3InitOne(db, 1, pzErrMsg);
94261     if( rc ){
94262       sqlite3ResetOneSchema(db, 1);
94263     }
94264   }
94265 #endif
94266 
94267   db->init.busy = 0;
94268   if( rc==SQLITE_OK && commit_internal ){
94269     sqlite3CommitInternalChanges(db);
94270   }
94271 
94272   return rc;
94273 }
94274 
94275 /*
94276 ** This routine is a no-op if the database schema is already initialized.
94277 ** Otherwise, the schema is loaded. An error code is returned.
94278 */
94279 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
94280   int rc = SQLITE_OK;
94281   sqlite3 *db = pParse->db;
94282   assert( sqlite3_mutex_held(db->mutex) );
94283   if( !db->init.busy ){
94284     rc = sqlite3Init(db, &pParse->zErrMsg);
94285   }
94286   if( rc!=SQLITE_OK ){
94287     pParse->rc = rc;
94288     pParse->nErr++;
94289   }
94290   return rc;
94291 }
94292 
94293 
94294 /*
94295 ** Check schema cookies in all databases.  If any cookie is out
94296 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
94297 ** make no changes to pParse->rc.
94298 */
94299 static void schemaIsValid(Parse *pParse){
94300   sqlite3 *db = pParse->db;
94301   int iDb;
94302   int rc;
94303   int cookie;
94304 
94305   assert( pParse->checkSchema );
94306   assert( sqlite3_mutex_held(db->mutex) );
94307   for(iDb=0; iDb<db->nDb; iDb++){
94308     int openedTransaction = 0;         /* True if a transaction is opened */
94309     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
94310     if( pBt==0 ) continue;
94311 
94312     /* If there is not already a read-only (or read-write) transaction opened
94313     ** on the b-tree database, open one now. If a transaction is opened, it
94314     ** will be closed immediately after reading the meta-value. */
94315     if( !sqlite3BtreeIsInReadTrans(pBt) ){
94316       rc = sqlite3BtreeBeginTrans(pBt, 0);
94317       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94318         db->mallocFailed = 1;
94319       }
94320       if( rc!=SQLITE_OK ) return;
94321       openedTransaction = 1;
94322     }
94323 
94324     /* Read the schema cookie from the database. If it does not match the
94325     ** value stored as part of the in-memory schema representation,
94326     ** set Parse.rc to SQLITE_SCHEMA. */
94327     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
94328     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94329     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
94330       sqlite3ResetOneSchema(db, iDb);
94331       pParse->rc = SQLITE_SCHEMA;
94332     }
94333 
94334     /* Close the transaction, if one was opened. */
94335     if( openedTransaction ){
94336       sqlite3BtreeCommit(pBt);
94337     }
94338   }
94339 }
94340 
94341 /*
94342 ** Convert a schema pointer into the iDb index that indicates
94343 ** which database file in db->aDb[] the schema refers to.
94344 **
94345 ** If the same database is attached more than once, the first
94346 ** attached database is returned.
94347 */
94348 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
94349   int i = -1000000;
94350 
94351   /* If pSchema is NULL, then return -1000000. This happens when code in
94352   ** expr.c is trying to resolve a reference to a transient table (i.e. one
94353   ** created by a sub-select). In this case the return value of this
94354   ** function should never be used.
94355   **
94356   ** We return -1000000 instead of the more usual -1 simply because using
94357   ** -1000000 as the incorrect index into db->aDb[] is much
94358   ** more likely to cause a segfault than -1 (of course there are assert()
94359   ** statements too, but it never hurts to play the odds).
94360   */
94361   assert( sqlite3_mutex_held(db->mutex) );
94362   if( pSchema ){
94363     for(i=0; ALWAYS(i<db->nDb); i++){
94364       if( db->aDb[i].pSchema==pSchema ){
94365         break;
94366       }
94367     }
94368     assert( i>=0 && i<db->nDb );
94369   }
94370   return i;
94371 }
94372 
94373 /*
94374 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
94375 */
94376 static int sqlite3Prepare(
94377   sqlite3 *db,              /* Database handle. */
94378   const char *zSql,         /* UTF-8 encoded SQL statement. */
94379   int nBytes,               /* Length of zSql in bytes. */
94380   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94381   Vdbe *pReprepare,         /* VM being reprepared */
94382   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94383   const char **pzTail       /* OUT: End of parsed string */
94384 ){
94385   Parse *pParse;            /* Parsing context */
94386   char *zErrMsg = 0;        /* Error message */
94387   int rc = SQLITE_OK;       /* Result code */
94388   int i;                    /* Loop counter */
94389 
94390   /* Allocate the parsing context */
94391   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
94392   if( pParse==0 ){
94393     rc = SQLITE_NOMEM;
94394     goto end_prepare;
94395   }
94396   pParse->pReprepare = pReprepare;
94397   assert( ppStmt && *ppStmt==0 );
94398   assert( !db->mallocFailed );
94399   assert( sqlite3_mutex_held(db->mutex) );
94400 
94401   /* Check to verify that it is possible to get a read lock on all
94402   ** database schemas.  The inability to get a read lock indicates that
94403   ** some other database connection is holding a write-lock, which in
94404   ** turn means that the other connection has made uncommitted changes
94405   ** to the schema.
94406   **
94407   ** Were we to proceed and prepare the statement against the uncommitted
94408   ** schema changes and if those schema changes are subsequently rolled
94409   ** back and different changes are made in their place, then when this
94410   ** prepared statement goes to run the schema cookie would fail to detect
94411   ** the schema change.  Disaster would follow.
94412   **
94413   ** This thread is currently holding mutexes on all Btrees (because
94414   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
94415   ** is not possible for another thread to start a new schema change
94416   ** while this routine is running.  Hence, we do not need to hold
94417   ** locks on the schema, we just need to make sure nobody else is
94418   ** holding them.
94419   **
94420   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
94421   ** but it does *not* override schema lock detection, so this all still
94422   ** works even if READ_UNCOMMITTED is set.
94423   */
94424   for(i=0; i<db->nDb; i++) {
94425     Btree *pBt = db->aDb[i].pBt;
94426     if( pBt ){
94427       assert( sqlite3BtreeHoldsMutex(pBt) );
94428       rc = sqlite3BtreeSchemaLocked(pBt);
94429       if( rc ){
94430         const char *zDb = db->aDb[i].zName;
94431         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
94432         testcase( db->flags & SQLITE_ReadUncommitted );
94433         goto end_prepare;
94434       }
94435     }
94436   }
94437 
94438   sqlite3VtabUnlockList(db);
94439 
94440   pParse->db = db;
94441   pParse->nQueryLoop = (double)1;
94442   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
94443     char *zSqlCopy;
94444     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94445     testcase( nBytes==mxLen );
94446     testcase( nBytes==mxLen+1 );
94447     if( nBytes>mxLen ){
94448       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
94449       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
94450       goto end_prepare;
94451     }
94452     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
94453     if( zSqlCopy ){
94454       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
94455       sqlite3DbFree(db, zSqlCopy);
94456       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
94457     }else{
94458       pParse->zTail = &zSql[nBytes];
94459     }
94460   }else{
94461     sqlite3RunParser(pParse, zSql, &zErrMsg);
94462   }
94463   assert( 1==(int)pParse->nQueryLoop );
94464 
94465   if( db->mallocFailed ){
94466     pParse->rc = SQLITE_NOMEM;
94467   }
94468   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
94469   if( pParse->checkSchema ){
94470     schemaIsValid(pParse);
94471   }
94472   if( db->mallocFailed ){
94473     pParse->rc = SQLITE_NOMEM;
94474   }
94475   if( pzTail ){
94476     *pzTail = pParse->zTail;
94477   }
94478   rc = pParse->rc;
94479 
94480 #ifndef SQLITE_OMIT_EXPLAIN
94481   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
94482     static const char * const azColName[] = {
94483        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
94484        "selectid", "order", "from", "detail"
94485     };
94486     int iFirst, mx;
94487     if( pParse->explain==2 ){
94488       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
94489       iFirst = 8;
94490       mx = 12;
94491     }else{
94492       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
94493       iFirst = 0;
94494       mx = 8;
94495     }
94496     for(i=iFirst; i<mx; i++){
94497       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
94498                             azColName[i], SQLITE_STATIC);
94499     }
94500   }
94501 #endif
94502 
94503   assert( db->init.busy==0 || saveSqlFlag==0 );
94504   if( db->init.busy==0 ){
94505     Vdbe *pVdbe = pParse->pVdbe;
94506     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
94507   }
94508   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
94509     sqlite3VdbeFinalize(pParse->pVdbe);
94510     assert(!(*ppStmt));
94511   }else{
94512     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
94513   }
94514 
94515   if( zErrMsg ){
94516     sqlite3Error(db, rc, "%s", zErrMsg);
94517     sqlite3DbFree(db, zErrMsg);
94518   }else{
94519     sqlite3Error(db, rc, 0);
94520   }
94521 
94522   /* Delete any TriggerPrg structures allocated while parsing this statement. */
94523   while( pParse->pTriggerPrg ){
94524     TriggerPrg *pT = pParse->pTriggerPrg;
94525     pParse->pTriggerPrg = pT->pNext;
94526     sqlite3DbFree(db, pT);
94527   }
94528 
94529 end_prepare:
94530 
94531   sqlite3StackFree(db, pParse);
94532   rc = sqlite3ApiExit(db, rc);
94533   assert( (rc&db->errMask)==rc );
94534   return rc;
94535 }
94536 static int sqlite3LockAndPrepare(
94537   sqlite3 *db,              /* Database handle. */
94538   const char *zSql,         /* UTF-8 encoded SQL statement. */
94539   int nBytes,               /* Length of zSql in bytes. */
94540   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94541   Vdbe *pOld,               /* VM being reprepared */
94542   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94543   const char **pzTail       /* OUT: End of parsed string */
94544 ){
94545   int rc;
94546   assert( ppStmt!=0 );
94547   *ppStmt = 0;
94548   if( !sqlite3SafetyCheckOk(db) ){
94549     return SQLITE_MISUSE_BKPT;
94550   }
94551   sqlite3_mutex_enter(db->mutex);
94552   sqlite3BtreeEnterAll(db);
94553   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94554   if( rc==SQLITE_SCHEMA ){
94555     sqlite3_finalize(*ppStmt);
94556     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94557   }
94558   sqlite3BtreeLeaveAll(db);
94559   sqlite3_mutex_leave(db->mutex);
94560   assert( rc==SQLITE_OK || *ppStmt==0 );
94561   return rc;
94562 }
94563 
94564 /*
94565 ** Rerun the compilation of a statement after a schema change.
94566 **
94567 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
94568 ** if the statement cannot be recompiled because another connection has
94569 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
94570 ** occurs, return SQLITE_SCHEMA.
94571 */
94572 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
94573   int rc;
94574   sqlite3_stmt *pNew;
94575   const char *zSql;
94576   sqlite3 *db;
94577 
94578   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
94579   zSql = sqlite3_sql((sqlite3_stmt *)p);
94580   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94581   db = sqlite3VdbeDb(p);
94582   assert( sqlite3_mutex_held(db->mutex) );
94583   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94584   if( rc ){
94585     if( rc==SQLITE_NOMEM ){
94586       db->mallocFailed = 1;
94587     }
94588     assert( pNew==0 );
94589     return rc;
94590   }else{
94591     assert( pNew!=0 );
94592   }
94593   sqlite3VdbeSwap((Vdbe*)pNew, p);
94594   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
94595   sqlite3VdbeResetStepResult((Vdbe*)pNew);
94596   sqlite3VdbeFinalize((Vdbe*)pNew);
94597   return SQLITE_OK;
94598 }
94599 
94600 
94601 /*
94602 ** Two versions of the official API.  Legacy and new use.  In the legacy
94603 ** version, the original SQL text is not saved in the prepared statement
94604 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94605 ** sqlite3_step().  In the new version, the original SQL text is retained
94606 ** and the statement is automatically recompiled if an schema change
94607 ** occurs.
94608 */
94609 SQLITE_API int sqlite3_prepare(
94610   sqlite3 *db,              /* Database handle. */
94611   const char *zSql,         /* UTF-8 encoded SQL statement. */
94612   int nBytes,               /* Length of zSql in bytes. */
94613   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94614   const char **pzTail       /* OUT: End of parsed string */
94615 ){
94616   int rc;
94617   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94618   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94619   return rc;
94620 }
94621 SQLITE_API int sqlite3_prepare_v2(
94622   sqlite3 *db,              /* Database handle. */
94623   const char *zSql,         /* UTF-8 encoded SQL statement. */
94624   int nBytes,               /* Length of zSql in bytes. */
94625   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94626   const char **pzTail       /* OUT: End of parsed string */
94627 ){
94628   int rc;
94629   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94630   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94631   return rc;
94632 }
94633 
94634 
94635 #ifndef SQLITE_OMIT_UTF16
94636 /*
94637 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94638 */
94639 static int sqlite3Prepare16(
94640   sqlite3 *db,              /* Database handle. */
94641   const void *zSql,         /* UTF-16 encoded SQL statement. */
94642   int nBytes,               /* Length of zSql in bytes. */
94643   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
94644   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94645   const void **pzTail       /* OUT: End of parsed string */
94646 ){
94647   /* This function currently works by first transforming the UTF-16
94648   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
94649   ** tricky bit is figuring out the pointer to return in *pzTail.
94650   */
94651   char *zSql8;
94652   const char *zTail8 = 0;
94653   int rc = SQLITE_OK;
94654 
94655   assert( ppStmt );
94656   *ppStmt = 0;
94657   if( !sqlite3SafetyCheckOk(db) ){
94658     return SQLITE_MISUSE_BKPT;
94659   }
94660   sqlite3_mutex_enter(db->mutex);
94661   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
94662   if( zSql8 ){
94663     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94664   }
94665 
94666   if( zTail8 && pzTail ){
94667     /* If sqlite3_prepare returns a tail pointer, we calculate the
94668     ** equivalent pointer into the UTF-16 string by counting the unicode
94669     ** characters between zSql8 and zTail8, and then returning a pointer
94670     ** the same number of characters into the UTF-16 string.
94671     */
94672     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94673     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
94674   }
94675   sqlite3DbFree(db, zSql8);
94676   rc = sqlite3ApiExit(db, rc);
94677   sqlite3_mutex_leave(db->mutex);
94678   return rc;
94679 }
94680 
94681 /*
94682 ** Two versions of the official API.  Legacy and new use.  In the legacy
94683 ** version, the original SQL text is not saved in the prepared statement
94684 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94685 ** sqlite3_step().  In the new version, the original SQL text is retained
94686 ** and the statement is automatically recompiled if an schema change
94687 ** occurs.
94688 */
94689 SQLITE_API int sqlite3_prepare16(
94690   sqlite3 *db,              /* Database handle. */
94691   const void *zSql,         /* UTF-16 encoded SQL statement. */
94692   int nBytes,               /* Length of zSql in bytes. */
94693   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94694   const void **pzTail       /* OUT: End of parsed string */
94695 ){
94696   int rc;
94697   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94698   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94699   return rc;
94700 }
94701 SQLITE_API int sqlite3_prepare16_v2(
94702   sqlite3 *db,              /* Database handle. */
94703   const void *zSql,         /* UTF-16 encoded SQL statement. */
94704   int nBytes,               /* Length of zSql in bytes. */
94705   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94706   const void **pzTail       /* OUT: End of parsed string */
94707 ){
94708   int rc;
94709   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94710   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94711   return rc;
94712 }
94713 
94714 #endif /* SQLITE_OMIT_UTF16 */
94715 
94716 /************** End of prepare.c *********************************************/
94717 /************** Begin file select.c ******************************************/
94718 /*
94719 ** 2001 September 15
94720 **
94721 ** The author disclaims copyright to this source code.  In place of
94722 ** a legal notice, here is a blessing:
94723 **
94724 **    May you do good and not evil.
94725 **    May you find forgiveness for yourself and forgive others.
94726 **    May you share freely, never taking more than you give.
94727 **
94728 *************************************************************************
94729 ** This file contains C code routines that are called by the parser
94730 ** to handle SELECT statements in SQLite.
94731 */
94732 
94733 
94734 /*
94735 ** Delete all the content of a Select structure but do not deallocate
94736 ** the select structure itself.
94737 */
94738 static void clearSelect(sqlite3 *db, Select *p){
94739   sqlite3ExprListDelete(db, p->pEList);
94740   sqlite3SrcListDelete(db, p->pSrc);
94741   sqlite3ExprDelete(db, p->pWhere);
94742   sqlite3ExprListDelete(db, p->pGroupBy);
94743   sqlite3ExprDelete(db, p->pHaving);
94744   sqlite3ExprListDelete(db, p->pOrderBy);
94745   sqlite3SelectDelete(db, p->pPrior);
94746   sqlite3ExprDelete(db, p->pLimit);
94747   sqlite3ExprDelete(db, p->pOffset);
94748 }
94749 
94750 /*
94751 ** Initialize a SelectDest structure.
94752 */
94753 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94754   pDest->eDest = (u8)eDest;
94755   pDest->iSDParm = iParm;
94756   pDest->affSdst = 0;
94757   pDest->iSdst = 0;
94758   pDest->nSdst = 0;
94759 }
94760 
94761 
94762 /*
94763 ** Allocate a new Select structure and return a pointer to that
94764 ** structure.
94765 */
94766 SQLITE_PRIVATE Select *sqlite3SelectNew(
94767   Parse *pParse,        /* Parsing context */
94768   ExprList *pEList,     /* which columns to include in the result */
94769   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94770   Expr *pWhere,         /* the WHERE clause */
94771   ExprList *pGroupBy,   /* the GROUP BY clause */
94772   Expr *pHaving,        /* the HAVING clause */
94773   ExprList *pOrderBy,   /* the ORDER BY clause */
94774   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
94775   Expr *pLimit,         /* LIMIT value.  NULL means not used */
94776   Expr *pOffset         /* OFFSET value.  NULL means no offset */
94777 ){
94778   Select *pNew;
94779   Select standin;
94780   sqlite3 *db = pParse->db;
94781   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
94782   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94783   if( pNew==0 ){
94784     assert( db->mallocFailed );
94785     pNew = &standin;
94786     memset(pNew, 0, sizeof(*pNew));
94787   }
94788   if( pEList==0 ){
94789     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
94790   }
94791   pNew->pEList = pEList;
94792   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
94793   pNew->pSrc = pSrc;
94794   pNew->pWhere = pWhere;
94795   pNew->pGroupBy = pGroupBy;
94796   pNew->pHaving = pHaving;
94797   pNew->pOrderBy = pOrderBy;
94798   pNew->selFlags = selFlags;
94799   pNew->op = TK_SELECT;
94800   pNew->pLimit = pLimit;
94801   pNew->pOffset = pOffset;
94802   assert( pOffset==0 || pLimit!=0 );
94803   pNew->addrOpenEphm[0] = -1;
94804   pNew->addrOpenEphm[1] = -1;
94805   pNew->addrOpenEphm[2] = -1;
94806   if( db->mallocFailed ) {
94807     clearSelect(db, pNew);
94808     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94809     pNew = 0;
94810   }else{
94811     assert( pNew->pSrc!=0 || pParse->nErr>0 );
94812   }
94813   assert( pNew!=&standin );
94814   return pNew;
94815 }
94816 
94817 /*
94818 ** Delete the given Select structure and all of its substructures.
94819 */
94820 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
94821   if( p ){
94822     clearSelect(db, p);
94823     sqlite3DbFree(db, p);
94824   }
94825 }
94826 
94827 /*
94828 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94829 ** type of join.  Return an integer constant that expresses that type
94830 ** in terms of the following bit values:
94831 **
94832 **     JT_INNER
94833 **     JT_CROSS
94834 **     JT_OUTER
94835 **     JT_NATURAL
94836 **     JT_LEFT
94837 **     JT_RIGHT
94838 **
94839 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94840 **
94841 ** If an illegal or unsupported join type is seen, then still return
94842 ** a join type, but put an error in the pParse structure.
94843 */
94844 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94845   int jointype = 0;
94846   Token *apAll[3];
94847   Token *p;
94848                              /*   0123456789 123456789 123456789 123 */
94849   static const char zKeyText[] = "naturaleftouterightfullinnercross";
94850   static const struct {
94851     u8 i;        /* Beginning of keyword text in zKeyText[] */
94852     u8 nChar;    /* Length of the keyword in characters */
94853     u8 code;     /* Join type mask */
94854   } aKeyword[] = {
94855     /* natural */ { 0,  7, JT_NATURAL                },
94856     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94857     /* outer   */ { 10, 5, JT_OUTER                  },
94858     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94859     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94860     /* inner   */ { 23, 5, JT_INNER                  },
94861     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94862   };
94863   int i, j;
94864   apAll[0] = pA;
94865   apAll[1] = pB;
94866   apAll[2] = pC;
94867   for(i=0; i<3 && apAll[i]; i++){
94868     p = apAll[i];
94869     for(j=0; j<ArraySize(aKeyword); j++){
94870       if( p->n==aKeyword[j].nChar
94871           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94872         jointype |= aKeyword[j].code;
94873         break;
94874       }
94875     }
94876     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94877     if( j>=ArraySize(aKeyword) ){
94878       jointype |= JT_ERROR;
94879       break;
94880     }
94881   }
94882   if(
94883      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94884      (jointype & JT_ERROR)!=0
94885   ){
94886     const char *zSp = " ";
94887     assert( pB!=0 );
94888     if( pC==0 ){ zSp++; }
94889     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
94890        "%T %T%s%T", pA, pB, zSp, pC);
94891     jointype = JT_INNER;
94892   }else if( (jointype & JT_OUTER)!=0
94893          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94894     sqlite3ErrorMsg(pParse,
94895       "RIGHT and FULL OUTER JOINs are not currently supported");
94896     jointype = JT_INNER;
94897   }
94898   return jointype;
94899 }
94900 
94901 /*
94902 ** Return the index of a column in a table.  Return -1 if the column
94903 ** is not contained in the table.
94904 */
94905 static int columnIndex(Table *pTab, const char *zCol){
94906   int i;
94907   for(i=0; i<pTab->nCol; i++){
94908     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94909   }
94910   return -1;
94911 }
94912 
94913 /*
94914 ** Search the first N tables in pSrc, from left to right, looking for a
94915 ** table that has a column named zCol.
94916 **
94917 ** When found, set *piTab and *piCol to the table index and column index
94918 ** of the matching column and return TRUE.
94919 **
94920 ** If not found, return FALSE.
94921 */
94922 static int tableAndColumnIndex(
94923   SrcList *pSrc,       /* Array of tables to search */
94924   int N,               /* Number of tables in pSrc->a[] to search */
94925   const char *zCol,    /* Name of the column we are looking for */
94926   int *piTab,          /* Write index of pSrc->a[] here */
94927   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94928 ){
94929   int i;               /* For looping over tables in pSrc */
94930   int iCol;            /* Index of column matching zCol */
94931 
94932   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94933   for(i=0; i<N; i++){
94934     iCol = columnIndex(pSrc->a[i].pTab, zCol);
94935     if( iCol>=0 ){
94936       if( piTab ){
94937         *piTab = i;
94938         *piCol = iCol;
94939       }
94940       return 1;
94941     }
94942   }
94943   return 0;
94944 }
94945 
94946 /*
94947 ** This function is used to add terms implied by JOIN syntax to the
94948 ** WHERE clause expression of a SELECT statement. The new term, which
94949 ** is ANDed with the existing WHERE clause, is of the form:
94950 **
94951 **    (tab1.col1 = tab2.col2)
94952 **
94953 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
94954 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94955 ** column iColRight of tab2.
94956 */
94957 static void addWhereTerm(
94958   Parse *pParse,                  /* Parsing context */
94959   SrcList *pSrc,                  /* List of tables in FROM clause */
94960   int iLeft,                      /* Index of first table to join in pSrc */
94961   int iColLeft,                   /* Index of column in first table */
94962   int iRight,                     /* Index of second table in pSrc */
94963   int iColRight,                  /* Index of column in second table */
94964   int isOuterJoin,                /* True if this is an OUTER join */
94965   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94966 ){
94967   sqlite3 *db = pParse->db;
94968   Expr *pE1;
94969   Expr *pE2;
94970   Expr *pEq;
94971 
94972   assert( iLeft<iRight );
94973   assert( pSrc->nSrc>iRight );
94974   assert( pSrc->a[iLeft].pTab );
94975   assert( pSrc->a[iRight].pTab );
94976 
94977   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94978   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
94979 
94980   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94981   if( pEq && isOuterJoin ){
94982     ExprSetProperty(pEq, EP_FromJoin);
94983     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94984     ExprSetIrreducible(pEq);
94985     pEq->iRightJoinTable = (i16)pE2->iTable;
94986   }
94987   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
94988 }
94989 
94990 /*
94991 ** Set the EP_FromJoin property on all terms of the given expression.
94992 ** And set the Expr.iRightJoinTable to iTable for every term in the
94993 ** expression.
94994 **
94995 ** The EP_FromJoin property is used on terms of an expression to tell
94996 ** the LEFT OUTER JOIN processing logic that this term is part of the
94997 ** join restriction specified in the ON or USING clause and not a part
94998 ** of the more general WHERE clause.  These terms are moved over to the
94999 ** WHERE clause during join processing but we need to remember that they
95000 ** originated in the ON or USING clause.
95001 **
95002 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
95003 ** expression depends on table iRightJoinTable even if that table is not
95004 ** explicitly mentioned in the expression.  That information is needed
95005 ** for cases like this:
95006 **
95007 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
95008 **
95009 ** The where clause needs to defer the handling of the t1.x=5
95010 ** term until after the t2 loop of the join.  In that way, a
95011 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
95012 ** defer the handling of t1.x=5, it will be processed immediately
95013 ** after the t1 loop and rows with t1.x!=5 will never appear in
95014 ** the output, which is incorrect.
95015 */
95016 static void setJoinExpr(Expr *p, int iTable){
95017   while( p ){
95018     ExprSetProperty(p, EP_FromJoin);
95019     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
95020     ExprSetIrreducible(p);
95021     p->iRightJoinTable = (i16)iTable;
95022     setJoinExpr(p->pLeft, iTable);
95023     p = p->pRight;
95024   }
95025 }
95026 
95027 /*
95028 ** This routine processes the join information for a SELECT statement.
95029 ** ON and USING clauses are converted into extra terms of the WHERE clause.
95030 ** NATURAL joins also create extra WHERE clause terms.
95031 **
95032 ** The terms of a FROM clause are contained in the Select.pSrc structure.
95033 ** The left most table is the first entry in Select.pSrc.  The right-most
95034 ** table is the last entry.  The join operator is held in the entry to
95035 ** the left.  Thus entry 0 contains the join operator for the join between
95036 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
95037 ** also attached to the left entry.
95038 **
95039 ** This routine returns the number of errors encountered.
95040 */
95041 static int sqliteProcessJoin(Parse *pParse, Select *p){
95042   SrcList *pSrc;                  /* All tables in the FROM clause */
95043   int i, j;                       /* Loop counters */
95044   struct SrcList_item *pLeft;     /* Left table being joined */
95045   struct SrcList_item *pRight;    /* Right table being joined */
95046 
95047   pSrc = p->pSrc;
95048   pLeft = &pSrc->a[0];
95049   pRight = &pLeft[1];
95050   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
95051     Table *pLeftTab = pLeft->pTab;
95052     Table *pRightTab = pRight->pTab;
95053     int isOuter;
95054 
95055     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
95056     isOuter = (pRight->jointype & JT_OUTER)!=0;
95057 
95058     /* When the NATURAL keyword is present, add WHERE clause terms for
95059     ** every column that the two tables have in common.
95060     */
95061     if( pRight->jointype & JT_NATURAL ){
95062       if( pRight->pOn || pRight->pUsing ){
95063         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
95064            "an ON or USING clause", 0);
95065         return 1;
95066       }
95067       for(j=0; j<pRightTab->nCol; j++){
95068         char *zName;   /* Name of column in the right table */
95069         int iLeft;     /* Matching left table */
95070         int iLeftCol;  /* Matching column in the left table */
95071 
95072         zName = pRightTab->aCol[j].zName;
95073         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
95074           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
95075                        isOuter, &p->pWhere);
95076         }
95077       }
95078     }
95079 
95080     /* Disallow both ON and USING clauses in the same join
95081     */
95082     if( pRight->pOn && pRight->pUsing ){
95083       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
95084         "clauses in the same join");
95085       return 1;
95086     }
95087 
95088     /* Add the ON clause to the end of the WHERE clause, connected by
95089     ** an AND operator.
95090     */
95091     if( pRight->pOn ){
95092       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
95093       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
95094       pRight->pOn = 0;
95095     }
95096 
95097     /* Create extra terms on the WHERE clause for each column named
95098     ** in the USING clause.  Example: If the two tables to be joined are
95099     ** A and B and the USING clause names X, Y, and Z, then add this
95100     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
95101     ** Report an error if any column mentioned in the USING clause is
95102     ** not contained in both tables to be joined.
95103     */
95104     if( pRight->pUsing ){
95105       IdList *pList = pRight->pUsing;
95106       for(j=0; j<pList->nId; j++){
95107         char *zName;     /* Name of the term in the USING clause */
95108         int iLeft;       /* Table on the left with matching column name */
95109         int iLeftCol;    /* Column number of matching column on the left */
95110         int iRightCol;   /* Column number of matching column on the right */
95111 
95112         zName = pList->a[j].zName;
95113         iRightCol = columnIndex(pRightTab, zName);
95114         if( iRightCol<0
95115          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
95116         ){
95117           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
95118             "not present in both tables", zName);
95119           return 1;
95120         }
95121         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
95122                      isOuter, &p->pWhere);
95123       }
95124     }
95125   }
95126   return 0;
95127 }
95128 
95129 /*
95130 ** Insert code into "v" that will push the record on the top of the
95131 ** stack into the sorter.
95132 */
95133 static void pushOntoSorter(
95134   Parse *pParse,         /* Parser context */
95135   ExprList *pOrderBy,    /* The ORDER BY clause */
95136   Select *pSelect,       /* The whole SELECT statement */
95137   int regData            /* Register holding data to be sorted */
95138 ){
95139   Vdbe *v = pParse->pVdbe;
95140   int nExpr = pOrderBy->nExpr;
95141   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
95142   int regRecord = sqlite3GetTempReg(pParse);
95143   int op;
95144   sqlite3ExprCacheClear(pParse);
95145   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
95146   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
95147   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
95148   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
95149   if( pSelect->selFlags & SF_UseSorter ){
95150     op = OP_SorterInsert;
95151   }else{
95152     op = OP_IdxInsert;
95153   }
95154   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
95155   sqlite3ReleaseTempReg(pParse, regRecord);
95156   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
95157   if( pSelect->iLimit ){
95158     int addr1, addr2;
95159     int iLimit;
95160     if( pSelect->iOffset ){
95161       iLimit = pSelect->iOffset+1;
95162     }else{
95163       iLimit = pSelect->iLimit;
95164     }
95165     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
95166     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
95167     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
95168     sqlite3VdbeJumpHere(v, addr1);
95169     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
95170     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
95171     sqlite3VdbeJumpHere(v, addr2);
95172   }
95173 }
95174 
95175 /*
95176 ** Add code to implement the OFFSET
95177 */
95178 static void codeOffset(
95179   Vdbe *v,          /* Generate code into this VM */
95180   Select *p,        /* The SELECT statement being coded */
95181   int iContinue     /* Jump here to skip the current record */
95182 ){
95183   if( p->iOffset && iContinue!=0 ){
95184     int addr;
95185     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
95186     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
95187     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
95188     VdbeComment((v, "skip OFFSET records"));
95189     sqlite3VdbeJumpHere(v, addr);
95190   }
95191 }
95192 
95193 /*
95194 ** Add code that will check to make sure the N registers starting at iMem
95195 ** form a distinct entry.  iTab is a sorting index that holds previously
95196 ** seen combinations of the N values.  A new entry is made in iTab
95197 ** if the current N values are new.
95198 **
95199 ** A jump to addrRepeat is made and the N+1 values are popped from the
95200 ** stack if the top N elements are not distinct.
95201 */
95202 static void codeDistinct(
95203   Parse *pParse,     /* Parsing and code generating context */
95204   int iTab,          /* A sorting index used to test for distinctness */
95205   int addrRepeat,    /* Jump to here if not distinct */
95206   int N,             /* Number of elements */
95207   int iMem           /* First element */
95208 ){
95209   Vdbe *v;
95210   int r1;
95211 
95212   v = pParse->pVdbe;
95213   r1 = sqlite3GetTempReg(pParse);
95214   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
95215   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
95216   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
95217   sqlite3ReleaseTempReg(pParse, r1);
95218 }
95219 
95220 #ifndef SQLITE_OMIT_SUBQUERY
95221 /*
95222 ** Generate an error message when a SELECT is used within a subexpression
95223 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
95224 ** column.  We do this in a subroutine because the error used to occur
95225 ** in multiple places.  (The error only occurs in one place now, but we
95226 ** retain the subroutine to minimize code disruption.)
95227 */
95228 static int checkForMultiColumnSelectError(
95229   Parse *pParse,       /* Parse context. */
95230   SelectDest *pDest,   /* Destination of SELECT results */
95231   int nExpr            /* Number of result columns returned by SELECT */
95232 ){
95233   int eDest = pDest->eDest;
95234   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
95235     sqlite3ErrorMsg(pParse, "only a single result allowed for "
95236        "a SELECT that is part of an expression");
95237     return 1;
95238   }else{
95239     return 0;
95240   }
95241 }
95242 #endif
95243 
95244 /*
95245 ** An instance of the following object is used to record information about
95246 ** how to process the DISTINCT keyword, to simplify passing that information
95247 ** into the selectInnerLoop() routine.
95248 */
95249 typedef struct DistinctCtx DistinctCtx;
95250 struct DistinctCtx {
95251   u8 isTnct;      /* True if the DISTINCT keyword is present */
95252   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
95253   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
95254   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
95255 };
95256 
95257 /*
95258 ** This routine generates the code for the inside of the inner loop
95259 ** of a SELECT.
95260 **
95261 ** If srcTab and nColumn are both zero, then the pEList expressions
95262 ** are evaluated in order to get the data for this row.  If nColumn>0
95263 ** then data is pulled from srcTab and pEList is used only to get the
95264 ** datatypes for each column.
95265 */
95266 static void selectInnerLoop(
95267   Parse *pParse,          /* The parser context */
95268   Select *p,              /* The complete select statement being coded */
95269   ExprList *pEList,       /* List of values being extracted */
95270   int srcTab,             /* Pull data from this table */
95271   int nColumn,            /* Number of columns in the source table */
95272   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
95273   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
95274   SelectDest *pDest,      /* How to dispose of the results */
95275   int iContinue,          /* Jump here to continue with next row */
95276   int iBreak              /* Jump here to break out of the inner loop */
95277 ){
95278   Vdbe *v = pParse->pVdbe;
95279   int i;
95280   int hasDistinct;        /* True if the DISTINCT keyword is present */
95281   int regResult;              /* Start of memory holding result set */
95282   int eDest = pDest->eDest;   /* How to dispose of results */
95283   int iParm = pDest->iSDParm; /* First argument to disposal method */
95284   int nResultCol;             /* Number of result columns */
95285 
95286   assert( v );
95287   if( NEVER(v==0) ) return;
95288   assert( pEList!=0 );
95289   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
95290   if( pOrderBy==0 && !hasDistinct ){
95291     codeOffset(v, p, iContinue);
95292   }
95293 
95294   /* Pull the requested columns.
95295   */
95296   if( nColumn>0 ){
95297     nResultCol = nColumn;
95298   }else{
95299     nResultCol = pEList->nExpr;
95300   }
95301   if( pDest->iSdst==0 ){
95302     pDest->iSdst = pParse->nMem+1;
95303     pDest->nSdst = nResultCol;
95304     pParse->nMem += nResultCol;
95305   }else{
95306     assert( pDest->nSdst==nResultCol );
95307   }
95308   regResult = pDest->iSdst;
95309   if( nColumn>0 ){
95310     for(i=0; i<nColumn; i++){
95311       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
95312     }
95313   }else if( eDest!=SRT_Exists ){
95314     /* If the destination is an EXISTS(...) expression, the actual
95315     ** values returned by the SELECT are not required.
95316     */
95317     sqlite3ExprCacheClear(pParse);
95318     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
95319   }
95320   nColumn = nResultCol;
95321 
95322   /* If the DISTINCT keyword was present on the SELECT statement
95323   ** and this row has been seen before, then do not make this row
95324   ** part of the result.
95325   */
95326   if( hasDistinct ){
95327     assert( pEList!=0 );
95328     assert( pEList->nExpr==nColumn );
95329     switch( pDistinct->eTnctType ){
95330       case WHERE_DISTINCT_ORDERED: {
95331         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
95332         int iJump;              /* Jump destination */
95333         int regPrev;            /* Previous row content */
95334 
95335         /* Allocate space for the previous row */
95336         regPrev = pParse->nMem+1;
95337         pParse->nMem += nColumn;
95338 
95339         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
95340         ** sets the MEM_Cleared bit on the first register of the
95341         ** previous value.  This will cause the OP_Ne below to always
95342         ** fail on the first iteration of the loop even if the first
95343         ** row is all NULLs.
95344         */
95345         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
95346         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
95347         pOp->opcode = OP_Null;
95348         pOp->p1 = 1;
95349         pOp->p2 = regPrev;
95350 
95351         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
95352         for(i=0; i<nColumn; i++){
95353           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
95354           if( i<nColumn-1 ){
95355             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
95356           }else{
95357             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
95358           }
95359           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
95360           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
95361         }
95362         assert( sqlite3VdbeCurrentAddr(v)==iJump );
95363         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
95364         break;
95365       }
95366 
95367       case WHERE_DISTINCT_UNIQUE: {
95368         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
95369         break;
95370       }
95371 
95372       default: {
95373         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
95374         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
95375         break;
95376       }
95377     }
95378     if( pOrderBy==0 ){
95379       codeOffset(v, p, iContinue);
95380     }
95381   }
95382 
95383   switch( eDest ){
95384     /* In this mode, write each query result to the key of the temporary
95385     ** table iParm.
95386     */
95387 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95388     case SRT_Union: {
95389       int r1;
95390       r1 = sqlite3GetTempReg(pParse);
95391       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95392       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95393       sqlite3ReleaseTempReg(pParse, r1);
95394       break;
95395     }
95396 
95397     /* Construct a record from the query result, but instead of
95398     ** saving that record, use it as a key to delete elements from
95399     ** the temporary table iParm.
95400     */
95401     case SRT_Except: {
95402       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
95403       break;
95404     }
95405 #endif
95406 
95407     /* Store the result as data using a unique key.
95408     */
95409     case SRT_Table:
95410     case SRT_EphemTab: {
95411       int r1 = sqlite3GetTempReg(pParse);
95412       testcase( eDest==SRT_Table );
95413       testcase( eDest==SRT_EphemTab );
95414       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95415       if( pOrderBy ){
95416         pushOntoSorter(pParse, pOrderBy, p, r1);
95417       }else{
95418         int r2 = sqlite3GetTempReg(pParse);
95419         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
95420         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
95421         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95422         sqlite3ReleaseTempReg(pParse, r2);
95423       }
95424       sqlite3ReleaseTempReg(pParse, r1);
95425       break;
95426     }
95427 
95428 #ifndef SQLITE_OMIT_SUBQUERY
95429     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
95430     ** then there should be a single item on the stack.  Write this
95431     ** item into the set table with bogus data.
95432     */
95433     case SRT_Set: {
95434       assert( nColumn==1 );
95435       pDest->affSdst =
95436                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
95437       if( pOrderBy ){
95438         /* At first glance you would think we could optimize out the
95439         ** ORDER BY in this case since the order of entries in the set
95440         ** does not matter.  But there might be a LIMIT clause, in which
95441         ** case the order does matter */
95442         pushOntoSorter(pParse, pOrderBy, p, regResult);
95443       }else{
95444         int r1 = sqlite3GetTempReg(pParse);
95445         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
95446         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
95447         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95448         sqlite3ReleaseTempReg(pParse, r1);
95449       }
95450       break;
95451     }
95452 
95453     /* If any row exist in the result set, record that fact and abort.
95454     */
95455     case SRT_Exists: {
95456       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
95457       /* The LIMIT clause will terminate the loop for us */
95458       break;
95459     }
95460 
95461     /* If this is a scalar select that is part of an expression, then
95462     ** store the results in the appropriate memory cell and break out
95463     ** of the scan loop.
95464     */
95465     case SRT_Mem: {
95466       assert( nColumn==1 );
95467       if( pOrderBy ){
95468         pushOntoSorter(pParse, pOrderBy, p, regResult);
95469       }else{
95470         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
95471         /* The LIMIT clause will jump out of the loop for us */
95472       }
95473       break;
95474     }
95475 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
95476 
95477     /* Send the data to the callback function or to a subroutine.  In the
95478     ** case of a subroutine, the subroutine itself is responsible for
95479     ** popping the data from the stack.
95480     */
95481     case SRT_Coroutine:
95482     case SRT_Output: {
95483       testcase( eDest==SRT_Coroutine );
95484       testcase( eDest==SRT_Output );
95485       if( pOrderBy ){
95486         int r1 = sqlite3GetTempReg(pParse);
95487         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95488         pushOntoSorter(pParse, pOrderBy, p, r1);
95489         sqlite3ReleaseTempReg(pParse, r1);
95490       }else if( eDest==SRT_Coroutine ){
95491         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95492       }else{
95493         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
95494         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
95495       }
95496       break;
95497     }
95498 
95499 #if !defined(SQLITE_OMIT_TRIGGER)
95500     /* Discard the results.  This is used for SELECT statements inside
95501     ** the body of a TRIGGER.  The purpose of such selects is to call
95502     ** user-defined functions that have side effects.  We do not care
95503     ** about the actual results of the select.
95504     */
95505     default: {
95506       assert( eDest==SRT_Discard );
95507       break;
95508     }
95509 #endif
95510   }
95511 
95512   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
95513   ** there is a sorter, in which case the sorter has already limited
95514   ** the output for us.
95515   */
95516   if( pOrderBy==0 && p->iLimit ){
95517     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
95518   }
95519 }
95520 
95521 /*
95522 ** Given an expression list, generate a KeyInfo structure that records
95523 ** the collating sequence for each expression in that expression list.
95524 **
95525 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
95526 ** KeyInfo structure is appropriate for initializing a virtual index to
95527 ** implement that clause.  If the ExprList is the result set of a SELECT
95528 ** then the KeyInfo structure is appropriate for initializing a virtual
95529 ** index to implement a DISTINCT test.
95530 **
95531 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
95532 ** function is responsible for seeing that this structure is eventually
95533 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
95534 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
95535 */
95536 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
95537   sqlite3 *db = pParse->db;
95538   int nExpr;
95539   KeyInfo *pInfo;
95540   struct ExprList_item *pItem;
95541   int i;
95542 
95543   nExpr = pList->nExpr;
95544   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
95545   if( pInfo ){
95546     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
95547     pInfo->nField = (u16)nExpr;
95548     pInfo->enc = ENC(db);
95549     pInfo->db = db;
95550     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
95551       CollSeq *pColl;
95552       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
95553       if( !pColl ){
95554         pColl = db->pDfltColl;
95555       }
95556       pInfo->aColl[i] = pColl;
95557       pInfo->aSortOrder[i] = pItem->sortOrder;
95558     }
95559   }
95560   return pInfo;
95561 }
95562 
95563 #ifndef SQLITE_OMIT_COMPOUND_SELECT
95564 /*
95565 ** Name of the connection operator, used for error messages.
95566 */
95567 static const char *selectOpName(int id){
95568   char *z;
95569   switch( id ){
95570     case TK_ALL:       z = "UNION ALL";   break;
95571     case TK_INTERSECT: z = "INTERSECT";   break;
95572     case TK_EXCEPT:    z = "EXCEPT";      break;
95573     default:           z = "UNION";       break;
95574   }
95575   return z;
95576 }
95577 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
95578 
95579 #ifndef SQLITE_OMIT_EXPLAIN
95580 /*
95581 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95582 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95583 ** where the caption is of the form:
95584 **
95585 **   "USE TEMP B-TREE FOR xxx"
95586 **
95587 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
95588 ** is determined by the zUsage argument.
95589 */
95590 static void explainTempTable(Parse *pParse, const char *zUsage){
95591   if( pParse->explain==2 ){
95592     Vdbe *v = pParse->pVdbe;
95593     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
95594     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95595   }
95596 }
95597 
95598 /*
95599 ** Assign expression b to lvalue a. A second, no-op, version of this macro
95600 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
95601 ** in sqlite3Select() to assign values to structure member variables that
95602 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
95603 ** code with #ifndef directives.
95604 */
95605 # define explainSetInteger(a, b) a = b
95606 
95607 #else
95608 /* No-op versions of the explainXXX() functions and macros. */
95609 # define explainTempTable(y,z)
95610 # define explainSetInteger(y,z)
95611 #endif
95612 
95613 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
95614 /*
95615 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95616 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95617 ** where the caption is of one of the two forms:
95618 **
95619 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
95620 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
95621 **
95622 ** where iSub1 and iSub2 are the integers passed as the corresponding
95623 ** function parameters, and op is the text representation of the parameter
95624 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
95625 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
95626 ** false, or the second form if it is true.
95627 */
95628 static void explainComposite(
95629   Parse *pParse,                  /* Parse context */
95630   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
95631   int iSub1,                      /* Subquery id 1 */
95632   int iSub2,                      /* Subquery id 2 */
95633   int bUseTmp                     /* True if a temp table was used */
95634 ){
95635   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
95636   if( pParse->explain==2 ){
95637     Vdbe *v = pParse->pVdbe;
95638     char *zMsg = sqlite3MPrintf(
95639         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95640         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95641     );
95642     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95643   }
95644 }
95645 #else
95646 /* No-op versions of the explainXXX() functions and macros. */
95647 # define explainComposite(v,w,x,y,z)
95648 #endif
95649 
95650 /*
95651 ** If the inner loop was generated using a non-null pOrderBy argument,
95652 ** then the results were placed in a sorter.  After the loop is terminated
95653 ** we need to run the sorter and output the results.  The following
95654 ** routine generates the code needed to do that.
95655 */
95656 static void generateSortTail(
95657   Parse *pParse,    /* Parsing context */
95658   Select *p,        /* The SELECT statement */
95659   Vdbe *v,          /* Generate code into this VDBE */
95660   int nColumn,      /* Number of columns of data */
95661   SelectDest *pDest /* Write the sorted results here */
95662 ){
95663   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
95664   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
95665   int addr;
95666   int iTab;
95667   int pseudoTab = 0;
95668   ExprList *pOrderBy = p->pOrderBy;
95669 
95670   int eDest = pDest->eDest;
95671   int iParm = pDest->iSDParm;
95672 
95673   int regRow;
95674   int regRowid;
95675 
95676   iTab = pOrderBy->iECursor;
95677   regRow = sqlite3GetTempReg(pParse);
95678   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95679     pseudoTab = pParse->nTab++;
95680     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95681     regRowid = 0;
95682   }else{
95683     regRowid = sqlite3GetTempReg(pParse);
95684   }
95685   if( p->selFlags & SF_UseSorter ){
95686     int regSortOut = ++pParse->nMem;
95687     int ptab2 = pParse->nTab++;
95688     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95689     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95690     codeOffset(v, p, addrContinue);
95691     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95692     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95693     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95694   }else{
95695     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95696     codeOffset(v, p, addrContinue);
95697     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95698   }
95699   switch( eDest ){
95700     case SRT_Table:
95701     case SRT_EphemTab: {
95702       testcase( eDest==SRT_Table );
95703       testcase( eDest==SRT_EphemTab );
95704       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95705       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95706       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95707       break;
95708     }
95709 #ifndef SQLITE_OMIT_SUBQUERY
95710     case SRT_Set: {
95711       assert( nColumn==1 );
95712       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
95713                         &pDest->affSdst, 1);
95714       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
95715       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95716       break;
95717     }
95718     case SRT_Mem: {
95719       assert( nColumn==1 );
95720       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
95721       /* The LIMIT clause will terminate the loop for us */
95722       break;
95723     }
95724 #endif
95725     default: {
95726       int i;
95727       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
95728       testcase( eDest==SRT_Output );
95729       testcase( eDest==SRT_Coroutine );
95730       for(i=0; i<nColumn; i++){
95731         assert( regRow!=pDest->iSdst+i );
95732         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
95733         if( i==0 ){
95734           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95735         }
95736       }
95737       if( eDest==SRT_Output ){
95738         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
95739         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
95740       }else{
95741         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
95742       }
95743       break;
95744     }
95745   }
95746   sqlite3ReleaseTempReg(pParse, regRow);
95747   sqlite3ReleaseTempReg(pParse, regRowid);
95748 
95749   /* The bottom of the loop
95750   */
95751   sqlite3VdbeResolveLabel(v, addrContinue);
95752   if( p->selFlags & SF_UseSorter ){
95753     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95754   }else{
95755     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
95756   }
95757   sqlite3VdbeResolveLabel(v, addrBreak);
95758   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95759     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95760   }
95761 }
95762 
95763 /*
95764 ** Return a pointer to a string containing the 'declaration type' of the
95765 ** expression pExpr. The string may be treated as static by the caller.
95766 **
95767 ** The declaration type is the exact datatype definition extracted from the
95768 ** original CREATE TABLE statement if the expression is a column. The
95769 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
95770 ** is considered a column can be complex in the presence of subqueries. The
95771 ** result-set expression in all of the following SELECT statements is
95772 ** considered a column by this function.
95773 **
95774 **   SELECT col FROM tbl;
95775 **   SELECT (SELECT col FROM tbl;
95776 **   SELECT (SELECT col FROM tbl);
95777 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
95778 **
95779 ** The declaration type for any expression other than a column is NULL.
95780 */
95781 static const char *columnType(
95782   NameContext *pNC,
95783   Expr *pExpr,
95784   const char **pzOriginDb,
95785   const char **pzOriginTab,
95786   const char **pzOriginCol
95787 ){
95788   char const *zType = 0;
95789   char const *zOriginDb = 0;
95790   char const *zOriginTab = 0;
95791   char const *zOriginCol = 0;
95792   int j;
95793   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95794 
95795   switch( pExpr->op ){
95796     case TK_AGG_COLUMN:
95797     case TK_COLUMN: {
95798       /* The expression is a column. Locate the table the column is being
95799       ** extracted from in NameContext.pSrcList. This table may be real
95800       ** database table or a subquery.
95801       */
95802       Table *pTab = 0;            /* Table structure column is extracted from */
95803       Select *pS = 0;             /* Select the column is extracted from */
95804       int iCol = pExpr->iColumn;  /* Index of column in pTab */
95805       testcase( pExpr->op==TK_AGG_COLUMN );
95806       testcase( pExpr->op==TK_COLUMN );
95807       while( pNC && !pTab ){
95808         SrcList *pTabList = pNC->pSrcList;
95809         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95810         if( j<pTabList->nSrc ){
95811           pTab = pTabList->a[j].pTab;
95812           pS = pTabList->a[j].pSelect;
95813         }else{
95814           pNC = pNC->pNext;
95815         }
95816       }
95817 
95818       if( pTab==0 ){
95819         /* At one time, code such as "SELECT new.x" within a trigger would
95820         ** cause this condition to run.  Since then, we have restructured how
95821         ** trigger code is generated and so this condition is no longer
95822         ** possible. However, it can still be true for statements like
95823         ** the following:
95824         **
95825         **   CREATE TABLE t1(col INTEGER);
95826         **   SELECT (SELECT t1.col) FROM FROM t1;
95827         **
95828         ** when columnType() is called on the expression "t1.col" in the
95829         ** sub-select. In this case, set the column type to NULL, even
95830         ** though it should really be "INTEGER".
95831         **
95832         ** This is not a problem, as the column type of "t1.col" is never
95833         ** used. When columnType() is called on the expression
95834         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95835         ** branch below.  */
95836         break;
95837       }
95838 
95839       assert( pTab && pExpr->pTab==pTab );
95840       if( pS ){
95841         /* The "table" is actually a sub-select or a view in the FROM clause
95842         ** of the SELECT statement. Return the declaration type and origin
95843         ** data for the result-set column of the sub-select.
95844         */
95845         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95846           /* If iCol is less than zero, then the expression requests the
95847           ** rowid of the sub-select or view. This expression is legal (see
95848           ** test case misc2.2.2) - it always evaluates to NULL.
95849           */
95850           NameContext sNC;
95851           Expr *p = pS->pEList->a[iCol].pExpr;
95852           sNC.pSrcList = pS->pSrc;
95853           sNC.pNext = pNC;
95854           sNC.pParse = pNC->pParse;
95855           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
95856         }
95857       }else if( ALWAYS(pTab->pSchema) ){
95858         /* A real table */
95859         assert( !pS );
95860         if( iCol<0 ) iCol = pTab->iPKey;
95861         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95862         if( iCol<0 ){
95863           zType = "INTEGER";
95864           zOriginCol = "rowid";
95865         }else{
95866           zType = pTab->aCol[iCol].zType;
95867           zOriginCol = pTab->aCol[iCol].zName;
95868         }
95869         zOriginTab = pTab->zName;
95870         if( pNC->pParse ){
95871           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95872           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95873         }
95874       }
95875       break;
95876     }
95877 #ifndef SQLITE_OMIT_SUBQUERY
95878     case TK_SELECT: {
95879       /* The expression is a sub-select. Return the declaration type and
95880       ** origin info for the single column in the result set of the SELECT
95881       ** statement.
95882       */
95883       NameContext sNC;
95884       Select *pS = pExpr->x.pSelect;
95885       Expr *p = pS->pEList->a[0].pExpr;
95886       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95887       sNC.pSrcList = pS->pSrc;
95888       sNC.pNext = pNC;
95889       sNC.pParse = pNC->pParse;
95890       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
95891       break;
95892     }
95893 #endif
95894   }
95895 
95896   if( pzOriginDb ){
95897     assert( pzOriginTab && pzOriginCol );
95898     *pzOriginDb = zOriginDb;
95899     *pzOriginTab = zOriginTab;
95900     *pzOriginCol = zOriginCol;
95901   }
95902   return zType;
95903 }
95904 
95905 /*
95906 ** Generate code that will tell the VDBE the declaration types of columns
95907 ** in the result set.
95908 */
95909 static void generateColumnTypes(
95910   Parse *pParse,      /* Parser context */
95911   SrcList *pTabList,  /* List of tables */
95912   ExprList *pEList    /* Expressions defining the result set */
95913 ){
95914 #ifndef SQLITE_OMIT_DECLTYPE
95915   Vdbe *v = pParse->pVdbe;
95916   int i;
95917   NameContext sNC;
95918   sNC.pSrcList = pTabList;
95919   sNC.pParse = pParse;
95920   for(i=0; i<pEList->nExpr; i++){
95921     Expr *p = pEList->a[i].pExpr;
95922     const char *zType;
95923 #ifdef SQLITE_ENABLE_COLUMN_METADATA
95924     const char *zOrigDb = 0;
95925     const char *zOrigTab = 0;
95926     const char *zOrigCol = 0;
95927     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95928 
95929     /* The vdbe must make its own copy of the column-type and other
95930     ** column specific strings, in case the schema is reset before this
95931     ** virtual machine is deleted.
95932     */
95933     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
95934     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
95935     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
95936 #else
95937     zType = columnType(&sNC, p, 0, 0, 0);
95938 #endif
95939     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
95940   }
95941 #endif /* SQLITE_OMIT_DECLTYPE */
95942 }
95943 
95944 /*
95945 ** Generate code that will tell the VDBE the names of columns
95946 ** in the result set.  This information is used to provide the
95947 ** azCol[] values in the callback.
95948 */
95949 static void generateColumnNames(
95950   Parse *pParse,      /* Parser context */
95951   SrcList *pTabList,  /* List of tables */
95952   ExprList *pEList    /* Expressions defining the result set */
95953 ){
95954   Vdbe *v = pParse->pVdbe;
95955   int i, j;
95956   sqlite3 *db = pParse->db;
95957   int fullNames, shortNames;
95958 
95959 #ifndef SQLITE_OMIT_EXPLAIN
95960   /* If this is an EXPLAIN, skip this step */
95961   if( pParse->explain ){
95962     return;
95963   }
95964 #endif
95965 
95966   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95967   pParse->colNamesSet = 1;
95968   fullNames = (db->flags & SQLITE_FullColNames)!=0;
95969   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
95970   sqlite3VdbeSetNumCols(v, pEList->nExpr);
95971   for(i=0; i<pEList->nExpr; i++){
95972     Expr *p;
95973     p = pEList->a[i].pExpr;
95974     if( NEVER(p==0) ) continue;
95975     if( pEList->a[i].zName ){
95976       char *zName = pEList->a[i].zName;
95977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
95978     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95979       Table *pTab;
95980       char *zCol;
95981       int iCol = p->iColumn;
95982       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95983         if( pTabList->a[j].iCursor==p->iTable ) break;
95984       }
95985       assert( j<pTabList->nSrc );
95986       pTab = pTabList->a[j].pTab;
95987       if( iCol<0 ) iCol = pTab->iPKey;
95988       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95989       if( iCol<0 ){
95990         zCol = "rowid";
95991       }else{
95992         zCol = pTab->aCol[iCol].zName;
95993       }
95994       if( !shortNames && !fullNames ){
95995         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
95996             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95997       }else if( fullNames ){
95998         char *zName = 0;
95999         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
96000         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
96001       }else{
96002         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
96003       }
96004     }else{
96005       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
96006           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
96007     }
96008   }
96009   generateColumnTypes(pParse, pTabList, pEList);
96010 }
96011 
96012 /*
96013 ** Given a an expression list (which is really the list of expressions
96014 ** that form the result set of a SELECT statement) compute appropriate
96015 ** column names for a table that would hold the expression list.
96016 **
96017 ** All column names will be unique.
96018 **
96019 ** Only the column names are computed.  Column.zType, Column.zColl,
96020 ** and other fields of Column are zeroed.
96021 **
96022 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
96023 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
96024 */
96025 static int selectColumnsFromExprList(
96026   Parse *pParse,          /* Parsing context */
96027   ExprList *pEList,       /* Expr list from which to derive column names */
96028   i16 *pnCol,             /* Write the number of columns here */
96029   Column **paCol          /* Write the new column list here */
96030 ){
96031   sqlite3 *db = pParse->db;   /* Database connection */
96032   int i, j;                   /* Loop counters */
96033   int cnt;                    /* Index added to make the name unique */
96034   Column *aCol, *pCol;        /* For looping over result columns */
96035   int nCol;                   /* Number of columns in the result set */
96036   Expr *p;                    /* Expression for a single result column */
96037   char *zName;                /* Column name */
96038   int nName;                  /* Size of name in zName[] */
96039 
96040   if( pEList ){
96041     nCol = pEList->nExpr;
96042     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
96043     testcase( aCol==0 );
96044   }else{
96045     nCol = 0;
96046     aCol = 0;
96047   }
96048   *pnCol = nCol;
96049   *paCol = aCol;
96050 
96051   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
96052     /* Get an appropriate name for the column
96053     */
96054     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
96055     if( (zName = pEList->a[i].zName)!=0 ){
96056       /* If the column contains an "AS <name>" phrase, use <name> as the name */
96057       zName = sqlite3DbStrDup(db, zName);
96058     }else{
96059       Expr *pColExpr = p;  /* The expression that is the result column name */
96060       Table *pTab;         /* Table associated with this expression */
96061       while( pColExpr->op==TK_DOT ){
96062         pColExpr = pColExpr->pRight;
96063         assert( pColExpr!=0 );
96064       }
96065       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
96066         /* For columns use the column name name */
96067         int iCol = pColExpr->iColumn;
96068         pTab = pColExpr->pTab;
96069         if( iCol<0 ) iCol = pTab->iPKey;
96070         zName = sqlite3MPrintf(db, "%s",
96071                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
96072       }else if( pColExpr->op==TK_ID ){
96073         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
96074         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
96075       }else{
96076         /* Use the original text of the column expression as its name */
96077         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
96078       }
96079     }
96080     if( db->mallocFailed ){
96081       sqlite3DbFree(db, zName);
96082       break;
96083     }
96084 
96085     /* Make sure the column name is unique.  If the name is not unique,
96086     ** append a integer to the name so that it becomes unique.
96087     */
96088     nName = sqlite3Strlen30(zName);
96089     for(j=cnt=0; j<i; j++){
96090       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
96091         char *zNewName;
96092         int k;
96093         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
96094         if( zName[k]==':' ) nName = k;
96095         zName[nName] = 0;
96096         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
96097         sqlite3DbFree(db, zName);
96098         zName = zNewName;
96099         j = -1;
96100         if( zName==0 ) break;
96101       }
96102     }
96103     pCol->zName = zName;
96104   }
96105   if( db->mallocFailed ){
96106     for(j=0; j<i; j++){
96107       sqlite3DbFree(db, aCol[j].zName);
96108     }
96109     sqlite3DbFree(db, aCol);
96110     *paCol = 0;
96111     *pnCol = 0;
96112     return SQLITE_NOMEM;
96113   }
96114   return SQLITE_OK;
96115 }
96116 
96117 /*
96118 ** Add type and collation information to a column list based on
96119 ** a SELECT statement.
96120 **
96121 ** The column list presumably came from selectColumnNamesFromExprList().
96122 ** The column list has only names, not types or collations.  This
96123 ** routine goes through and adds the types and collations.
96124 **
96125 ** This routine requires that all identifiers in the SELECT
96126 ** statement be resolved.
96127 */
96128 static void selectAddColumnTypeAndCollation(
96129   Parse *pParse,        /* Parsing contexts */
96130   int nCol,             /* Number of columns */
96131   Column *aCol,         /* List of columns */
96132   Select *pSelect       /* SELECT used to determine types and collations */
96133 ){
96134   sqlite3 *db = pParse->db;
96135   NameContext sNC;
96136   Column *pCol;
96137   CollSeq *pColl;
96138   int i;
96139   Expr *p;
96140   struct ExprList_item *a;
96141 
96142   assert( pSelect!=0 );
96143   assert( (pSelect->selFlags & SF_Resolved)!=0 );
96144   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
96145   if( db->mallocFailed ) return;
96146   memset(&sNC, 0, sizeof(sNC));
96147   sNC.pSrcList = pSelect->pSrc;
96148   a = pSelect->pEList->a;
96149   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
96150     p = a[i].pExpr;
96151     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
96152     pCol->affinity = sqlite3ExprAffinity(p);
96153     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
96154     pColl = sqlite3ExprCollSeq(pParse, p);
96155     if( pColl ){
96156       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
96157     }
96158   }
96159 }
96160 
96161 /*
96162 ** Given a SELECT statement, generate a Table structure that describes
96163 ** the result set of that SELECT.
96164 */
96165 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
96166   Table *pTab;
96167   sqlite3 *db = pParse->db;
96168   int savedFlags;
96169 
96170   savedFlags = db->flags;
96171   db->flags &= ~SQLITE_FullColNames;
96172   db->flags |= SQLITE_ShortColNames;
96173   sqlite3SelectPrep(pParse, pSelect, 0);
96174   if( pParse->nErr ) return 0;
96175   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
96176   db->flags = savedFlags;
96177   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
96178   if( pTab==0 ){
96179     return 0;
96180   }
96181   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
96182   ** is disabled */
96183   assert( db->lookaside.bEnabled==0 );
96184   pTab->nRef = 1;
96185   pTab->zName = 0;
96186   pTab->nRowEst = 1000000;
96187   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
96188   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
96189   pTab->iPKey = -1;
96190   if( db->mallocFailed ){
96191     sqlite3DeleteTable(db, pTab);
96192     return 0;
96193   }
96194   return pTab;
96195 }
96196 
96197 /*
96198 ** Get a VDBE for the given parser context.  Create a new one if necessary.
96199 ** If an error occurs, return NULL and leave a message in pParse.
96200 */
96201 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
96202   Vdbe *v = pParse->pVdbe;
96203   if( v==0 ){
96204     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
96205 #ifndef SQLITE_OMIT_TRACE
96206     if( v ){
96207       sqlite3VdbeAddOp0(v, OP_Trace);
96208     }
96209 #endif
96210   }
96211   return v;
96212 }
96213 
96214 
96215 /*
96216 ** Compute the iLimit and iOffset fields of the SELECT based on the
96217 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
96218 ** that appear in the original SQL statement after the LIMIT and OFFSET
96219 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
96220 ** are the integer memory register numbers for counters used to compute
96221 ** the limit and offset.  If there is no limit and/or offset, then
96222 ** iLimit and iOffset are negative.
96223 **
96224 ** This routine changes the values of iLimit and iOffset only if
96225 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
96226 ** iOffset should have been preset to appropriate default values
96227 ** (usually but not always -1) prior to calling this routine.
96228 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
96229 ** redefined.  The UNION ALL operator uses this property to force
96230 ** the reuse of the same limit and offset registers across multiple
96231 ** SELECT statements.
96232 */
96233 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
96234   Vdbe *v = 0;
96235   int iLimit = 0;
96236   int iOffset;
96237   int addr1, n;
96238   if( p->iLimit ) return;
96239 
96240   /*
96241   ** "LIMIT -1" always shows all rows.  There is some
96242   ** contraversy about what the correct behavior should be.
96243   ** The current implementation interprets "LIMIT 0" to mean
96244   ** no rows.
96245   */
96246   sqlite3ExprCacheClear(pParse);
96247   assert( p->pOffset==0 || p->pLimit!=0 );
96248   if( p->pLimit ){
96249     p->iLimit = iLimit = ++pParse->nMem;
96250     v = sqlite3GetVdbe(pParse);
96251     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
96252     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
96253       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
96254       VdbeComment((v, "LIMIT counter"));
96255       if( n==0 ){
96256         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
96257       }else{
96258         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
96259       }
96260     }else{
96261       sqlite3ExprCode(pParse, p->pLimit, iLimit);
96262       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
96263       VdbeComment((v, "LIMIT counter"));
96264       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
96265     }
96266     if( p->pOffset ){
96267       p->iOffset = iOffset = ++pParse->nMem;
96268       pParse->nMem++;   /* Allocate an extra register for limit+offset */
96269       sqlite3ExprCode(pParse, p->pOffset, iOffset);
96270       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
96271       VdbeComment((v, "OFFSET counter"));
96272       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
96273       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
96274       sqlite3VdbeJumpHere(v, addr1);
96275       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
96276       VdbeComment((v, "LIMIT+OFFSET"));
96277       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
96278       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
96279       sqlite3VdbeJumpHere(v, addr1);
96280     }
96281   }
96282 }
96283 
96284 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96285 /*
96286 ** Return the appropriate collating sequence for the iCol-th column of
96287 ** the result set for the compound-select statement "p".  Return NULL if
96288 ** the column has no default collating sequence.
96289 **
96290 ** The collating sequence for the compound select is taken from the
96291 ** left-most term of the select that has a collating sequence.
96292 */
96293 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
96294   CollSeq *pRet;
96295   if( p->pPrior ){
96296     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
96297   }else{
96298     pRet = 0;
96299   }
96300   assert( iCol>=0 );
96301   if( pRet==0 && iCol<p->pEList->nExpr ){
96302     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
96303   }
96304   return pRet;
96305 }
96306 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96307 
96308 /* Forward reference */
96309 static int multiSelectOrderBy(
96310   Parse *pParse,        /* Parsing context */
96311   Select *p,            /* The right-most of SELECTs to be coded */
96312   SelectDest *pDest     /* What to do with query results */
96313 );
96314 
96315 
96316 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96317 /*
96318 ** This routine is called to process a compound query form from
96319 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
96320 ** INTERSECT
96321 **
96322 ** "p" points to the right-most of the two queries.  the query on the
96323 ** left is p->pPrior.  The left query could also be a compound query
96324 ** in which case this routine will be called recursively.
96325 **
96326 ** The results of the total query are to be written into a destination
96327 ** of type eDest with parameter iParm.
96328 **
96329 ** Example 1:  Consider a three-way compound SQL statement.
96330 **
96331 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
96332 **
96333 ** This statement is parsed up as follows:
96334 **
96335 **     SELECT c FROM t3
96336 **      |
96337 **      `----->  SELECT b FROM t2
96338 **                |
96339 **                `------>  SELECT a FROM t1
96340 **
96341 ** The arrows in the diagram above represent the Select.pPrior pointer.
96342 ** So if this routine is called with p equal to the t3 query, then
96343 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
96344 **
96345 ** Notice that because of the way SQLite parses compound SELECTs, the
96346 ** individual selects always group from left to right.
96347 */
96348 static int multiSelect(
96349   Parse *pParse,        /* Parsing context */
96350   Select *p,            /* The right-most of SELECTs to be coded */
96351   SelectDest *pDest     /* What to do with query results */
96352 ){
96353   int rc = SQLITE_OK;   /* Success code from a subroutine */
96354   Select *pPrior;       /* Another SELECT immediately to our left */
96355   Vdbe *v;              /* Generate code to this VDBE */
96356   SelectDest dest;      /* Alternative data destination */
96357   Select *pDelete = 0;  /* Chain of simple selects to delete */
96358   sqlite3 *db;          /* Database connection */
96359 #ifndef SQLITE_OMIT_EXPLAIN
96360   int iSub1;            /* EQP id of left-hand query */
96361   int iSub2;            /* EQP id of right-hand query */
96362 #endif
96363 
96364   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
96365   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
96366   */
96367   assert( p && p->pPrior );  /* Calling function guarantees this much */
96368   db = pParse->db;
96369   pPrior = p->pPrior;
96370   assert( pPrior->pRightmost!=pPrior );
96371   assert( pPrior->pRightmost==p->pRightmost );
96372   dest = *pDest;
96373   if( pPrior->pOrderBy ){
96374     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
96375       selectOpName(p->op));
96376     rc = 1;
96377     goto multi_select_end;
96378   }
96379   if( pPrior->pLimit ){
96380     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
96381       selectOpName(p->op));
96382     rc = 1;
96383     goto multi_select_end;
96384   }
96385 
96386   v = sqlite3GetVdbe(pParse);
96387   assert( v!=0 );  /* The VDBE already created by calling function */
96388 
96389   /* Create the destination temporary table if necessary
96390   */
96391   if( dest.eDest==SRT_EphemTab ){
96392     assert( p->pEList );
96393     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
96394     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96395     dest.eDest = SRT_Table;
96396   }
96397 
96398   /* Make sure all SELECTs in the statement have the same number of elements
96399   ** in their result sets.
96400   */
96401   assert( p->pEList && pPrior->pEList );
96402   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
96403     if( p->selFlags & SF_Values ){
96404       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
96405     }else{
96406       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
96407         " do not have the same number of result columns", selectOpName(p->op));
96408     }
96409     rc = 1;
96410     goto multi_select_end;
96411   }
96412 
96413   /* Compound SELECTs that have an ORDER BY clause are handled separately.
96414   */
96415   if( p->pOrderBy ){
96416     return multiSelectOrderBy(pParse, p, pDest);
96417   }
96418 
96419   /* Generate code for the left and right SELECT statements.
96420   */
96421   switch( p->op ){
96422     case TK_ALL: {
96423       int addr = 0;
96424       int nLimit;
96425       assert( !pPrior->pLimit );
96426       pPrior->iLimit = p->iLimit;
96427       pPrior->iOffset = p->iOffset;
96428       pPrior->pLimit = p->pLimit;
96429       pPrior->pOffset = p->pOffset;
96430       explainSetInteger(iSub1, pParse->iNextSelectId);
96431       rc = sqlite3Select(pParse, pPrior, &dest);
96432       p->pLimit = 0;
96433       p->pOffset = 0;
96434       if( rc ){
96435         goto multi_select_end;
96436       }
96437       p->pPrior = 0;
96438       p->iLimit = pPrior->iLimit;
96439       p->iOffset = pPrior->iOffset;
96440       if( p->iLimit ){
96441         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
96442         VdbeComment((v, "Jump ahead if LIMIT reached"));
96443       }
96444       explainSetInteger(iSub2, pParse->iNextSelectId);
96445       rc = sqlite3Select(pParse, p, &dest);
96446       testcase( rc!=SQLITE_OK );
96447       pDelete = p->pPrior;
96448       p->pPrior = pPrior;
96449       p->nSelectRow += pPrior->nSelectRow;
96450       if( pPrior->pLimit
96451        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
96452        && p->nSelectRow > (double)nLimit
96453       ){
96454         p->nSelectRow = (double)nLimit;
96455       }
96456       if( addr ){
96457         sqlite3VdbeJumpHere(v, addr);
96458       }
96459       break;
96460     }
96461     case TK_EXCEPT:
96462     case TK_UNION: {
96463       int unionTab;    /* Cursor number of the temporary table holding result */
96464       u8 op = 0;       /* One of the SRT_ operations to apply to self */
96465       int priorOp;     /* The SRT_ operation to apply to prior selects */
96466       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
96467       int addr;
96468       SelectDest uniondest;
96469 
96470       testcase( p->op==TK_EXCEPT );
96471       testcase( p->op==TK_UNION );
96472       priorOp = SRT_Union;
96473       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
96474         /* We can reuse a temporary table generated by a SELECT to our
96475         ** right.
96476         */
96477         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
96478                                      ** of a 3-way or more compound */
96479         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
96480         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
96481         unionTab = dest.iSDParm;
96482       }else{
96483         /* We will need to create our own temporary table to hold the
96484         ** intermediate results.
96485         */
96486         unionTab = pParse->nTab++;
96487         assert( p->pOrderBy==0 );
96488         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
96489         assert( p->addrOpenEphm[0] == -1 );
96490         p->addrOpenEphm[0] = addr;
96491         p->pRightmost->selFlags |= SF_UsesEphemeral;
96492         assert( p->pEList );
96493       }
96494 
96495       /* Code the SELECT statements to our left
96496       */
96497       assert( !pPrior->pOrderBy );
96498       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
96499       explainSetInteger(iSub1, pParse->iNextSelectId);
96500       rc = sqlite3Select(pParse, pPrior, &uniondest);
96501       if( rc ){
96502         goto multi_select_end;
96503       }
96504 
96505       /* Code the current SELECT statement
96506       */
96507       if( p->op==TK_EXCEPT ){
96508         op = SRT_Except;
96509       }else{
96510         assert( p->op==TK_UNION );
96511         op = SRT_Union;
96512       }
96513       p->pPrior = 0;
96514       pLimit = p->pLimit;
96515       p->pLimit = 0;
96516       pOffset = p->pOffset;
96517       p->pOffset = 0;
96518       uniondest.eDest = op;
96519       explainSetInteger(iSub2, pParse->iNextSelectId);
96520       rc = sqlite3Select(pParse, p, &uniondest);
96521       testcase( rc!=SQLITE_OK );
96522       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
96523       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
96524       sqlite3ExprListDelete(db, p->pOrderBy);
96525       pDelete = p->pPrior;
96526       p->pPrior = pPrior;
96527       p->pOrderBy = 0;
96528       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
96529       sqlite3ExprDelete(db, p->pLimit);
96530       p->pLimit = pLimit;
96531       p->pOffset = pOffset;
96532       p->iLimit = 0;
96533       p->iOffset = 0;
96534 
96535       /* Convert the data in the temporary table into whatever form
96536       ** it is that we currently need.
96537       */
96538       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
96539       if( dest.eDest!=priorOp ){
96540         int iCont, iBreak, iStart;
96541         assert( p->pEList );
96542         if( dest.eDest==SRT_Output ){
96543           Select *pFirst = p;
96544           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96545           generateColumnNames(pParse, 0, pFirst->pEList);
96546         }
96547         iBreak = sqlite3VdbeMakeLabel(v);
96548         iCont = sqlite3VdbeMakeLabel(v);
96549         computeLimitRegisters(pParse, p, iBreak);
96550         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
96551         iStart = sqlite3VdbeCurrentAddr(v);
96552         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
96553                         0, 0, &dest, iCont, iBreak);
96554         sqlite3VdbeResolveLabel(v, iCont);
96555         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
96556         sqlite3VdbeResolveLabel(v, iBreak);
96557         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
96558       }
96559       break;
96560     }
96561     default: assert( p->op==TK_INTERSECT ); {
96562       int tab1, tab2;
96563       int iCont, iBreak, iStart;
96564       Expr *pLimit, *pOffset;
96565       int addr;
96566       SelectDest intersectdest;
96567       int r1;
96568 
96569       /* INTERSECT is different from the others since it requires
96570       ** two temporary tables.  Hence it has its own case.  Begin
96571       ** by allocating the tables we will need.
96572       */
96573       tab1 = pParse->nTab++;
96574       tab2 = pParse->nTab++;
96575       assert( p->pOrderBy==0 );
96576 
96577       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
96578       assert( p->addrOpenEphm[0] == -1 );
96579       p->addrOpenEphm[0] = addr;
96580       p->pRightmost->selFlags |= SF_UsesEphemeral;
96581       assert( p->pEList );
96582 
96583       /* Code the SELECTs to our left into temporary table "tab1".
96584       */
96585       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
96586       explainSetInteger(iSub1, pParse->iNextSelectId);
96587       rc = sqlite3Select(pParse, pPrior, &intersectdest);
96588       if( rc ){
96589         goto multi_select_end;
96590       }
96591 
96592       /* Code the current SELECT into temporary table "tab2"
96593       */
96594       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
96595       assert( p->addrOpenEphm[1] == -1 );
96596       p->addrOpenEphm[1] = addr;
96597       p->pPrior = 0;
96598       pLimit = p->pLimit;
96599       p->pLimit = 0;
96600       pOffset = p->pOffset;
96601       p->pOffset = 0;
96602       intersectdest.iSDParm = tab2;
96603       explainSetInteger(iSub2, pParse->iNextSelectId);
96604       rc = sqlite3Select(pParse, p, &intersectdest);
96605       testcase( rc!=SQLITE_OK );
96606       pDelete = p->pPrior;
96607       p->pPrior = pPrior;
96608       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96609       sqlite3ExprDelete(db, p->pLimit);
96610       p->pLimit = pLimit;
96611       p->pOffset = pOffset;
96612 
96613       /* Generate code to take the intersection of the two temporary
96614       ** tables.
96615       */
96616       assert( p->pEList );
96617       if( dest.eDest==SRT_Output ){
96618         Select *pFirst = p;
96619         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96620         generateColumnNames(pParse, 0, pFirst->pEList);
96621       }
96622       iBreak = sqlite3VdbeMakeLabel(v);
96623       iCont = sqlite3VdbeMakeLabel(v);
96624       computeLimitRegisters(pParse, p, iBreak);
96625       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
96626       r1 = sqlite3GetTempReg(pParse);
96627       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
96628       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
96629       sqlite3ReleaseTempReg(pParse, r1);
96630       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
96631                       0, 0, &dest, iCont, iBreak);
96632       sqlite3VdbeResolveLabel(v, iCont);
96633       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
96634       sqlite3VdbeResolveLabel(v, iBreak);
96635       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
96636       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
96637       break;
96638     }
96639   }
96640 
96641   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
96642 
96643   /* Compute collating sequences used by
96644   ** temporary tables needed to implement the compound select.
96645   ** Attach the KeyInfo structure to all temporary tables.
96646   **
96647   ** This section is run by the right-most SELECT statement only.
96648   ** SELECT statements to the left always skip this part.  The right-most
96649   ** SELECT might also skip this part if it has no ORDER BY clause and
96650   ** no temp tables are required.
96651   */
96652   if( p->selFlags & SF_UsesEphemeral ){
96653     int i;                        /* Loop counter */
96654     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96655     Select *pLoop;                /* For looping through SELECT statements */
96656     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96657     int nCol;                     /* Number of columns in result set */
96658 
96659     assert( p->pRightmost==p );
96660     nCol = p->pEList->nExpr;
96661     pKeyInfo = sqlite3DbMallocZero(db,
96662                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96663     if( !pKeyInfo ){
96664       rc = SQLITE_NOMEM;
96665       goto multi_select_end;
96666     }
96667 
96668     pKeyInfo->enc = ENC(db);
96669     pKeyInfo->nField = (u16)nCol;
96670 
96671     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96672       *apColl = multiSelectCollSeq(pParse, p, i);
96673       if( 0==*apColl ){
96674         *apColl = db->pDfltColl;
96675       }
96676     }
96677     pKeyInfo->aSortOrder = (u8*)apColl;
96678 
96679     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96680       for(i=0; i<2; i++){
96681         int addr = pLoop->addrOpenEphm[i];
96682         if( addr<0 ){
96683           /* If [0] is unused then [1] is also unused.  So we can
96684           ** always safely abort as soon as the first unused slot is found */
96685           assert( pLoop->addrOpenEphm[1]<0 );
96686           break;
96687         }
96688         sqlite3VdbeChangeP2(v, addr, nCol);
96689         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96690         pLoop->addrOpenEphm[i] = -1;
96691       }
96692     }
96693     sqlite3DbFree(db, pKeyInfo);
96694   }
96695 
96696 multi_select_end:
96697   pDest->iSdst = dest.iSdst;
96698   pDest->nSdst = dest.nSdst;
96699   sqlite3SelectDelete(db, pDelete);
96700   return rc;
96701 }
96702 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96703 
96704 /*
96705 ** Code an output subroutine for a coroutine implementation of a
96706 ** SELECT statment.
96707 **
96708 ** The data to be output is contained in pIn->iSdst.  There are
96709 ** pIn->nSdst columns to be output.  pDest is where the output should
96710 ** be sent.
96711 **
96712 ** regReturn is the number of the register holding the subroutine
96713 ** return address.
96714 **
96715 ** If regPrev>0 then it is the first register in a vector that
96716 ** records the previous output.  mem[regPrev] is a flag that is false
96717 ** if there has been no previous output.  If regPrev>0 then code is
96718 ** generated to suppress duplicates.  pKeyInfo is used for comparing
96719 ** keys.
96720 **
96721 ** If the LIMIT found in p->iLimit is reached, jump immediately to
96722 ** iBreak.
96723 */
96724 static int generateOutputSubroutine(
96725   Parse *pParse,          /* Parsing context */
96726   Select *p,              /* The SELECT statement */
96727   SelectDest *pIn,        /* Coroutine supplying data */
96728   SelectDest *pDest,      /* Where to send the data */
96729   int regReturn,          /* The return address register */
96730   int regPrev,            /* Previous result register.  No uniqueness if 0 */
96731   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96732   int p4type,             /* The p4 type for pKeyInfo */
96733   int iBreak              /* Jump here if we hit the LIMIT */
96734 ){
96735   Vdbe *v = pParse->pVdbe;
96736   int iContinue;
96737   int addr;
96738 
96739   addr = sqlite3VdbeCurrentAddr(v);
96740   iContinue = sqlite3VdbeMakeLabel(v);
96741 
96742   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
96743   */
96744   if( regPrev ){
96745     int j1, j2;
96746     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
96747     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
96748                               (char*)pKeyInfo, p4type);
96749     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96750     sqlite3VdbeJumpHere(v, j1);
96751     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
96752     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96753   }
96754   if( pParse->db->mallocFailed ) return 0;
96755 
96756   /* Suppress the first OFFSET entries if there is an OFFSET clause
96757   */
96758   codeOffset(v, p, iContinue);
96759 
96760   switch( pDest->eDest ){
96761     /* Store the result as data using a unique key.
96762     */
96763     case SRT_Table:
96764     case SRT_EphemTab: {
96765       int r1 = sqlite3GetTempReg(pParse);
96766       int r2 = sqlite3GetTempReg(pParse);
96767       testcase( pDest->eDest==SRT_Table );
96768       testcase( pDest->eDest==SRT_EphemTab );
96769       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
96770       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
96771       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
96772       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96773       sqlite3ReleaseTempReg(pParse, r2);
96774       sqlite3ReleaseTempReg(pParse, r1);
96775       break;
96776     }
96777 
96778 #ifndef SQLITE_OMIT_SUBQUERY
96779     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96780     ** then there should be a single item on the stack.  Write this
96781     ** item into the set table with bogus data.
96782     */
96783     case SRT_Set: {
96784       int r1;
96785       assert( pIn->nSdst==1 );
96786       pDest->affSdst =
96787          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
96788       r1 = sqlite3GetTempReg(pParse);
96789       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
96790       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
96791       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
96792       sqlite3ReleaseTempReg(pParse, r1);
96793       break;
96794     }
96795 
96796 #if 0  /* Never occurs on an ORDER BY query */
96797     /* If any row exist in the result set, record that fact and abort.
96798     */
96799     case SRT_Exists: {
96800       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
96801       /* The LIMIT clause will terminate the loop for us */
96802       break;
96803     }
96804 #endif
96805 
96806     /* If this is a scalar select that is part of an expression, then
96807     ** store the results in the appropriate memory cell and break out
96808     ** of the scan loop.
96809     */
96810     case SRT_Mem: {
96811       assert( pIn->nSdst==1 );
96812       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
96813       /* The LIMIT clause will jump out of the loop for us */
96814       break;
96815     }
96816 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96817 
96818     /* The results are stored in a sequence of registers
96819     ** starting at pDest->iSdst.  Then the co-routine yields.
96820     */
96821     case SRT_Coroutine: {
96822       if( pDest->iSdst==0 ){
96823         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
96824         pDest->nSdst = pIn->nSdst;
96825       }
96826       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
96827       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
96828       break;
96829     }
96830 
96831     /* If none of the above, then the result destination must be
96832     ** SRT_Output.  This routine is never called with any other
96833     ** destination other than the ones handled above or SRT_Output.
96834     **
96835     ** For SRT_Output, results are stored in a sequence of registers.
96836     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
96837     ** return the next row of result.
96838     */
96839     default: {
96840       assert( pDest->eDest==SRT_Output );
96841       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
96842       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
96843       break;
96844     }
96845   }
96846 
96847   /* Jump to the end of the loop if the LIMIT is reached.
96848   */
96849   if( p->iLimit ){
96850     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96851   }
96852 
96853   /* Generate the subroutine return
96854   */
96855   sqlite3VdbeResolveLabel(v, iContinue);
96856   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
96857 
96858   return addr;
96859 }
96860 
96861 /*
96862 ** Alternative compound select code generator for cases when there
96863 ** is an ORDER BY clause.
96864 **
96865 ** We assume a query of the following form:
96866 **
96867 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96868 **
96869 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96870 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
96871 ** co-routines.  Then run the co-routines in parallel and merge the results
96872 ** into the output.  In addition to the two coroutines (called selectA and
96873 ** selectB) there are 7 subroutines:
96874 **
96875 **    outA:    Move the output of the selectA coroutine into the output
96876 **             of the compound query.
96877 **
96878 **    outB:    Move the output of the selectB coroutine into the output
96879 **             of the compound query.  (Only generated for UNION and
96880 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96881 **             appears only in B.)
96882 **
96883 **    AltB:    Called when there is data from both coroutines and A<B.
96884 **
96885 **    AeqB:    Called when there is data from both coroutines and A==B.
96886 **
96887 **    AgtB:    Called when there is data from both coroutines and A>B.
96888 **
96889 **    EofA:    Called when data is exhausted from selectA.
96890 **
96891 **    EofB:    Called when data is exhausted from selectB.
96892 **
96893 ** The implementation of the latter five subroutines depend on which
96894 ** <operator> is used:
96895 **
96896 **
96897 **             UNION ALL         UNION            EXCEPT          INTERSECT
96898 **          -------------  -----------------  --------------  -----------------
96899 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96900 **
96901 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96902 **
96903 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96904 **
96905 **   EofA:   outB, nextB      outB, nextB          halt             halt
96906 **
96907 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96908 **
96909 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96910 ** causes an immediate jump to EofA and an EOF on B following nextB causes
96911 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96912 ** following nextX causes a jump to the end of the select processing.
96913 **
96914 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96915 ** within the output subroutine.  The regPrev register set holds the previously
96916 ** output value.  A comparison is made against this value and the output
96917 ** is skipped if the next results would be the same as the previous.
96918 **
96919 ** The implementation plan is to implement the two coroutines and seven
96920 ** subroutines first, then put the control logic at the bottom.  Like this:
96921 **
96922 **          goto Init
96923 **     coA: coroutine for left query (A)
96924 **     coB: coroutine for right query (B)
96925 **    outA: output one row of A
96926 **    outB: output one row of B (UNION and UNION ALL only)
96927 **    EofA: ...
96928 **    EofB: ...
96929 **    AltB: ...
96930 **    AeqB: ...
96931 **    AgtB: ...
96932 **    Init: initialize coroutine registers
96933 **          yield coA
96934 **          if eof(A) goto EofA
96935 **          yield coB
96936 **          if eof(B) goto EofB
96937 **    Cmpr: Compare A, B
96938 **          Jump AltB, AeqB, AgtB
96939 **     End: ...
96940 **
96941 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96942 ** actually called using Gosub and they do not Return.  EofA and EofB loop
96943 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96944 ** and AgtB jump to either L2 or to one of EofA or EofB.
96945 */
96946 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96947 static int multiSelectOrderBy(
96948   Parse *pParse,        /* Parsing context */
96949   Select *p,            /* The right-most of SELECTs to be coded */
96950   SelectDest *pDest     /* What to do with query results */
96951 ){
96952   int i, j;             /* Loop counters */
96953   Select *pPrior;       /* Another SELECT immediately to our left */
96954   Vdbe *v;              /* Generate code to this VDBE */
96955   SelectDest destA;     /* Destination for coroutine A */
96956   SelectDest destB;     /* Destination for coroutine B */
96957   int regAddrA;         /* Address register for select-A coroutine */
96958   int regEofA;          /* Flag to indicate when select-A is complete */
96959   int regAddrB;         /* Address register for select-B coroutine */
96960   int regEofB;          /* Flag to indicate when select-B is complete */
96961   int addrSelectA;      /* Address of the select-A coroutine */
96962   int addrSelectB;      /* Address of the select-B coroutine */
96963   int regOutA;          /* Address register for the output-A subroutine */
96964   int regOutB;          /* Address register for the output-B subroutine */
96965   int addrOutA;         /* Address of the output-A subroutine */
96966   int addrOutB = 0;     /* Address of the output-B subroutine */
96967   int addrEofA;         /* Address of the select-A-exhausted subroutine */
96968   int addrEofB;         /* Address of the select-B-exhausted subroutine */
96969   int addrAltB;         /* Address of the A<B subroutine */
96970   int addrAeqB;         /* Address of the A==B subroutine */
96971   int addrAgtB;         /* Address of the A>B subroutine */
96972   int regLimitA;        /* Limit register for select-A */
96973   int regLimitB;        /* Limit register for select-A */
96974   int regPrev;          /* A range of registers to hold previous output */
96975   int savedLimit;       /* Saved value of p->iLimit */
96976   int savedOffset;      /* Saved value of p->iOffset */
96977   int labelCmpr;        /* Label for the start of the merge algorithm */
96978   int labelEnd;         /* Label for the end of the overall SELECT stmt */
96979   int j1;               /* Jump instructions that get retargetted */
96980   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96981   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96982   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96983   sqlite3 *db;          /* Database connection */
96984   ExprList *pOrderBy;   /* The ORDER BY clause */
96985   int nOrderBy;         /* Number of terms in the ORDER BY clause */
96986   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96987 #ifndef SQLITE_OMIT_EXPLAIN
96988   int iSub1;            /* EQP id of left-hand query */
96989   int iSub2;            /* EQP id of right-hand query */
96990 #endif
96991 
96992   assert( p->pOrderBy!=0 );
96993   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96994   db = pParse->db;
96995   v = pParse->pVdbe;
96996   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
96997   labelEnd = sqlite3VdbeMakeLabel(v);
96998   labelCmpr = sqlite3VdbeMakeLabel(v);
96999 
97000 
97001   /* Patch up the ORDER BY clause
97002   */
97003   op = p->op;
97004   pPrior = p->pPrior;
97005   assert( pPrior->pOrderBy==0 );
97006   pOrderBy = p->pOrderBy;
97007   assert( pOrderBy );
97008   nOrderBy = pOrderBy->nExpr;
97009 
97010   /* For operators other than UNION ALL we have to make sure that
97011   ** the ORDER BY clause covers every term of the result set.  Add
97012   ** terms to the ORDER BY clause as necessary.
97013   */
97014   if( op!=TK_ALL ){
97015     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
97016       struct ExprList_item *pItem;
97017       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
97018         assert( pItem->iOrderByCol>0 );
97019         if( pItem->iOrderByCol==i ) break;
97020       }
97021       if( j==nOrderBy ){
97022         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
97023         if( pNew==0 ) return SQLITE_NOMEM;
97024         pNew->flags |= EP_IntValue;
97025         pNew->u.iValue = i;
97026         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
97027         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
97028       }
97029     }
97030   }
97031 
97032   /* Compute the comparison permutation and keyinfo that is used with
97033   ** the permutation used to determine if the next
97034   ** row of results comes from selectA or selectB.  Also add explicit
97035   ** collations to the ORDER BY clause terms so that when the subqueries
97036   ** to the right and the left are evaluated, they use the correct
97037   ** collation.
97038   */
97039   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
97040   if( aPermute ){
97041     struct ExprList_item *pItem;
97042     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
97043       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
97044       aPermute[i] = pItem->iOrderByCol - 1;
97045     }
97046     pKeyMerge =
97047       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
97048     if( pKeyMerge ){
97049       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
97050       pKeyMerge->nField = (u16)nOrderBy;
97051       pKeyMerge->enc = ENC(db);
97052       for(i=0; i<nOrderBy; i++){
97053         CollSeq *pColl;
97054         Expr *pTerm = pOrderBy->a[i].pExpr;
97055         if( pTerm->flags & EP_Collate ){
97056           pColl = sqlite3ExprCollSeq(pParse, pTerm);
97057         }else{
97058           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
97059           if( pColl==0 ) pColl = db->pDfltColl;
97060           pOrderBy->a[i].pExpr =
97061              sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
97062         }
97063         pKeyMerge->aColl[i] = pColl;
97064         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
97065       }
97066     }
97067   }else{
97068     pKeyMerge = 0;
97069   }
97070 
97071   /* Reattach the ORDER BY clause to the query.
97072   */
97073   p->pOrderBy = pOrderBy;
97074   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
97075 
97076   /* Allocate a range of temporary registers and the KeyInfo needed
97077   ** for the logic that removes duplicate result rows when the
97078   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
97079   */
97080   if( op==TK_ALL ){
97081     regPrev = 0;
97082   }else{
97083     int nExpr = p->pEList->nExpr;
97084     assert( nOrderBy>=nExpr || db->mallocFailed );
97085     regPrev = pParse->nMem+1;
97086     pParse->nMem += nExpr+1;
97087     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
97088     pKeyDup = sqlite3DbMallocZero(db,
97089                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
97090     if( pKeyDup ){
97091       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
97092       pKeyDup->nField = (u16)nExpr;
97093       pKeyDup->enc = ENC(db);
97094       for(i=0; i<nExpr; i++){
97095         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
97096         pKeyDup->aSortOrder[i] = 0;
97097       }
97098     }
97099   }
97100 
97101   /* Separate the left and the right query from one another
97102   */
97103   p->pPrior = 0;
97104   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
97105   if( pPrior->pPrior==0 ){
97106     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
97107   }
97108 
97109   /* Compute the limit registers */
97110   computeLimitRegisters(pParse, p, labelEnd);
97111   if( p->iLimit && op==TK_ALL ){
97112     regLimitA = ++pParse->nMem;
97113     regLimitB = ++pParse->nMem;
97114     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
97115                                   regLimitA);
97116     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
97117   }else{
97118     regLimitA = regLimitB = 0;
97119   }
97120   sqlite3ExprDelete(db, p->pLimit);
97121   p->pLimit = 0;
97122   sqlite3ExprDelete(db, p->pOffset);
97123   p->pOffset = 0;
97124 
97125   regAddrA = ++pParse->nMem;
97126   regEofA = ++pParse->nMem;
97127   regAddrB = ++pParse->nMem;
97128   regEofB = ++pParse->nMem;
97129   regOutA = ++pParse->nMem;
97130   regOutB = ++pParse->nMem;
97131   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
97132   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
97133 
97134   /* Jump past the various subroutines and coroutines to the main
97135   ** merge loop
97136   */
97137   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
97138   addrSelectA = sqlite3VdbeCurrentAddr(v);
97139 
97140 
97141   /* Generate a coroutine to evaluate the SELECT statement to the
97142   ** left of the compound operator - the "A" select.
97143   */
97144   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
97145   pPrior->iLimit = regLimitA;
97146   explainSetInteger(iSub1, pParse->iNextSelectId);
97147   sqlite3Select(pParse, pPrior, &destA);
97148   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
97149   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97150   VdbeNoopComment((v, "End coroutine for left SELECT"));
97151 
97152   /* Generate a coroutine to evaluate the SELECT statement on
97153   ** the right - the "B" select
97154   */
97155   addrSelectB = sqlite3VdbeCurrentAddr(v);
97156   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
97157   savedLimit = p->iLimit;
97158   savedOffset = p->iOffset;
97159   p->iLimit = regLimitB;
97160   p->iOffset = 0;
97161   explainSetInteger(iSub2, pParse->iNextSelectId);
97162   sqlite3Select(pParse, p, &destB);
97163   p->iLimit = savedLimit;
97164   p->iOffset = savedOffset;
97165   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
97166   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97167   VdbeNoopComment((v, "End coroutine for right SELECT"));
97168 
97169   /* Generate a subroutine that outputs the current row of the A
97170   ** select as the next output row of the compound select.
97171   */
97172   VdbeNoopComment((v, "Output routine for A"));
97173   addrOutA = generateOutputSubroutine(pParse,
97174                  p, &destA, pDest, regOutA,
97175                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
97176 
97177   /* Generate a subroutine that outputs the current row of the B
97178   ** select as the next output row of the compound select.
97179   */
97180   if( op==TK_ALL || op==TK_UNION ){
97181     VdbeNoopComment((v, "Output routine for B"));
97182     addrOutB = generateOutputSubroutine(pParse,
97183                  p, &destB, pDest, regOutB,
97184                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
97185   }
97186 
97187   /* Generate a subroutine to run when the results from select A
97188   ** are exhausted and only data in select B remains.
97189   */
97190   VdbeNoopComment((v, "eof-A subroutine"));
97191   if( op==TK_EXCEPT || op==TK_INTERSECT ){
97192     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
97193   }else{
97194     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
97195     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
97196     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97197     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
97198     p->nSelectRow += pPrior->nSelectRow;
97199   }
97200 
97201   /* Generate a subroutine to run when the results from select B
97202   ** are exhausted and only data in select A remains.
97203   */
97204   if( op==TK_INTERSECT ){
97205     addrEofB = addrEofA;
97206     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
97207   }else{
97208     VdbeNoopComment((v, "eof-B subroutine"));
97209     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
97210     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
97211     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97212     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
97213   }
97214 
97215   /* Generate code to handle the case of A<B
97216   */
97217   VdbeNoopComment((v, "A-lt-B subroutine"));
97218   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
97219   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97220   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
97221   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
97222 
97223   /* Generate code to handle the case of A==B
97224   */
97225   if( op==TK_ALL ){
97226     addrAeqB = addrAltB;
97227   }else if( op==TK_INTERSECT ){
97228     addrAeqB = addrAltB;
97229     addrAltB++;
97230   }else{
97231     VdbeNoopComment((v, "A-eq-B subroutine"));
97232     addrAeqB =
97233     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
97234     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
97235     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
97236   }
97237 
97238   /* Generate code to handle the case of A>B
97239   */
97240   VdbeNoopComment((v, "A-gt-B subroutine"));
97241   addrAgtB = sqlite3VdbeCurrentAddr(v);
97242   if( op==TK_ALL || op==TK_UNION ){
97243     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
97244   }
97245   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
97246   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
97247   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
97248 
97249   /* This code runs once to initialize everything.
97250   */
97251   sqlite3VdbeJumpHere(v, j1);
97252   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
97253   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
97254   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
97255   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
97256   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
97257   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
97258 
97259   /* Implement the main merge loop
97260   */
97261   sqlite3VdbeResolveLabel(v, labelCmpr);
97262   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
97263   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
97264                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
97265   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
97266   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
97267 
97268   /* Jump to the this point in order to terminate the query.
97269   */
97270   sqlite3VdbeResolveLabel(v, labelEnd);
97271 
97272   /* Set the number of output columns
97273   */
97274   if( pDest->eDest==SRT_Output ){
97275     Select *pFirst = pPrior;
97276     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97277     generateColumnNames(pParse, 0, pFirst->pEList);
97278   }
97279 
97280   /* Reassembly the compound query so that it will be freed correctly
97281   ** by the calling function */
97282   if( p->pPrior ){
97283     sqlite3SelectDelete(db, p->pPrior);
97284   }
97285   p->pPrior = pPrior;
97286 
97287   /*** TBD:  Insert subroutine calls to close cursors on incomplete
97288   **** subqueries ****/
97289   explainComposite(pParse, p->op, iSub1, iSub2, 0);
97290   return SQLITE_OK;
97291 }
97292 #endif
97293 
97294 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97295 /* Forward Declarations */
97296 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
97297 static void substSelect(sqlite3*, Select *, int, ExprList *);
97298 
97299 /*
97300 ** Scan through the expression pExpr.  Replace every reference to
97301 ** a column in table number iTable with a copy of the iColumn-th
97302 ** entry in pEList.  (But leave references to the ROWID column
97303 ** unchanged.)
97304 **
97305 ** This routine is part of the flattening procedure.  A subquery
97306 ** whose result set is defined by pEList appears as entry in the
97307 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
97308 ** FORM clause entry is iTable.  This routine make the necessary
97309 ** changes to pExpr so that it refers directly to the source table
97310 ** of the subquery rather the result set of the subquery.
97311 */
97312 static Expr *substExpr(
97313   sqlite3 *db,        /* Report malloc errors to this connection */
97314   Expr *pExpr,        /* Expr in which substitution occurs */
97315   int iTable,         /* Table to be substituted */
97316   ExprList *pEList    /* Substitute expressions */
97317 ){
97318   if( pExpr==0 ) return 0;
97319   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
97320     if( pExpr->iColumn<0 ){
97321       pExpr->op = TK_NULL;
97322     }else{
97323       Expr *pNew;
97324       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
97325       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
97326       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
97327       sqlite3ExprDelete(db, pExpr);
97328       pExpr = pNew;
97329     }
97330   }else{
97331     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
97332     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
97333     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97334       substSelect(db, pExpr->x.pSelect, iTable, pEList);
97335     }else{
97336       substExprList(db, pExpr->x.pList, iTable, pEList);
97337     }
97338   }
97339   return pExpr;
97340 }
97341 static void substExprList(
97342   sqlite3 *db,         /* Report malloc errors here */
97343   ExprList *pList,     /* List to scan and in which to make substitutes */
97344   int iTable,          /* Table to be substituted */
97345   ExprList *pEList     /* Substitute values */
97346 ){
97347   int i;
97348   if( pList==0 ) return;
97349   for(i=0; i<pList->nExpr; i++){
97350     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
97351   }
97352 }
97353 static void substSelect(
97354   sqlite3 *db,         /* Report malloc errors here */
97355   Select *p,           /* SELECT statement in which to make substitutions */
97356   int iTable,          /* Table to be replaced */
97357   ExprList *pEList     /* Substitute values */
97358 ){
97359   SrcList *pSrc;
97360   struct SrcList_item *pItem;
97361   int i;
97362   if( !p ) return;
97363   substExprList(db, p->pEList, iTable, pEList);
97364   substExprList(db, p->pGroupBy, iTable, pEList);
97365   substExprList(db, p->pOrderBy, iTable, pEList);
97366   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
97367   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
97368   substSelect(db, p->pPrior, iTable, pEList);
97369   pSrc = p->pSrc;
97370   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
97371   if( ALWAYS(pSrc) ){
97372     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
97373       substSelect(db, pItem->pSelect, iTable, pEList);
97374     }
97375   }
97376 }
97377 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97378 
97379 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97380 /*
97381 ** This routine attempts to flatten subqueries as a performance optimization.
97382 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
97383 **
97384 ** To understand the concept of flattening, consider the following
97385 ** query:
97386 **
97387 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
97388 **
97389 ** The default way of implementing this query is to execute the
97390 ** subquery first and store the results in a temporary table, then
97391 ** run the outer query on that temporary table.  This requires two
97392 ** passes over the data.  Furthermore, because the temporary table
97393 ** has no indices, the WHERE clause on the outer query cannot be
97394 ** optimized.
97395 **
97396 ** This routine attempts to rewrite queries such as the above into
97397 ** a single flat select, like this:
97398 **
97399 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
97400 **
97401 ** The code generated for this simpification gives the same result
97402 ** but only has to scan the data once.  And because indices might
97403 ** exist on the table t1, a complete scan of the data might be
97404 ** avoided.
97405 **
97406 ** Flattening is only attempted if all of the following are true:
97407 **
97408 **   (1)  The subquery and the outer query do not both use aggregates.
97409 **
97410 **   (2)  The subquery is not an aggregate or the outer query is not a join.
97411 **
97412 **   (3)  The subquery is not the right operand of a left outer join
97413 **        (Originally ticket #306.  Strengthened by ticket #3300)
97414 **
97415 **   (4)  The subquery is not DISTINCT.
97416 **
97417 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
97418 **        sub-queries that were excluded from this optimization. Restriction
97419 **        (4) has since been expanded to exclude all DISTINCT subqueries.
97420 **
97421 **   (6)  The subquery does not use aggregates or the outer query is not
97422 **        DISTINCT.
97423 **
97424 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
97425 **        A FROM clause, consider adding a FROM close with the special
97426 **        table sqlite_once that consists of a single row containing a
97427 **        single NULL.
97428 **
97429 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
97430 **
97431 **   (9)  The subquery does not use LIMIT or the outer query does not use
97432 **        aggregates.
97433 **
97434 **  (10)  The subquery does not use aggregates or the outer query does not
97435 **        use LIMIT.
97436 **
97437 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
97438 **
97439 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
97440 **        a separate restriction deriving from ticket #350.
97441 **
97442 **  (13)  The subquery and outer query do not both use LIMIT.
97443 **
97444 **  (14)  The subquery does not use OFFSET.
97445 **
97446 **  (15)  The outer query is not part of a compound select or the
97447 **        subquery does not have a LIMIT clause.
97448 **        (See ticket #2339 and ticket [02a8e81d44]).
97449 **
97450 **  (16)  The outer query is not an aggregate or the subquery does
97451 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
97452 **        until we introduced the group_concat() function.
97453 **
97454 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
97455 **        compound clause made up entirely of non-aggregate queries, and
97456 **        the parent query:
97457 **
97458 **          * is not itself part of a compound select,
97459 **          * is not an aggregate or DISTINCT query, and
97460 **          * is not a join
97461 **
97462 **        The parent and sub-query may contain WHERE clauses. Subject to
97463 **        rules (11), (13) and (14), they may also contain ORDER BY,
97464 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
97465 **        operator other than UNION ALL because all the other compound
97466 **        operators have an implied DISTINCT which is disallowed by
97467 **        restriction (4).
97468 **
97469 **        Also, each component of the sub-query must return the same number
97470 **        of result columns. This is actually a requirement for any compound
97471 **        SELECT statement, but all the code here does is make sure that no
97472 **        such (illegal) sub-query is flattened. The caller will detect the
97473 **        syntax error and return a detailed message.
97474 **
97475 **  (18)  If the sub-query is a compound select, then all terms of the
97476 **        ORDER by clause of the parent must be simple references to
97477 **        columns of the sub-query.
97478 **
97479 **  (19)  The subquery does not use LIMIT or the outer query does not
97480 **        have a WHERE clause.
97481 **
97482 **  (20)  If the sub-query is a compound select, then it must not use
97483 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
97484 **        somewhat by saying that the terms of the ORDER BY clause must
97485 **        appear as unmodified result columns in the outer query.  But we
97486 **        have other optimizations in mind to deal with that case.
97487 **
97488 **  (21)  The subquery does not use LIMIT or the outer query is not
97489 **        DISTINCT.  (See ticket [752e1646fc]).
97490 **
97491 ** In this routine, the "p" parameter is a pointer to the outer query.
97492 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
97493 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
97494 **
97495 ** If flattening is not attempted, this routine is a no-op and returns 0.
97496 ** If flattening is attempted this routine returns 1.
97497 **
97498 ** All of the expression analysis must occur on both the outer query and
97499 ** the subquery before this routine runs.
97500 */
97501 static int flattenSubquery(
97502   Parse *pParse,       /* Parsing context */
97503   Select *p,           /* The parent or outer SELECT statement */
97504   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
97505   int isAgg,           /* True if outer SELECT uses aggregate functions */
97506   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
97507 ){
97508   const char *zSavedAuthContext = pParse->zAuthContext;
97509   Select *pParent;
97510   Select *pSub;       /* The inner query or "subquery" */
97511   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
97512   SrcList *pSrc;      /* The FROM clause of the outer query */
97513   SrcList *pSubSrc;   /* The FROM clause of the subquery */
97514   ExprList *pList;    /* The result set of the outer query */
97515   int iParent;        /* VDBE cursor number of the pSub result set temp table */
97516   int i;              /* Loop counter */
97517   Expr *pWhere;                    /* The WHERE clause */
97518   struct SrcList_item *pSubitem;   /* The subquery */
97519   sqlite3 *db = pParse->db;
97520 
97521   /* Check to see if flattening is permitted.  Return 0 if not.
97522   */
97523   assert( p!=0 );
97524   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
97525   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
97526   pSrc = p->pSrc;
97527   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
97528   pSubitem = &pSrc->a[iFrom];
97529   iParent = pSubitem->iCursor;
97530   pSub = pSubitem->pSelect;
97531   assert( pSub!=0 );
97532   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
97533   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
97534   pSubSrc = pSub->pSrc;
97535   assert( pSubSrc );
97536   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
97537   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
97538   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
97539   ** became arbitrary expressions, we were forced to add restrictions (13)
97540   ** and (14). */
97541   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
97542   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
97543   if( p->pRightmost && pSub->pLimit ){
97544     return 0;                                            /* Restriction (15) */
97545   }
97546   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
97547   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
97548   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
97549      return 0;         /* Restrictions (8)(9) */
97550   }
97551   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
97552      return 0;         /* Restriction (6)  */
97553   }
97554   if( p->pOrderBy && pSub->pOrderBy ){
97555      return 0;                                           /* Restriction (11) */
97556   }
97557   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
97558   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
97559   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
97560      return 0;         /* Restriction (21) */
97561   }
97562 
97563   /* OBSOLETE COMMENT 1:
97564   ** Restriction 3:  If the subquery is a join, make sure the subquery is
97565   ** not used as the right operand of an outer join.  Examples of why this
97566   ** is not allowed:
97567   **
97568   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
97569   **
97570   ** If we flatten the above, we would get
97571   **
97572   **         (t1 LEFT OUTER JOIN t2) JOIN t3
97573   **
97574   ** which is not at all the same thing.
97575   **
97576   ** OBSOLETE COMMENT 2:
97577   ** Restriction 12:  If the subquery is the right operand of a left outer
97578   ** join, make sure the subquery has no WHERE clause.
97579   ** An examples of why this is not allowed:
97580   **
97581   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
97582   **
97583   ** If we flatten the above, we would get
97584   **
97585   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
97586   **
97587   ** But the t2.x>0 test will always fail on a NULL row of t2, which
97588   ** effectively converts the OUTER JOIN into an INNER JOIN.
97589   **
97590   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
97591   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
97592   ** is fraught with danger.  Best to avoid the whole thing.  If the
97593   ** subquery is the right term of a LEFT JOIN, then do not flatten.
97594   */
97595   if( (pSubitem->jointype & JT_OUTER)!=0 ){
97596     return 0;
97597   }
97598 
97599   /* Restriction 17: If the sub-query is a compound SELECT, then it must
97600   ** use only the UNION ALL operator. And none of the simple select queries
97601   ** that make up the compound SELECT are allowed to be aggregate or distinct
97602   ** queries.
97603   */
97604   if( pSub->pPrior ){
97605     if( pSub->pOrderBy ){
97606       return 0;  /* Restriction 20 */
97607     }
97608     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
97609       return 0;
97610     }
97611     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
97612       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
97613       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
97614       assert( pSub->pSrc!=0 );
97615       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
97616        || (pSub1->pPrior && pSub1->op!=TK_ALL)
97617        || pSub1->pSrc->nSrc<1
97618        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
97619       ){
97620         return 0;
97621       }
97622       testcase( pSub1->pSrc->nSrc>1 );
97623     }
97624 
97625     /* Restriction 18. */
97626     if( p->pOrderBy ){
97627       int ii;
97628       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
97629         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
97630       }
97631     }
97632   }
97633 
97634   /***** If we reach this point, flattening is permitted. *****/
97635 
97636   /* Authorize the subquery */
97637   pParse->zAuthContext = pSubitem->zName;
97638   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
97639   testcase( i==SQLITE_DENY );
97640   pParse->zAuthContext = zSavedAuthContext;
97641 
97642   /* If the sub-query is a compound SELECT statement, then (by restrictions
97643   ** 17 and 18 above) it must be a UNION ALL and the parent query must
97644   ** be of the form:
97645   **
97646   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
97647   **
97648   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
97649   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
97650   ** OFFSET clauses and joins them to the left-hand-side of the original
97651   ** using UNION ALL operators. In this case N is the number of simple
97652   ** select statements in the compound sub-query.
97653   **
97654   ** Example:
97655   **
97656   **     SELECT a+1 FROM (
97657   **        SELECT x FROM tab
97658   **        UNION ALL
97659   **        SELECT y FROM tab
97660   **        UNION ALL
97661   **        SELECT abs(z*2) FROM tab2
97662   **     ) WHERE a!=5 ORDER BY 1
97663   **
97664   ** Transformed into:
97665   **
97666   **     SELECT x+1 FROM tab WHERE x+1!=5
97667   **     UNION ALL
97668   **     SELECT y+1 FROM tab WHERE y+1!=5
97669   **     UNION ALL
97670   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97671   **     ORDER BY 1
97672   **
97673   ** We call this the "compound-subquery flattening".
97674   */
97675   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97676     Select *pNew;
97677     ExprList *pOrderBy = p->pOrderBy;
97678     Expr *pLimit = p->pLimit;
97679     Expr *pOffset = p->pOffset;
97680     Select *pPrior = p->pPrior;
97681     p->pOrderBy = 0;
97682     p->pSrc = 0;
97683     p->pPrior = 0;
97684     p->pLimit = 0;
97685     p->pOffset = 0;
97686     pNew = sqlite3SelectDup(db, p, 0);
97687     p->pOffset = pOffset;
97688     p->pLimit = pLimit;
97689     p->pOrderBy = pOrderBy;
97690     p->pSrc = pSrc;
97691     p->op = TK_ALL;
97692     p->pRightmost = 0;
97693     if( pNew==0 ){
97694       pNew = pPrior;
97695     }else{
97696       pNew->pPrior = pPrior;
97697       pNew->pRightmost = 0;
97698     }
97699     p->pPrior = pNew;
97700     if( db->mallocFailed ) return 1;
97701   }
97702 
97703   /* Begin flattening the iFrom-th entry of the FROM clause
97704   ** in the outer query.
97705   */
97706   pSub = pSub1 = pSubitem->pSelect;
97707 
97708   /* Delete the transient table structure associated with the
97709   ** subquery
97710   */
97711   sqlite3DbFree(db, pSubitem->zDatabase);
97712   sqlite3DbFree(db, pSubitem->zName);
97713   sqlite3DbFree(db, pSubitem->zAlias);
97714   pSubitem->zDatabase = 0;
97715   pSubitem->zName = 0;
97716   pSubitem->zAlias = 0;
97717   pSubitem->pSelect = 0;
97718 
97719   /* Defer deleting the Table object associated with the
97720   ** subquery until code generation is
97721   ** complete, since there may still exist Expr.pTab entries that
97722   ** refer to the subquery even after flattening.  Ticket #3346.
97723   **
97724   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97725   */
97726   if( ALWAYS(pSubitem->pTab!=0) ){
97727     Table *pTabToDel = pSubitem->pTab;
97728     if( pTabToDel->nRef==1 ){
97729       Parse *pToplevel = sqlite3ParseToplevel(pParse);
97730       pTabToDel->pNextZombie = pToplevel->pZombieTab;
97731       pToplevel->pZombieTab = pTabToDel;
97732     }else{
97733       pTabToDel->nRef--;
97734     }
97735     pSubitem->pTab = 0;
97736   }
97737 
97738   /* The following loop runs once for each term in a compound-subquery
97739   ** flattening (as described above).  If we are doing a different kind
97740   ** of flattening - a flattening other than a compound-subquery flattening -
97741   ** then this loop only runs once.
97742   **
97743   ** This loop moves all of the FROM elements of the subquery into the
97744   ** the FROM clause of the outer query.  Before doing this, remember
97745   ** the cursor number for the original outer query FROM element in
97746   ** iParent.  The iParent cursor will never be used.  Subsequent code
97747   ** will scan expressions looking for iParent references and replace
97748   ** those references with expressions that resolve to the subquery FROM
97749   ** elements we are now copying in.
97750   */
97751   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97752     int nSubSrc;
97753     u8 jointype = 0;
97754     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97755     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97756     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97757 
97758     if( pSrc ){
97759       assert( pParent==p );  /* First time through the loop */
97760       jointype = pSubitem->jointype;
97761     }else{
97762       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97763       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97764       if( pSrc==0 ){
97765         assert( db->mallocFailed );
97766         break;
97767       }
97768     }
97769 
97770     /* The subquery uses a single slot of the FROM clause of the outer
97771     ** query.  If the subquery has more than one element in its FROM clause,
97772     ** then expand the outer query to make space for it to hold all elements
97773     ** of the subquery.
97774     **
97775     ** Example:
97776     **
97777     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97778     **
97779     ** The outer query has 3 slots in its FROM clause.  One slot of the
97780     ** outer query (the middle slot) is used by the subquery.  The next
97781     ** block of code will expand the out query to 4 slots.  The middle
97782     ** slot is expanded to two slots in order to make space for the
97783     ** two elements in the FROM clause of the subquery.
97784     */
97785     if( nSubSrc>1 ){
97786       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97787       if( db->mallocFailed ){
97788         break;
97789       }
97790     }
97791 
97792     /* Transfer the FROM clause terms from the subquery into the
97793     ** outer query.
97794     */
97795     for(i=0; i<nSubSrc; i++){
97796       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97797       pSrc->a[i+iFrom] = pSubSrc->a[i];
97798       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97799     }
97800     pSrc->a[iFrom].jointype = jointype;
97801 
97802     /* Now begin substituting subquery result set expressions for
97803     ** references to the iParent in the outer query.
97804     **
97805     ** Example:
97806     **
97807     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97808     **   \                     \_____________ subquery __________/          /
97809     **    \_____________________ outer query ______________________________/
97810     **
97811     ** We look at every expression in the outer query and every place we see
97812     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97813     */
97814     pList = pParent->pEList;
97815     for(i=0; i<pList->nExpr; i++){
97816       if( pList->a[i].zName==0 ){
97817         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
97818         sqlite3Dequote(zName);
97819         pList->a[i].zName = zName;
97820       }
97821     }
97822     substExprList(db, pParent->pEList, iParent, pSub->pEList);
97823     if( isAgg ){
97824       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97825       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97826     }
97827     if( pSub->pOrderBy ){
97828       assert( pParent->pOrderBy==0 );
97829       pParent->pOrderBy = pSub->pOrderBy;
97830       pSub->pOrderBy = 0;
97831     }else if( pParent->pOrderBy ){
97832       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97833     }
97834     if( pSub->pWhere ){
97835       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
97836     }else{
97837       pWhere = 0;
97838     }
97839     if( subqueryIsAgg ){
97840       assert( pParent->pHaving==0 );
97841       pParent->pHaving = pParent->pWhere;
97842       pParent->pWhere = pWhere;
97843       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97844       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
97845                                   sqlite3ExprDup(db, pSub->pHaving, 0));
97846       assert( pParent->pGroupBy==0 );
97847       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
97848     }else{
97849       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97850       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
97851     }
97852 
97853     /* The flattened query is distinct if either the inner or the
97854     ** outer query is distinct.
97855     */
97856     pParent->selFlags |= pSub->selFlags & SF_Distinct;
97857 
97858     /*
97859     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97860     **
97861     ** One is tempted to try to add a and b to combine the limits.  But this
97862     ** does not work if either limit is negative.
97863     */
97864     if( pSub->pLimit ){
97865       pParent->pLimit = pSub->pLimit;
97866       pSub->pLimit = 0;
97867     }
97868   }
97869 
97870   /* Finially, delete what is left of the subquery and return
97871   ** success.
97872   */
97873   sqlite3SelectDelete(db, pSub1);
97874 
97875   return 1;
97876 }
97877 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97878 
97879 /*
97880 ** Based on the contents of the AggInfo structure indicated by the first
97881 ** argument, this function checks if the following are true:
97882 **
97883 **    * the query contains just a single aggregate function,
97884 **    * the aggregate function is either min() or max(), and
97885 **    * the argument to the aggregate function is a column value.
97886 **
97887 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
97888 ** is returned as appropriate. Also, *ppMinMax is set to point to the
97889 ** list of arguments passed to the aggregate before returning.
97890 **
97891 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
97892 ** WHERE_ORDERBY_NORMAL is returned.
97893 */
97894 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
97895   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
97896 
97897   *ppMinMax = 0;
97898   if( pAggInfo->nFunc==1 ){
97899     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
97900     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
97901 
97902     assert( pExpr->op==TK_AGG_FUNCTION );
97903     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
97904       const char *zFunc = pExpr->u.zToken;
97905       if( sqlite3StrICmp(zFunc, "min")==0 ){
97906         eRet = WHERE_ORDERBY_MIN;
97907         *ppMinMax = pEList;
97908       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
97909         eRet = WHERE_ORDERBY_MAX;
97910         *ppMinMax = pEList;
97911       }
97912     }
97913   }
97914 
97915   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
97916   return eRet;
97917 }
97918 
97919 /*
97920 ** The select statement passed as the first argument is an aggregate query.
97921 ** The second argment is the associated aggregate-info object. This
97922 ** function tests if the SELECT is of the form:
97923 **
97924 **   SELECT count(*) FROM <tbl>
97925 **
97926 ** where table is a database table, not a sub-select or view. If the query
97927 ** does match this pattern, then a pointer to the Table object representing
97928 ** <tbl> is returned. Otherwise, 0 is returned.
97929 */
97930 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97931   Table *pTab;
97932   Expr *pExpr;
97933 
97934   assert( !p->pGroupBy );
97935 
97936   if( p->pWhere || p->pEList->nExpr!=1
97937    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97938   ){
97939     return 0;
97940   }
97941   pTab = p->pSrc->a[0].pTab;
97942   pExpr = p->pEList->a[0].pExpr;
97943   assert( pTab && !pTab->pSelect && pExpr );
97944 
97945   if( IsVirtual(pTab) ) return 0;
97946   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97947   if( NEVER(pAggInfo->nFunc==0) ) return 0;
97948   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
97949   if( pExpr->flags&EP_Distinct ) return 0;
97950 
97951   return pTab;
97952 }
97953 
97954 /*
97955 ** If the source-list item passed as an argument was augmented with an
97956 ** INDEXED BY clause, then try to locate the specified index. If there
97957 ** was such a clause and the named index cannot be found, return
97958 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
97959 ** pFrom->pIndex and return SQLITE_OK.
97960 */
97961 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97962   if( pFrom->pTab && pFrom->zIndex ){
97963     Table *pTab = pFrom->pTab;
97964     char *zIndex = pFrom->zIndex;
97965     Index *pIdx;
97966     for(pIdx=pTab->pIndex;
97967         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
97968         pIdx=pIdx->pNext
97969     );
97970     if( !pIdx ){
97971       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97972       pParse->checkSchema = 1;
97973       return SQLITE_ERROR;
97974     }
97975     pFrom->pIndex = pIdx;
97976   }
97977   return SQLITE_OK;
97978 }
97979 
97980 /*
97981 ** This routine is a Walker callback for "expanding" a SELECT statement.
97982 ** "Expanding" means to do the following:
97983 **
97984 **    (1)  Make sure VDBE cursor numbers have been assigned to every
97985 **         element of the FROM clause.
97986 **
97987 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
97988 **         defines FROM clause.  When views appear in the FROM clause,
97989 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
97990 **         that implements the view.  A copy is made of the view's SELECT
97991 **         statement so that we can freely modify or delete that statement
97992 **         without worrying about messing up the presistent representation
97993 **         of the view.
97994 **
97995 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
97996 **         on joins and the ON and USING clause of joins.
97997 **
97998 **    (4)  Scan the list of columns in the result set (pEList) looking
97999 **         for instances of the "*" operator or the TABLE.* operator.
98000 **         If found, expand each "*" to be every column in every table
98001 **         and TABLE.* to be every column in TABLE.
98002 **
98003 */
98004 static int selectExpander(Walker *pWalker, Select *p){
98005   Parse *pParse = pWalker->pParse;
98006   int i, j, k;
98007   SrcList *pTabList;
98008   ExprList *pEList;
98009   struct SrcList_item *pFrom;
98010   sqlite3 *db = pParse->db;
98011   Expr *pE, *pRight, *pExpr;
98012   u16 selFlags = p->selFlags;
98013 
98014   p->selFlags |= SF_Expanded;
98015   if( db->mallocFailed  ){
98016     return WRC_Abort;
98017   }
98018   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
98019     return WRC_Prune;
98020   }
98021   pTabList = p->pSrc;
98022   pEList = p->pEList;
98023 
98024   /* Make sure cursor numbers have been assigned to all entries in
98025   ** the FROM clause of the SELECT statement.
98026   */
98027   sqlite3SrcListAssignCursors(pParse, pTabList);
98028 
98029   /* Look up every table named in the FROM clause of the select.  If
98030   ** an entry of the FROM clause is a subquery instead of a table or view,
98031   ** then create a transient table structure to describe the subquery.
98032   */
98033   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98034     Table *pTab;
98035     if( pFrom->pTab!=0 ){
98036       /* This statement has already been prepared.  There is no need
98037       ** to go further. */
98038       assert( i==0 );
98039       return WRC_Prune;
98040     }
98041     if( pFrom->zName==0 ){
98042 #ifndef SQLITE_OMIT_SUBQUERY
98043       Select *pSel = pFrom->pSelect;
98044       /* A sub-query in the FROM clause of a SELECT */
98045       assert( pSel!=0 );
98046       assert( pFrom->pTab==0 );
98047       sqlite3WalkSelect(pWalker, pSel);
98048       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
98049       if( pTab==0 ) return WRC_Abort;
98050       pTab->nRef = 1;
98051       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
98052       while( pSel->pPrior ){ pSel = pSel->pPrior; }
98053       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
98054       pTab->iPKey = -1;
98055       pTab->nRowEst = 1000000;
98056       pTab->tabFlags |= TF_Ephemeral;
98057 #endif
98058     }else{
98059       /* An ordinary table or view name in the FROM clause */
98060       assert( pFrom->pTab==0 );
98061       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
98062       if( pTab==0 ) return WRC_Abort;
98063       if( pTab->nRef==0xffff ){
98064         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
98065            pTab->zName);
98066         pFrom->pTab = 0;
98067         return WRC_Abort;
98068       }
98069       pTab->nRef++;
98070 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
98071       if( pTab->pSelect || IsVirtual(pTab) ){
98072         /* We reach here if the named table is a really a view */
98073         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
98074         assert( pFrom->pSelect==0 );
98075         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
98076         sqlite3WalkSelect(pWalker, pFrom->pSelect);
98077       }
98078 #endif
98079     }
98080 
98081     /* Locate the index named by the INDEXED BY clause, if any. */
98082     if( sqlite3IndexedByLookup(pParse, pFrom) ){
98083       return WRC_Abort;
98084     }
98085   }
98086 
98087   /* Process NATURAL keywords, and ON and USING clauses of joins.
98088   */
98089   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
98090     return WRC_Abort;
98091   }
98092 
98093   /* For every "*" that occurs in the column list, insert the names of
98094   ** all columns in all tables.  And for every TABLE.* insert the names
98095   ** of all columns in TABLE.  The parser inserted a special expression
98096   ** with the TK_ALL operator for each "*" that it found in the column list.
98097   ** The following code just has to locate the TK_ALL expressions and expand
98098   ** each one to the list of all columns in all tables.
98099   **
98100   ** The first loop just checks to see if there are any "*" operators
98101   ** that need expanding.
98102   */
98103   for(k=0; k<pEList->nExpr; k++){
98104     pE = pEList->a[k].pExpr;
98105     if( pE->op==TK_ALL ) break;
98106     assert( pE->op!=TK_DOT || pE->pRight!=0 );
98107     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
98108     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
98109   }
98110   if( k<pEList->nExpr ){
98111     /*
98112     ** If we get here it means the result set contains one or more "*"
98113     ** operators that need to be expanded.  Loop through each expression
98114     ** in the result set and expand them one by one.
98115     */
98116     struct ExprList_item *a = pEList->a;
98117     ExprList *pNew = 0;
98118     int flags = pParse->db->flags;
98119     int longNames = (flags & SQLITE_FullColNames)!=0
98120                       && (flags & SQLITE_ShortColNames)==0;
98121 
98122     /* When processing FROM-clause subqueries, it is always the case
98123     ** that full_column_names=OFF and short_column_names=ON.  The
98124     ** sqlite3ResultSetOfSelect() routine makes it so. */
98125     assert( (p->selFlags & SF_NestedFrom)==0
98126           || ((flags & SQLITE_FullColNames)==0 &&
98127               (flags & SQLITE_ShortColNames)!=0) );
98128 
98129     for(k=0; k<pEList->nExpr; k++){
98130       pE = a[k].pExpr;
98131       pRight = pE->pRight;
98132       assert( pE->op!=TK_DOT || pRight!=0 );
98133       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
98134         /* This particular expression does not need to be expanded.
98135         */
98136         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
98137         if( pNew ){
98138           pNew->a[pNew->nExpr-1].zName = a[k].zName;
98139           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
98140           a[k].zName = 0;
98141           a[k].zSpan = 0;
98142         }
98143         a[k].pExpr = 0;
98144       }else{
98145         /* This expression is a "*" or a "TABLE.*" and needs to be
98146         ** expanded. */
98147         int tableSeen = 0;      /* Set to 1 when TABLE matches */
98148         char *zTName = 0;       /* text of name of TABLE */
98149         if( pE->op==TK_DOT ){
98150           assert( pE->pLeft!=0 );
98151           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
98152           zTName = pE->pLeft->u.zToken;
98153         }
98154         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98155           Table *pTab = pFrom->pTab;
98156           Select *pSub = pFrom->pSelect;
98157           char *zTabName = pFrom->zAlias;
98158           const char *zSchemaName = 0;
98159           int iDb;
98160           if( zTabName==0 ){
98161             zTabName = pTab->zName;
98162           }
98163           if( db->mallocFailed ) break;
98164           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
98165             pSub = 0;
98166             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
98167               continue;
98168             }
98169             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98170             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
98171           }
98172           for(j=0; j<pTab->nCol; j++){
98173             char *zName = pTab->aCol[j].zName;
98174             char *zColname;  /* The computed column name */
98175             char *zToFree;   /* Malloced string that needs to be freed */
98176             Token sColname;  /* Computed column name as a token */
98177 
98178             assert( zName );
98179             if( zTName && pSub
98180              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
98181             ){
98182               continue;
98183             }
98184 
98185             /* If a column is marked as 'hidden' (currently only possible
98186             ** for virtual tables), do not include it in the expanded
98187             ** result-set list.
98188             */
98189             if( IsHiddenColumn(&pTab->aCol[j]) ){
98190               assert(IsVirtual(pTab));
98191               continue;
98192             }
98193             tableSeen = 1;
98194 
98195             if( i>0 && zTName==0 ){
98196               if( (pFrom->jointype & JT_NATURAL)!=0
98197                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
98198               ){
98199                 /* In a NATURAL join, omit the join columns from the
98200                 ** table to the right of the join */
98201                 continue;
98202               }
98203               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
98204                 /* In a join with a USING clause, omit columns in the
98205                 ** using clause from the table on the right. */
98206                 continue;
98207               }
98208             }
98209             pRight = sqlite3Expr(db, TK_ID, zName);
98210             zColname = zName;
98211             zToFree = 0;
98212             if( longNames || pTabList->nSrc>1 ){
98213               Expr *pLeft;
98214               pLeft = sqlite3Expr(db, TK_ID, zTabName);
98215               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
98216               if( zSchemaName ){
98217                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
98218                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
98219               }
98220               if( longNames ){
98221                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
98222                 zToFree = zColname;
98223               }
98224             }else{
98225               pExpr = pRight;
98226             }
98227             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
98228             sColname.z = zColname;
98229             sColname.n = sqlite3Strlen30(zColname);
98230             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
98231             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
98232               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
98233               if( pSub ){
98234                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
98235                 testcase( pX->zSpan==0 );
98236               }else{
98237                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
98238                                            zSchemaName, zTabName, zColname);
98239                 testcase( pX->zSpan==0 );
98240               }
98241               pX->bSpanIsTab = 1;
98242             }
98243             sqlite3DbFree(db, zToFree);
98244           }
98245         }
98246         if( !tableSeen ){
98247           if( zTName ){
98248             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
98249           }else{
98250             sqlite3ErrorMsg(pParse, "no tables specified");
98251           }
98252         }
98253       }
98254     }
98255     sqlite3ExprListDelete(db, pEList);
98256     p->pEList = pNew;
98257   }
98258 #if SQLITE_MAX_COLUMN
98259   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
98260     sqlite3ErrorMsg(pParse, "too many columns in result set");
98261   }
98262 #endif
98263   return WRC_Continue;
98264 }
98265 
98266 /*
98267 ** No-op routine for the parse-tree walker.
98268 **
98269 ** When this routine is the Walker.xExprCallback then expression trees
98270 ** are walked without any actions being taken at each node.  Presumably,
98271 ** when this routine is used for Walker.xExprCallback then
98272 ** Walker.xSelectCallback is set to do something useful for every
98273 ** subquery in the parser tree.
98274 */
98275 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
98276   UNUSED_PARAMETER2(NotUsed, NotUsed2);
98277   return WRC_Continue;
98278 }
98279 
98280 /*
98281 ** This routine "expands" a SELECT statement and all of its subqueries.
98282 ** For additional information on what it means to "expand" a SELECT
98283 ** statement, see the comment on the selectExpand worker callback above.
98284 **
98285 ** Expanding a SELECT statement is the first step in processing a
98286 ** SELECT statement.  The SELECT statement must be expanded before
98287 ** name resolution is performed.
98288 **
98289 ** If anything goes wrong, an error message is written into pParse.
98290 ** The calling function can detect the problem by looking at pParse->nErr
98291 ** and/or pParse->db->mallocFailed.
98292 */
98293 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
98294   Walker w;
98295   w.xSelectCallback = selectExpander;
98296   w.xExprCallback = exprWalkNoop;
98297   w.pParse = pParse;
98298   sqlite3WalkSelect(&w, pSelect);
98299 }
98300 
98301 
98302 #ifndef SQLITE_OMIT_SUBQUERY
98303 /*
98304 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
98305 ** interface.
98306 **
98307 ** For each FROM-clause subquery, add Column.zType and Column.zColl
98308 ** information to the Table structure that represents the result set
98309 ** of that subquery.
98310 **
98311 ** The Table structure that represents the result set was constructed
98312 ** by selectExpander() but the type and collation information was omitted
98313 ** at that point because identifiers had not yet been resolved.  This
98314 ** routine is called after identifier resolution.
98315 */
98316 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
98317   Parse *pParse;
98318   int i;
98319   SrcList *pTabList;
98320   struct SrcList_item *pFrom;
98321 
98322   assert( p->selFlags & SF_Resolved );
98323   if( (p->selFlags & SF_HasTypeInfo)==0 ){
98324     p->selFlags |= SF_HasTypeInfo;
98325     pParse = pWalker->pParse;
98326     pTabList = p->pSrc;
98327     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
98328       Table *pTab = pFrom->pTab;
98329       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
98330         /* A sub-query in the FROM clause of a SELECT */
98331         Select *pSel = pFrom->pSelect;
98332         assert( pSel );
98333         while( pSel->pPrior ) pSel = pSel->pPrior;
98334         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
98335       }
98336     }
98337   }
98338   return WRC_Continue;
98339 }
98340 #endif
98341 
98342 
98343 /*
98344 ** This routine adds datatype and collating sequence information to
98345 ** the Table structures of all FROM-clause subqueries in a
98346 ** SELECT statement.
98347 **
98348 ** Use this routine after name resolution.
98349 */
98350 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
98351 #ifndef SQLITE_OMIT_SUBQUERY
98352   Walker w;
98353   w.xSelectCallback = selectAddSubqueryTypeInfo;
98354   w.xExprCallback = exprWalkNoop;
98355   w.pParse = pParse;
98356   sqlite3WalkSelect(&w, pSelect);
98357 #endif
98358 }
98359 
98360 
98361 /*
98362 ** This routine sets up a SELECT statement for processing.  The
98363 ** following is accomplished:
98364 **
98365 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
98366 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
98367 **     *  ON and USING clauses are shifted into WHERE statements
98368 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
98369 **     *  Identifiers in expression are matched to tables.
98370 **
98371 ** This routine acts recursively on all subqueries within the SELECT.
98372 */
98373 SQLITE_PRIVATE void sqlite3SelectPrep(
98374   Parse *pParse,         /* The parser context */
98375   Select *p,             /* The SELECT statement being coded. */
98376   NameContext *pOuterNC  /* Name context for container */
98377 ){
98378   sqlite3 *db;
98379   if( NEVER(p==0) ) return;
98380   db = pParse->db;
98381   if( db->mallocFailed ) return;
98382   if( p->selFlags & SF_HasTypeInfo ) return;
98383   sqlite3SelectExpand(pParse, p);
98384   if( pParse->nErr || db->mallocFailed ) return;
98385   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
98386   if( pParse->nErr || db->mallocFailed ) return;
98387   sqlite3SelectAddTypeInfo(pParse, p);
98388 }
98389 
98390 /*
98391 ** Reset the aggregate accumulator.
98392 **
98393 ** The aggregate accumulator is a set of memory cells that hold
98394 ** intermediate results while calculating an aggregate.  This
98395 ** routine generates code that stores NULLs in all of those memory
98396 ** cells.
98397 */
98398 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
98399   Vdbe *v = pParse->pVdbe;
98400   int i;
98401   struct AggInfo_func *pFunc;
98402   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
98403     return;
98404   }
98405   for(i=0; i<pAggInfo->nColumn; i++){
98406     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
98407   }
98408   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
98409     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
98410     if( pFunc->iDistinct>=0 ){
98411       Expr *pE = pFunc->pExpr;
98412       assert( !ExprHasProperty(pE, EP_xIsSelect) );
98413       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
98414         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
98415            "argument");
98416         pFunc->iDistinct = -1;
98417       }else{
98418         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
98419         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
98420                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98421       }
98422     }
98423   }
98424 }
98425 
98426 /*
98427 ** Invoke the OP_AggFinalize opcode for every aggregate function
98428 ** in the AggInfo structure.
98429 */
98430 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
98431   Vdbe *v = pParse->pVdbe;
98432   int i;
98433   struct AggInfo_func *pF;
98434   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98435     ExprList *pList = pF->pExpr->x.pList;
98436     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98437     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
98438                       (void*)pF->pFunc, P4_FUNCDEF);
98439   }
98440 }
98441 
98442 /*
98443 ** Update the accumulator memory cells for an aggregate based on
98444 ** the current cursor position.
98445 */
98446 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
98447   Vdbe *v = pParse->pVdbe;
98448   int i;
98449   int regHit = 0;
98450   int addrHitTest = 0;
98451   struct AggInfo_func *pF;
98452   struct AggInfo_col *pC;
98453 
98454   pAggInfo->directMode = 1;
98455   sqlite3ExprCacheClear(pParse);
98456   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98457     int nArg;
98458     int addrNext = 0;
98459     int regAgg;
98460     ExprList *pList = pF->pExpr->x.pList;
98461     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98462     if( pList ){
98463       nArg = pList->nExpr;
98464       regAgg = sqlite3GetTempRange(pParse, nArg);
98465       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
98466     }else{
98467       nArg = 0;
98468       regAgg = 0;
98469     }
98470     if( pF->iDistinct>=0 ){
98471       addrNext = sqlite3VdbeMakeLabel(v);
98472       assert( nArg==1 );
98473       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
98474     }
98475     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
98476       CollSeq *pColl = 0;
98477       struct ExprList_item *pItem;
98478       int j;
98479       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
98480       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
98481         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
98482       }
98483       if( !pColl ){
98484         pColl = pParse->db->pDfltColl;
98485       }
98486       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
98487       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
98488     }
98489     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
98490                       (void*)pF->pFunc, P4_FUNCDEF);
98491     sqlite3VdbeChangeP5(v, (u8)nArg);
98492     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
98493     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
98494     if( addrNext ){
98495       sqlite3VdbeResolveLabel(v, addrNext);
98496       sqlite3ExprCacheClear(pParse);
98497     }
98498   }
98499 
98500   /* Before populating the accumulator registers, clear the column cache.
98501   ** Otherwise, if any of the required column values are already present
98502   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
98503   ** to pC->iMem. But by the time the value is used, the original register
98504   ** may have been used, invalidating the underlying buffer holding the
98505   ** text or blob value. See ticket [883034dcb5].
98506   **
98507   ** Another solution would be to change the OP_SCopy used to copy cached
98508   ** values to an OP_Copy.
98509   */
98510   if( regHit ){
98511     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
98512   }
98513   sqlite3ExprCacheClear(pParse);
98514   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
98515     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
98516   }
98517   pAggInfo->directMode = 0;
98518   sqlite3ExprCacheClear(pParse);
98519   if( addrHitTest ){
98520     sqlite3VdbeJumpHere(v, addrHitTest);
98521   }
98522 }
98523 
98524 /*
98525 ** Add a single OP_Explain instruction to the VDBE to explain a simple
98526 ** count(*) query ("SELECT count(*) FROM pTab").
98527 */
98528 #ifndef SQLITE_OMIT_EXPLAIN
98529 static void explainSimpleCount(
98530   Parse *pParse,                  /* Parse context */
98531   Table *pTab,                    /* Table being queried */
98532   Index *pIdx                     /* Index used to optimize scan, or NULL */
98533 ){
98534   if( pParse->explain==2 ){
98535     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
98536         pTab->zName,
98537         pIdx ? "USING COVERING INDEX " : "",
98538         pIdx ? pIdx->zName : "",
98539         pTab->nRowEst
98540     );
98541     sqlite3VdbeAddOp4(
98542         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
98543     );
98544   }
98545 }
98546 #else
98547 # define explainSimpleCount(a,b,c)
98548 #endif
98549 
98550 /*
98551 ** Generate code for the SELECT statement given in the p argument.
98552 **
98553 ** The results are distributed in various ways depending on the
98554 ** contents of the SelectDest structure pointed to by argument pDest
98555 ** as follows:
98556 **
98557 **     pDest->eDest    Result
98558 **     ------------    -------------------------------------------
98559 **     SRT_Output      Generate a row of output (using the OP_ResultRow
98560 **                     opcode) for each row in the result set.
98561 **
98562 **     SRT_Mem         Only valid if the result is a single column.
98563 **                     Store the first column of the first result row
98564 **                     in register pDest->iSDParm then abandon the rest
98565 **                     of the query.  This destination implies "LIMIT 1".
98566 **
98567 **     SRT_Set         The result must be a single column.  Store each
98568 **                     row of result as the key in table pDest->iSDParm.
98569 **                     Apply the affinity pDest->affSdst before storing
98570 **                     results.  Used to implement "IN (SELECT ...)".
98571 **
98572 **     SRT_Union       Store results as a key in a temporary table
98573 **                     identified by pDest->iSDParm.
98574 **
98575 **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
98576 **
98577 **     SRT_Table       Store results in temporary table pDest->iSDParm.
98578 **                     This is like SRT_EphemTab except that the table
98579 **                     is assumed to already be open.
98580 **
98581 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
98582 **                     the result there. The cursor is left open after
98583 **                     returning.  This is like SRT_Table except that
98584 **                     this destination uses OP_OpenEphemeral to create
98585 **                     the table first.
98586 **
98587 **     SRT_Coroutine   Generate a co-routine that returns a new row of
98588 **                     results each time it is invoked.  The entry point
98589 **                     of the co-routine is stored in register pDest->iSDParm.
98590 **
98591 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
98592 **                     set is not empty.
98593 **
98594 **     SRT_Discard     Throw the results away.  This is used by SELECT
98595 **                     statements within triggers whose only purpose is
98596 **                     the side-effects of functions.
98597 **
98598 ** This routine returns the number of errors.  If any errors are
98599 ** encountered, then an appropriate error message is left in
98600 ** pParse->zErrMsg.
98601 **
98602 ** This routine does NOT free the Select structure passed in.  The
98603 ** calling function needs to do that.
98604 */
98605 SQLITE_PRIVATE int sqlite3Select(
98606   Parse *pParse,         /* The parser context */
98607   Select *p,             /* The SELECT statement being coded. */
98608   SelectDest *pDest      /* What to do with the query results */
98609 ){
98610   int i, j;              /* Loop counters */
98611   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
98612   Vdbe *v;               /* The virtual machine under construction */
98613   int isAgg;             /* True for select lists like "count(*)" */
98614   ExprList *pEList;      /* List of columns to extract. */
98615   SrcList *pTabList;     /* List of tables to select from */
98616   Expr *pWhere;          /* The WHERE clause.  May be NULL */
98617   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
98618   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
98619   Expr *pHaving;         /* The HAVING clause.  May be NULL */
98620   int rc = 1;            /* Value to return from this function */
98621   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
98622   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
98623   AggInfo sAggInfo;      /* Information used by aggregate queries */
98624   int iEnd;              /* Address of the end of the query */
98625   sqlite3 *db;           /* The database connection */
98626 
98627 #ifndef SQLITE_OMIT_EXPLAIN
98628   int iRestoreSelectId = pParse->iSelectId;
98629   pParse->iSelectId = pParse->iNextSelectId++;
98630 #endif
98631 
98632   db = pParse->db;
98633   if( p==0 || db->mallocFailed || pParse->nErr ){
98634     return 1;
98635   }
98636   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
98637   memset(&sAggInfo, 0, sizeof(sAggInfo));
98638 
98639   if( IgnorableOrderby(pDest) ){
98640     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
98641            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
98642     /* If ORDER BY makes no difference in the output then neither does
98643     ** DISTINCT so it can be removed too. */
98644     sqlite3ExprListDelete(db, p->pOrderBy);
98645     p->pOrderBy = 0;
98646     p->selFlags &= ~SF_Distinct;
98647   }
98648   sqlite3SelectPrep(pParse, p, 0);
98649   pOrderBy = p->pOrderBy;
98650   pTabList = p->pSrc;
98651   pEList = p->pEList;
98652   if( pParse->nErr || db->mallocFailed ){
98653     goto select_end;
98654   }
98655   isAgg = (p->selFlags & SF_Aggregate)!=0;
98656   assert( pEList!=0 );
98657 
98658   /* Begin generating code.
98659   */
98660   v = sqlite3GetVdbe(pParse);
98661   if( v==0 ) goto select_end;
98662 
98663   /* If writing to memory or generating a set
98664   ** only a single column may be output.
98665   */
98666 #ifndef SQLITE_OMIT_SUBQUERY
98667   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
98668     goto select_end;
98669   }
98670 #endif
98671 
98672   /* Generate code for all sub-queries in the FROM clause
98673   */
98674 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98675   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
98676     struct SrcList_item *pItem = &pTabList->a[i];
98677     SelectDest dest;
98678     Select *pSub = pItem->pSelect;
98679     int isAggSub;
98680 
98681     if( pSub==0 ) continue;
98682 
98683     /* Sometimes the code for a subquery will be generated more than
98684     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
98685     ** for example.  In that case, do not regenerate the code to manifest
98686     ** a view or the co-routine to implement a view.  The first instance
98687     ** is sufficient, though the subroutine to manifest the view does need
98688     ** to be invoked again. */
98689     if( pItem->addrFillSub ){
98690       if( pItem->viaCoroutine==0 ){
98691         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
98692       }
98693       continue;
98694     }
98695 
98696     /* Increment Parse.nHeight by the height of the largest expression
98697     ** tree refered to by this, the parent select. The child select
98698     ** may contain expression trees of at most
98699     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
98700     ** more conservative than necessary, but much easier than enforcing
98701     ** an exact limit.
98702     */
98703     pParse->nHeight += sqlite3SelectExprHeight(p);
98704 
98705     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
98706     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
98707       /* This subquery can be absorbed into its parent. */
98708       if( isAggSub ){
98709         isAgg = 1;
98710         p->selFlags |= SF_Aggregate;
98711       }
98712       i = -1;
98713     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
98714       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
98715     ){
98716       /* Implement a co-routine that will return a single row of the result
98717       ** set on each invocation.
98718       */
98719       int addrTop;
98720       int addrEof;
98721       pItem->regReturn = ++pParse->nMem;
98722       addrEof = ++pParse->nMem;
98723       /* Before coding the OP_Goto to jump to the start of the main routine,
98724       ** ensure that the jump to the verify-schema routine has already
98725       ** been coded. Otherwise, the verify-schema would likely be coded as
98726       ** part of the co-routine. If the main routine then accessed the
98727       ** database before invoking the co-routine for the first time (for
98728       ** example to initialize a LIMIT register from a sub-select), it would
98729       ** be doing so without having verified the schema version and obtained
98730       ** the required db locks. See ticket d6b36be38.  */
98731       sqlite3CodeVerifySchema(pParse, -1);
98732       sqlite3VdbeAddOp0(v, OP_Goto);
98733       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
98734       sqlite3VdbeChangeP5(v, 1);
98735       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
98736       pItem->addrFillSub = addrTop;
98737       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
98738       sqlite3VdbeChangeP5(v, 1);
98739       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
98740       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98741       sqlite3Select(pParse, pSub, &dest);
98742       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98743       pItem->viaCoroutine = 1;
98744       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
98745       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
98746       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
98747       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
98748       VdbeComment((v, "end %s", pItem->pTab->zName));
98749       sqlite3VdbeJumpHere(v, addrTop-1);
98750       sqlite3ClearTempRegCache(pParse);
98751     }else{
98752       /* Generate a subroutine that will fill an ephemeral table with
98753       ** the content of this subquery.  pItem->addrFillSub will point
98754       ** to the address of the generated subroutine.  pItem->regReturn
98755       ** is a register allocated to hold the subroutine return address
98756       */
98757       int topAddr;
98758       int onceAddr = 0;
98759       int retAddr;
98760       assert( pItem->addrFillSub==0 );
98761       pItem->regReturn = ++pParse->nMem;
98762       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
98763       pItem->addrFillSub = topAddr+1;
98764       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
98765       if( pItem->isCorrelated==0 ){
98766         /* If the subquery is no correlated and if we are not inside of
98767         ** a trigger, then we only need to compute the value of the subquery
98768         ** once. */
98769         onceAddr = sqlite3CodeOnce(pParse);
98770       }
98771       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
98772       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98773       sqlite3Select(pParse, pSub, &dest);
98774       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98775       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
98776       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98777       VdbeComment((v, "end %s", pItem->pTab->zName));
98778       sqlite3VdbeChangeP1(v, topAddr, retAddr);
98779       sqlite3ClearTempRegCache(pParse);
98780     }
98781     if( /*pParse->nErr ||*/ db->mallocFailed ){
98782       goto select_end;
98783     }
98784     pParse->nHeight -= sqlite3SelectExprHeight(p);
98785     pTabList = p->pSrc;
98786     if( !IgnorableOrderby(pDest) ){
98787       pOrderBy = p->pOrderBy;
98788     }
98789   }
98790   pEList = p->pEList;
98791 #endif
98792   pWhere = p->pWhere;
98793   pGroupBy = p->pGroupBy;
98794   pHaving = p->pHaving;
98795   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
98796 
98797 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98798   /* If there is are a sequence of queries, do the earlier ones first.
98799   */
98800   if( p->pPrior ){
98801     if( p->pRightmost==0 ){
98802       Select *pLoop, *pRight = 0;
98803       int cnt = 0;
98804       int mxSelect;
98805       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98806         pLoop->pRightmost = p;
98807         pLoop->pNext = pRight;
98808         pRight = pLoop;
98809       }
98810       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
98811       if( mxSelect && cnt>mxSelect ){
98812         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
98813         goto select_end;
98814       }
98815     }
98816     rc = multiSelect(pParse, p, pDest);
98817     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98818     return rc;
98819   }
98820 #endif
98821 
98822   /* If there is both a GROUP BY and an ORDER BY clause and they are
98823   ** identical, then disable the ORDER BY clause since the GROUP BY
98824   ** will cause elements to come out in the correct order.  This is
98825   ** an optimization - the correct answer should result regardless.
98826   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
98827   ** to disable this optimization for testing purposes.
98828   */
98829   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
98830          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
98831     pOrderBy = 0;
98832   }
98833 
98834   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
98835   ** if the select-list is the same as the ORDER BY list, then this query
98836   ** can be rewritten as a GROUP BY. In other words, this:
98837   **
98838   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98839   **
98840   ** is transformed to:
98841   **
98842   **     SELECT xyz FROM ... GROUP BY xyz
98843   **
98844   ** The second form is preferred as a single index (or temp-table) may be
98845   ** used for both the ORDER BY and DISTINCT processing. As originally
98846   ** written the query must use a temp-table for at least one of the ORDER
98847   ** BY and DISTINCT, and an index or separate temp-table for the other.
98848   */
98849   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
98850    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
98851   ){
98852     p->selFlags &= ~SF_Distinct;
98853     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
98854     pGroupBy = p->pGroupBy;
98855     pOrderBy = 0;
98856     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
98857     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
98858     ** original setting of the SF_Distinct flag, not the current setting */
98859     assert( sDistinct.isTnct );
98860   }
98861 
98862   /* If there is an ORDER BY clause, then this sorting
98863   ** index might end up being unused if the data can be
98864   ** extracted in pre-sorted order.  If that is the case, then the
98865   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98866   ** we figure out that the sorting index is not needed.  The addrSortIndex
98867   ** variable is used to facilitate that change.
98868   */
98869   if( pOrderBy ){
98870     KeyInfo *pKeyInfo;
98871     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98872     pOrderBy->iECursor = pParse->nTab++;
98873     p->addrOpenEphm[2] = addrSortIndex =
98874       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98875                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98876                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98877   }else{
98878     addrSortIndex = -1;
98879   }
98880 
98881   /* If the output is destined for a temporary table, open that table.
98882   */
98883   if( pDest->eDest==SRT_EphemTab ){
98884     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
98885   }
98886 
98887   /* Set the limiter.
98888   */
98889   iEnd = sqlite3VdbeMakeLabel(v);
98890   p->nSelectRow = (double)LARGEST_INT64;
98891   computeLimitRegisters(pParse, p, iEnd);
98892   if( p->iLimit==0 && addrSortIndex>=0 ){
98893     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98894     p->selFlags |= SF_UseSorter;
98895   }
98896 
98897   /* Open a virtual index to use for the distinct set.
98898   */
98899   if( p->selFlags & SF_Distinct ){
98900     sDistinct.tabTnct = pParse->nTab++;
98901     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98902                                 sDistinct.tabTnct, 0, 0,
98903                                 (char*)keyInfoFromExprList(pParse, p->pEList),
98904                                 P4_KEYINFO_HANDOFF);
98905     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98906     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
98907   }else{
98908     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
98909   }
98910 
98911   if( !isAgg && pGroupBy==0 ){
98912     /* No aggregate functions and no GROUP BY clause */
98913     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
98914 
98915     /* Begin the database scan. */
98916     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
98917     if( pWInfo==0 ) goto select_end;
98918     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98919     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
98920     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
98921 
98922     /* If sorting index that was created by a prior OP_OpenEphemeral
98923     ** instruction ended up not being needed, then change the OP_OpenEphemeral
98924     ** into an OP_Noop.
98925     */
98926     if( addrSortIndex>=0 && pOrderBy==0 ){
98927       sqlite3VdbeChangeToNoop(v, addrSortIndex);
98928       p->addrOpenEphm[2] = -1;
98929     }
98930 
98931     /* Use the standard inner loop. */
98932     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
98933                     pWInfo->iContinue, pWInfo->iBreak);
98934 
98935     /* End the database scan loop.
98936     */
98937     sqlite3WhereEnd(pWInfo);
98938   }else{
98939     /* This case when there exist aggregate functions or a GROUP BY clause
98940     ** or both */
98941     NameContext sNC;    /* Name context for processing aggregate information */
98942     int iAMem;          /* First Mem address for storing current GROUP BY */
98943     int iBMem;          /* First Mem address for previous GROUP BY */
98944     int iUseFlag;       /* Mem address holding flag indicating that at least
98945                         ** one row of the input to the aggregator has been
98946                         ** processed */
98947     int iAbortFlag;     /* Mem address which causes query abort if positive */
98948     int groupBySort;    /* Rows come from source in GROUP BY order */
98949     int addrEnd;        /* End of processing for this SELECT */
98950     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98951     int sortOut = 0;    /* Output register from the sorter */
98952 
98953     /* Remove any and all aliases between the result set and the
98954     ** GROUP BY clause.
98955     */
98956     if( pGroupBy ){
98957       int k;                        /* Loop counter */
98958       struct ExprList_item *pItem;  /* For looping over expression in a list */
98959 
98960       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98961         pItem->iAlias = 0;
98962       }
98963       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98964         pItem->iAlias = 0;
98965       }
98966       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98967     }else{
98968       p->nSelectRow = (double)1;
98969     }
98970 
98971 
98972     /* Create a label to jump to when we want to abort the query */
98973     addrEnd = sqlite3VdbeMakeLabel(v);
98974 
98975     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98976     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98977     ** SELECT statement.
98978     */
98979     memset(&sNC, 0, sizeof(sNC));
98980     sNC.pParse = pParse;
98981     sNC.pSrcList = pTabList;
98982     sNC.pAggInfo = &sAggInfo;
98983     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98984     sAggInfo.pGroupBy = pGroupBy;
98985     sqlite3ExprAnalyzeAggList(&sNC, pEList);
98986     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
98987     if( pHaving ){
98988       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
98989     }
98990     sAggInfo.nAccumulator = sAggInfo.nColumn;
98991     for(i=0; i<sAggInfo.nFunc; i++){
98992       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98993       sNC.ncFlags |= NC_InAggFunc;
98994       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98995       sNC.ncFlags &= ~NC_InAggFunc;
98996     }
98997     if( db->mallocFailed ) goto select_end;
98998 
98999     /* Processing for aggregates with GROUP BY is very different and
99000     ** much more complex than aggregates without a GROUP BY.
99001     */
99002     if( pGroupBy ){
99003       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
99004       int j1;             /* A-vs-B comparision jump */
99005       int addrOutputRow;  /* Start of subroutine that outputs a result row */
99006       int regOutputRow;   /* Return address register for output subroutine */
99007       int addrSetAbort;   /* Set the abort flag and return */
99008       int addrTopOfLoop;  /* Top of the input loop */
99009       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
99010       int addrReset;      /* Subroutine for resetting the accumulator */
99011       int regReset;       /* Return address register for reset subroutine */
99012 
99013       /* If there is a GROUP BY clause we might need a sorting index to
99014       ** implement it.  Allocate that sorting index now.  If it turns out
99015       ** that we do not need it after all, the OP_SorterOpen instruction
99016       ** will be converted into a Noop.
99017       */
99018       sAggInfo.sortingIdx = pParse->nTab++;
99019       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
99020       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
99021           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
99022           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99023 
99024       /* Initialize memory locations used by GROUP BY aggregate processing
99025       */
99026       iUseFlag = ++pParse->nMem;
99027       iAbortFlag = ++pParse->nMem;
99028       regOutputRow = ++pParse->nMem;
99029       addrOutputRow = sqlite3VdbeMakeLabel(v);
99030       regReset = ++pParse->nMem;
99031       addrReset = sqlite3VdbeMakeLabel(v);
99032       iAMem = pParse->nMem + 1;
99033       pParse->nMem += pGroupBy->nExpr;
99034       iBMem = pParse->nMem + 1;
99035       pParse->nMem += pGroupBy->nExpr;
99036       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
99037       VdbeComment((v, "clear abort flag"));
99038       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
99039       VdbeComment((v, "indicate accumulator empty"));
99040       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
99041 
99042       /* Begin a loop that will extract all source rows in GROUP BY order.
99043       ** This might involve two separate loops with an OP_Sort in between, or
99044       ** it might be a single loop that uses an index to extract information
99045       ** in the right order to begin with.
99046       */
99047       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
99048       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
99049       if( pWInfo==0 ) goto select_end;
99050       if( pWInfo->nOBSat==pGroupBy->nExpr ){
99051         /* The optimizer is able to deliver rows in group by order so
99052         ** we do not have to sort.  The OP_OpenEphemeral table will be
99053         ** cancelled later because we still need to use the pKeyInfo
99054         */
99055         groupBySort = 0;
99056       }else{
99057         /* Rows are coming out in undetermined order.  We have to push
99058         ** each row into a sorting index, terminate the first loop,
99059         ** then loop over the sorting index in order to get the output
99060         ** in sorted order
99061         */
99062         int regBase;
99063         int regRecord;
99064         int nCol;
99065         int nGroupBy;
99066 
99067         explainTempTable(pParse,
99068             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
99069                     "DISTINCT" : "GROUP BY");
99070 
99071         groupBySort = 1;
99072         nGroupBy = pGroupBy->nExpr;
99073         nCol = nGroupBy + 1;
99074         j = nGroupBy+1;
99075         for(i=0; i<sAggInfo.nColumn; i++){
99076           if( sAggInfo.aCol[i].iSorterColumn>=j ){
99077             nCol++;
99078             j++;
99079           }
99080         }
99081         regBase = sqlite3GetTempRange(pParse, nCol);
99082         sqlite3ExprCacheClear(pParse);
99083         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
99084         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
99085         j = nGroupBy+1;
99086         for(i=0; i<sAggInfo.nColumn; i++){
99087           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
99088           if( pCol->iSorterColumn>=j ){
99089             int r1 = j + regBase;
99090             int r2;
99091 
99092             r2 = sqlite3ExprCodeGetColumn(pParse,
99093                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
99094             if( r1!=r2 ){
99095               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
99096             }
99097             j++;
99098           }
99099         }
99100         regRecord = sqlite3GetTempReg(pParse);
99101         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
99102         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
99103         sqlite3ReleaseTempReg(pParse, regRecord);
99104         sqlite3ReleaseTempRange(pParse, regBase, nCol);
99105         sqlite3WhereEnd(pWInfo);
99106         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
99107         sortOut = sqlite3GetTempReg(pParse);
99108         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
99109         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
99110         VdbeComment((v, "GROUP BY sort"));
99111         sAggInfo.useSortingIdx = 1;
99112         sqlite3ExprCacheClear(pParse);
99113       }
99114 
99115       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
99116       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
99117       ** Then compare the current GROUP BY terms against the GROUP BY terms
99118       ** from the previous row currently stored in a0, a1, a2...
99119       */
99120       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
99121       sqlite3ExprCacheClear(pParse);
99122       if( groupBySort ){
99123         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
99124       }
99125       for(j=0; j<pGroupBy->nExpr; j++){
99126         if( groupBySort ){
99127           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
99128           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
99129         }else{
99130           sAggInfo.directMode = 1;
99131           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
99132         }
99133       }
99134       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
99135                           (char*)pKeyInfo, P4_KEYINFO);
99136       j1 = sqlite3VdbeCurrentAddr(v);
99137       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
99138 
99139       /* Generate code that runs whenever the GROUP BY changes.
99140       ** Changes in the GROUP BY are detected by the previous code
99141       ** block.  If there were no changes, this block is skipped.
99142       **
99143       ** This code copies current group by terms in b0,b1,b2,...
99144       ** over to a0,a1,a2.  It then calls the output subroutine
99145       ** and resets the aggregate accumulator registers in preparation
99146       ** for the next GROUP BY batch.
99147       */
99148       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
99149       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
99150       VdbeComment((v, "output one row"));
99151       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
99152       VdbeComment((v, "check abort flag"));
99153       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
99154       VdbeComment((v, "reset accumulator"));
99155 
99156       /* Update the aggregate accumulators based on the content of
99157       ** the current row
99158       */
99159       sqlite3VdbeJumpHere(v, j1);
99160       updateAccumulator(pParse, &sAggInfo);
99161       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
99162       VdbeComment((v, "indicate data in accumulator"));
99163 
99164       /* End of the loop
99165       */
99166       if( groupBySort ){
99167         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
99168       }else{
99169         sqlite3WhereEnd(pWInfo);
99170         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
99171       }
99172 
99173       /* Output the final row of result
99174       */
99175       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
99176       VdbeComment((v, "output final row"));
99177 
99178       /* Jump over the subroutines
99179       */
99180       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
99181 
99182       /* Generate a subroutine that outputs a single row of the result
99183       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
99184       ** is less than or equal to zero, the subroutine is a no-op.  If
99185       ** the processing calls for the query to abort, this subroutine
99186       ** increments the iAbortFlag memory location before returning in
99187       ** order to signal the caller to abort.
99188       */
99189       addrSetAbort = sqlite3VdbeCurrentAddr(v);
99190       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
99191       VdbeComment((v, "set abort flag"));
99192       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99193       sqlite3VdbeResolveLabel(v, addrOutputRow);
99194       addrOutputRow = sqlite3VdbeCurrentAddr(v);
99195       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
99196       VdbeComment((v, "Groupby result generator entry point"));
99197       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99198       finalizeAggFunctions(pParse, &sAggInfo);
99199       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
99200       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
99201                       &sDistinct, pDest,
99202                       addrOutputRow+1, addrSetAbort);
99203       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
99204       VdbeComment((v, "end groupby result generator"));
99205 
99206       /* Generate a subroutine that will reset the group-by accumulator
99207       */
99208       sqlite3VdbeResolveLabel(v, addrReset);
99209       resetAccumulator(pParse, &sAggInfo);
99210       sqlite3VdbeAddOp1(v, OP_Return, regReset);
99211 
99212     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
99213     else {
99214       ExprList *pDel = 0;
99215 #ifndef SQLITE_OMIT_BTREECOUNT
99216       Table *pTab;
99217       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
99218         /* If isSimpleCount() returns a pointer to a Table structure, then
99219         ** the SQL statement is of the form:
99220         **
99221         **   SELECT count(*) FROM <tbl>
99222         **
99223         ** where the Table structure returned represents table <tbl>.
99224         **
99225         ** This statement is so common that it is optimized specially. The
99226         ** OP_Count instruction is executed either on the intkey table that
99227         ** contains the data for table <tbl> or on one of its indexes. It
99228         ** is better to execute the op on an index, as indexes are almost
99229         ** always spread across less pages than their corresponding tables.
99230         */
99231         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99232         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
99233         Index *pIdx;                         /* Iterator variable */
99234         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
99235         Index *pBest = 0;                    /* Best index found so far */
99236         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
99237 
99238         sqlite3CodeVerifySchema(pParse, iDb);
99239         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
99240 
99241         /* Search for the index that has the least amount of columns. If
99242         ** there is such an index, and it has less columns than the table
99243         ** does, then we can assume that it consumes less space on disk and
99244         ** will therefore be cheaper to scan to determine the query result.
99245         ** In this case set iRoot to the root page number of the index b-tree
99246         ** and pKeyInfo to the KeyInfo structure required to navigate the
99247         ** index.
99248         **
99249         ** (2011-04-15) Do not do a full scan of an unordered index.
99250         **
99251         ** In practice the KeyInfo structure will not be used. It is only
99252         ** passed to keep OP_OpenRead happy.
99253         */
99254         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99255           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
99256             pBest = pIdx;
99257           }
99258         }
99259         if( pBest && pBest->nColumn<pTab->nCol ){
99260           iRoot = pBest->tnum;
99261           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
99262         }
99263 
99264         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
99265         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
99266         if( pKeyInfo ){
99267           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
99268         }
99269         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
99270         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
99271         explainSimpleCount(pParse, pTab, pBest);
99272       }else
99273 #endif /* SQLITE_OMIT_BTREECOUNT */
99274       {
99275         /* Check if the query is of one of the following forms:
99276         **
99277         **   SELECT min(x) FROM ...
99278         **   SELECT max(x) FROM ...
99279         **
99280         ** If it is, then ask the code in where.c to attempt to sort results
99281         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
99282         ** If where.c is able to produce results sorted in this order, then
99283         ** add vdbe code to break out of the processing loop after the
99284         ** first iteration (since the first iteration of the loop is
99285         ** guaranteed to operate on the row with the minimum or maximum
99286         ** value of x, the only row required).
99287         **
99288         ** A special flag must be passed to sqlite3WhereBegin() to slightly
99289         ** modify behavior as follows:
99290         **
99291         **   + If the query is a "SELECT min(x)", then the loop coded by
99292         **     where.c should not iterate over any values with a NULL value
99293         **     for x.
99294         **
99295         **   + The optimizer code in where.c (the thing that decides which
99296         **     index or indices to use) should place a different priority on
99297         **     satisfying the 'ORDER BY' clause than it does in other cases.
99298         **     Refer to code and comments in where.c for details.
99299         */
99300         ExprList *pMinMax = 0;
99301         u8 flag = WHERE_ORDERBY_NORMAL;
99302 
99303         assert( p->pGroupBy==0 );
99304         assert( flag==0 );
99305         if( p->pHaving==0 ){
99306           flag = minMaxQuery(&sAggInfo, &pMinMax);
99307         }
99308         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
99309 
99310         if( flag ){
99311           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
99312           pDel = pMinMax;
99313           if( pMinMax && !db->mallocFailed ){
99314             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
99315             pMinMax->a[0].pExpr->op = TK_COLUMN;
99316           }
99317         }
99318 
99319         /* This case runs if the aggregate has no GROUP BY clause.  The
99320         ** processing is much simpler since there is only a single row
99321         ** of output.
99322         */
99323         resetAccumulator(pParse, &sAggInfo);
99324         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
99325         if( pWInfo==0 ){
99326           sqlite3ExprListDelete(db, pDel);
99327           goto select_end;
99328         }
99329         updateAccumulator(pParse, &sAggInfo);
99330         assert( pMinMax==0 || pMinMax->nExpr==1 );
99331         if( pWInfo->nOBSat>0 ){
99332           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
99333           VdbeComment((v, "%s() by index",
99334                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
99335         }
99336         sqlite3WhereEnd(pWInfo);
99337         finalizeAggFunctions(pParse, &sAggInfo);
99338       }
99339 
99340       pOrderBy = 0;
99341       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
99342       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
99343                       pDest, addrEnd, addrEnd);
99344       sqlite3ExprListDelete(db, pDel);
99345     }
99346     sqlite3VdbeResolveLabel(v, addrEnd);
99347 
99348   } /* endif aggregate query */
99349 
99350   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
99351     explainTempTable(pParse, "DISTINCT");
99352   }
99353 
99354   /* If there is an ORDER BY clause, then we need to sort the results
99355   ** and send them to the callback one by one.
99356   */
99357   if( pOrderBy ){
99358     explainTempTable(pParse, "ORDER BY");
99359     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
99360   }
99361 
99362   /* Jump here to skip this query
99363   */
99364   sqlite3VdbeResolveLabel(v, iEnd);
99365 
99366   /* The SELECT was successfully coded.   Set the return code to 0
99367   ** to indicate no errors.
99368   */
99369   rc = 0;
99370 
99371   /* Control jumps to here if an error is encountered above, or upon
99372   ** successful coding of the SELECT.
99373   */
99374 select_end:
99375   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
99376 
99377   /* Identify column names if results of the SELECT are to be output.
99378   */
99379   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
99380     generateColumnNames(pParse, pTabList, pEList);
99381   }
99382 
99383   sqlite3DbFree(db, sAggInfo.aCol);
99384   sqlite3DbFree(db, sAggInfo.aFunc);
99385   return rc;
99386 }
99387 
99388 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
99389 /*
99390 ** Generate a human-readable description of a the Select object.
99391 */
99392 static void explainOneSelect(Vdbe *pVdbe, Select *p){
99393   sqlite3ExplainPrintf(pVdbe, "SELECT ");
99394   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
99395     if( p->selFlags & SF_Distinct ){
99396       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
99397     }
99398     if( p->selFlags & SF_Aggregate ){
99399       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
99400     }
99401     sqlite3ExplainNL(pVdbe);
99402     sqlite3ExplainPrintf(pVdbe, "   ");
99403   }
99404   sqlite3ExplainExprList(pVdbe, p->pEList);
99405   sqlite3ExplainNL(pVdbe);
99406   if( p->pSrc && p->pSrc->nSrc ){
99407     int i;
99408     sqlite3ExplainPrintf(pVdbe, "FROM ");
99409     sqlite3ExplainPush(pVdbe);
99410     for(i=0; i<p->pSrc->nSrc; i++){
99411       struct SrcList_item *pItem = &p->pSrc->a[i];
99412       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
99413       if( pItem->pSelect ){
99414         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
99415         if( pItem->pTab ){
99416           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
99417         }
99418       }else if( pItem->zName ){
99419         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
99420       }
99421       if( pItem->zAlias ){
99422         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
99423       }
99424       if( pItem->jointype & JT_LEFT ){
99425         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
99426       }
99427       sqlite3ExplainNL(pVdbe);
99428     }
99429     sqlite3ExplainPop(pVdbe);
99430   }
99431   if( p->pWhere ){
99432     sqlite3ExplainPrintf(pVdbe, "WHERE ");
99433     sqlite3ExplainExpr(pVdbe, p->pWhere);
99434     sqlite3ExplainNL(pVdbe);
99435   }
99436   if( p->pGroupBy ){
99437     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
99438     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
99439     sqlite3ExplainNL(pVdbe);
99440   }
99441   if( p->pHaving ){
99442     sqlite3ExplainPrintf(pVdbe, "HAVING ");
99443     sqlite3ExplainExpr(pVdbe, p->pHaving);
99444     sqlite3ExplainNL(pVdbe);
99445   }
99446   if( p->pOrderBy ){
99447     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
99448     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
99449     sqlite3ExplainNL(pVdbe);
99450   }
99451   if( p->pLimit ){
99452     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
99453     sqlite3ExplainExpr(pVdbe, p->pLimit);
99454     sqlite3ExplainNL(pVdbe);
99455   }
99456   if( p->pOffset ){
99457     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
99458     sqlite3ExplainExpr(pVdbe, p->pOffset);
99459     sqlite3ExplainNL(pVdbe);
99460   }
99461 }
99462 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
99463   if( p==0 ){
99464     sqlite3ExplainPrintf(pVdbe, "(null-select)");
99465     return;
99466   }
99467   while( p->pPrior ){
99468     p->pPrior->pNext = p;
99469     p = p->pPrior;
99470   }
99471   sqlite3ExplainPush(pVdbe);
99472   while( p ){
99473     explainOneSelect(pVdbe, p);
99474     p = p->pNext;
99475     if( p==0 ) break;
99476     sqlite3ExplainNL(pVdbe);
99477     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
99478   }
99479   sqlite3ExplainPrintf(pVdbe, "END");
99480   sqlite3ExplainPop(pVdbe);
99481 }
99482 
99483 /* End of the structure debug printing code
99484 *****************************************************************************/
99485 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
99486 
99487 /************** End of select.c **********************************************/
99488 /************** Begin file table.c *******************************************/
99489 /*
99490 ** 2001 September 15
99491 **
99492 ** The author disclaims copyright to this source code.  In place of
99493 ** a legal notice, here is a blessing:
99494 **
99495 **    May you do good and not evil.
99496 **    May you find forgiveness for yourself and forgive others.
99497 **    May you share freely, never taking more than you give.
99498 **
99499 *************************************************************************
99500 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
99501 ** interface routines.  These are just wrappers around the main
99502 ** interface routine of sqlite3_exec().
99503 **
99504 ** These routines are in a separate files so that they will not be linked
99505 ** if they are not used.
99506 */
99507 /* #include <stdlib.h> */
99508 /* #include <string.h> */
99509 
99510 #ifndef SQLITE_OMIT_GET_TABLE
99511 
99512 /*
99513 ** This structure is used to pass data from sqlite3_get_table() through
99514 ** to the callback function is uses to build the result.
99515 */
99516 typedef struct TabResult {
99517   char **azResult;   /* Accumulated output */
99518   char *zErrMsg;     /* Error message text, if an error occurs */
99519   int nAlloc;        /* Slots allocated for azResult[] */
99520   int nRow;          /* Number of rows in the result */
99521   int nColumn;       /* Number of columns in the result */
99522   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
99523   int rc;            /* Return code from sqlite3_exec() */
99524 } TabResult;
99525 
99526 /*
99527 ** This routine is called once for each row in the result table.  Its job
99528 ** is to fill in the TabResult structure appropriately, allocating new
99529 ** memory as necessary.
99530 */
99531 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
99532   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
99533   int need;                         /* Slots needed in p->azResult[] */
99534   int i;                            /* Loop counter */
99535   char *z;                          /* A single column of result */
99536 
99537   /* Make sure there is enough space in p->azResult to hold everything
99538   ** we need to remember from this invocation of the callback.
99539   */
99540   if( p->nRow==0 && argv!=0 ){
99541     need = nCol*2;
99542   }else{
99543     need = nCol;
99544   }
99545   if( p->nData + need > p->nAlloc ){
99546     char **azNew;
99547     p->nAlloc = p->nAlloc*2 + need;
99548     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
99549     if( azNew==0 ) goto malloc_failed;
99550     p->azResult = azNew;
99551   }
99552 
99553   /* If this is the first row, then generate an extra row containing
99554   ** the names of all columns.
99555   */
99556   if( p->nRow==0 ){
99557     p->nColumn = nCol;
99558     for(i=0; i<nCol; i++){
99559       z = sqlite3_mprintf("%s", colv[i]);
99560       if( z==0 ) goto malloc_failed;
99561       p->azResult[p->nData++] = z;
99562     }
99563   }else if( p->nColumn!=nCol ){
99564     sqlite3_free(p->zErrMsg);
99565     p->zErrMsg = sqlite3_mprintf(
99566        "sqlite3_get_table() called with two or more incompatible queries"
99567     );
99568     p->rc = SQLITE_ERROR;
99569     return 1;
99570   }
99571 
99572   /* Copy over the row data
99573   */
99574   if( argv!=0 ){
99575     for(i=0; i<nCol; i++){
99576       if( argv[i]==0 ){
99577         z = 0;
99578       }else{
99579         int n = sqlite3Strlen30(argv[i])+1;
99580         z = sqlite3_malloc( n );
99581         if( z==0 ) goto malloc_failed;
99582         memcpy(z, argv[i], n);
99583       }
99584       p->azResult[p->nData++] = z;
99585     }
99586     p->nRow++;
99587   }
99588   return 0;
99589 
99590 malloc_failed:
99591   p->rc = SQLITE_NOMEM;
99592   return 1;
99593 }
99594 
99595 /*
99596 ** Query the database.  But instead of invoking a callback for each row,
99597 ** malloc() for space to hold the result and return the entire results
99598 ** at the conclusion of the call.
99599 **
99600 ** The result that is written to ***pazResult is held in memory obtained
99601 ** from malloc().  But the caller cannot free this memory directly.
99602 ** Instead, the entire table should be passed to sqlite3_free_table() when
99603 ** the calling procedure is finished using it.
99604 */
99605 SQLITE_API int sqlite3_get_table(
99606   sqlite3 *db,                /* The database on which the SQL executes */
99607   const char *zSql,           /* The SQL to be executed */
99608   char ***pazResult,          /* Write the result table here */
99609   int *pnRow,                 /* Write the number of rows in the result here */
99610   int *pnColumn,              /* Write the number of columns of result here */
99611   char **pzErrMsg             /* Write error messages here */
99612 ){
99613   int rc;
99614   TabResult res;
99615 
99616   *pazResult = 0;
99617   if( pnColumn ) *pnColumn = 0;
99618   if( pnRow ) *pnRow = 0;
99619   if( pzErrMsg ) *pzErrMsg = 0;
99620   res.zErrMsg = 0;
99621   res.nRow = 0;
99622   res.nColumn = 0;
99623   res.nData = 1;
99624   res.nAlloc = 20;
99625   res.rc = SQLITE_OK;
99626   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
99627   if( res.azResult==0 ){
99628      db->errCode = SQLITE_NOMEM;
99629      return SQLITE_NOMEM;
99630   }
99631   res.azResult[0] = 0;
99632   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
99633   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
99634   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
99635   if( (rc&0xff)==SQLITE_ABORT ){
99636     sqlite3_free_table(&res.azResult[1]);
99637     if( res.zErrMsg ){
99638       if( pzErrMsg ){
99639         sqlite3_free(*pzErrMsg);
99640         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
99641       }
99642       sqlite3_free(res.zErrMsg);
99643     }
99644     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
99645     return res.rc;
99646   }
99647   sqlite3_free(res.zErrMsg);
99648   if( rc!=SQLITE_OK ){
99649     sqlite3_free_table(&res.azResult[1]);
99650     return rc;
99651   }
99652   if( res.nAlloc>res.nData ){
99653     char **azNew;
99654     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
99655     if( azNew==0 ){
99656       sqlite3_free_table(&res.azResult[1]);
99657       db->errCode = SQLITE_NOMEM;
99658       return SQLITE_NOMEM;
99659     }
99660     res.azResult = azNew;
99661   }
99662   *pazResult = &res.azResult[1];
99663   if( pnColumn ) *pnColumn = res.nColumn;
99664   if( pnRow ) *pnRow = res.nRow;
99665   return rc;
99666 }
99667 
99668 /*
99669 ** This routine frees the space the sqlite3_get_table() malloced.
99670 */
99671 SQLITE_API void sqlite3_free_table(
99672   char **azResult            /* Result returned from from sqlite3_get_table() */
99673 ){
99674   if( azResult ){
99675     int i, n;
99676     azResult--;
99677     assert( azResult!=0 );
99678     n = SQLITE_PTR_TO_INT(azResult[0]);
99679     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
99680     sqlite3_free(azResult);
99681   }
99682 }
99683 
99684 #endif /* SQLITE_OMIT_GET_TABLE */
99685 
99686 /************** End of table.c ***********************************************/
99687 /************** Begin file trigger.c *****************************************/
99688 /*
99689 **
99690 ** The author disclaims copyright to this source code.  In place of
99691 ** a legal notice, here is a blessing:
99692 **
99693 **    May you do good and not evil.
99694 **    May you find forgiveness for yourself and forgive others.
99695 **    May you share freely, never taking more than you give.
99696 **
99697 *************************************************************************
99698 ** This file contains the implementation for TRIGGERs
99699 */
99700 
99701 #ifndef SQLITE_OMIT_TRIGGER
99702 /*
99703 ** Delete a linked list of TriggerStep structures.
99704 */
99705 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
99706   while( pTriggerStep ){
99707     TriggerStep * pTmp = pTriggerStep;
99708     pTriggerStep = pTriggerStep->pNext;
99709 
99710     sqlite3ExprDelete(db, pTmp->pWhere);
99711     sqlite3ExprListDelete(db, pTmp->pExprList);
99712     sqlite3SelectDelete(db, pTmp->pSelect);
99713     sqlite3IdListDelete(db, pTmp->pIdList);
99714 
99715     sqlite3DbFree(db, pTmp);
99716   }
99717 }
99718 
99719 /*
99720 ** Given table pTab, return a list of all the triggers attached to
99721 ** the table. The list is connected by Trigger.pNext pointers.
99722 **
99723 ** All of the triggers on pTab that are in the same database as pTab
99724 ** are already attached to pTab->pTrigger.  But there might be additional
99725 ** triggers on pTab in the TEMP schema.  This routine prepends all
99726 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
99727 ** and returns the combined list.
99728 **
99729 ** To state it another way:  This routine returns a list of all triggers
99730 ** that fire off of pTab.  The list will include any TEMP triggers on
99731 ** pTab as well as the triggers lised in pTab->pTrigger.
99732 */
99733 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
99734   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
99735   Trigger *pList = 0;                  /* List of triggers to return */
99736 
99737   if( pParse->disableTriggers ){
99738     return 0;
99739   }
99740 
99741   if( pTmpSchema!=pTab->pSchema ){
99742     HashElem *p;
99743     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
99744     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
99745       Trigger *pTrig = (Trigger *)sqliteHashData(p);
99746       if( pTrig->pTabSchema==pTab->pSchema
99747        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
99748       ){
99749         pTrig->pNext = (pList ? pList : pTab->pTrigger);
99750         pList = pTrig;
99751       }
99752     }
99753   }
99754 
99755   return (pList ? pList : pTab->pTrigger);
99756 }
99757 
99758 /*
99759 ** This is called by the parser when it sees a CREATE TRIGGER statement
99760 ** up to the point of the BEGIN before the trigger actions.  A Trigger
99761 ** structure is generated based on the information available and stored
99762 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99763 ** sqlite3FinishTrigger() function is called to complete the trigger
99764 ** construction process.
99765 */
99766 SQLITE_PRIVATE void sqlite3BeginTrigger(
99767   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99768   Token *pName1,      /* The name of the trigger */
99769   Token *pName2,      /* The name of the trigger */
99770   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99771   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99772   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99773   SrcList *pTableName,/* The name of the table/view the trigger applies to */
99774   Expr *pWhen,        /* WHEN clause */
99775   int isTemp,         /* True if the TEMPORARY keyword is present */
99776   int noErr           /* Suppress errors if the trigger already exists */
99777 ){
99778   Trigger *pTrigger = 0;  /* The new trigger */
99779   Table *pTab;            /* Table that the trigger fires off of */
99780   char *zName = 0;        /* Name of the trigger */
99781   sqlite3 *db = pParse->db;  /* The database connection */
99782   int iDb;                /* The database to store the trigger in */
99783   Token *pName;           /* The unqualified db name */
99784   DbFixer sFix;           /* State vector for the DB fixer */
99785   int iTabDb;             /* Index of the database holding pTab */
99786 
99787   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99788   assert( pName2!=0 );
99789   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99790   assert( op>0 && op<0xff );
99791   if( isTemp ){
99792     /* If TEMP was specified, then the trigger name may not be qualified. */
99793     if( pName2->n>0 ){
99794       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99795       goto trigger_cleanup;
99796     }
99797     iDb = 1;
99798     pName = pName1;
99799   }else{
99800     /* Figure out the db that the trigger will be created in */
99801     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99802     if( iDb<0 ){
99803       goto trigger_cleanup;
99804     }
99805   }
99806   if( !pTableName || db->mallocFailed ){
99807     goto trigger_cleanup;
99808   }
99809 
99810   /* A long-standing parser bug is that this syntax was allowed:
99811   **
99812   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99813   **                                                 ^^^^^^^^
99814   **
99815   ** To maintain backwards compatibility, ignore the database
99816   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
99817   */
99818   if( db->init.busy && iDb!=1 ){
99819     sqlite3DbFree(db, pTableName->a[0].zDatabase);
99820     pTableName->a[0].zDatabase = 0;
99821   }
99822 
99823   /* If the trigger name was unqualified, and the table is a temp table,
99824   ** then set iDb to 1 to create the trigger in the temporary database.
99825   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
99826   ** exist, the error is caught by the block below.
99827   */
99828   pTab = sqlite3SrcListLookup(pParse, pTableName);
99829   if( db->init.busy==0 && pName2->n==0 && pTab
99830         && pTab->pSchema==db->aDb[1].pSchema ){
99831     iDb = 1;
99832   }
99833 
99834   /* Ensure the table name matches database name and that the table exists */
99835   if( db->mallocFailed ) goto trigger_cleanup;
99836   assert( pTableName->nSrc==1 );
99837   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
99838       sqlite3FixSrcList(&sFix, pTableName) ){
99839     goto trigger_cleanup;
99840   }
99841   pTab = sqlite3SrcListLookup(pParse, pTableName);
99842   if( !pTab ){
99843     /* The table does not exist. */
99844     if( db->init.iDb==1 ){
99845       /* Ticket #3810.
99846       ** Normally, whenever a table is dropped, all associated triggers are
99847       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99848       ** and the table is dropped by a different database connection, the
99849       ** trigger is not visible to the database connection that does the
99850       ** drop so the trigger cannot be dropped.  This results in an
99851       ** "orphaned trigger" - a trigger whose associated table is missing.
99852       */
99853       db->init.orphanTrigger = 1;
99854     }
99855     goto trigger_cleanup;
99856   }
99857   if( IsVirtual(pTab) ){
99858     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99859     goto trigger_cleanup;
99860   }
99861 
99862   /* Check that the trigger name is not reserved and that no trigger of the
99863   ** specified name exists */
99864   zName = sqlite3NameFromToken(db, pName);
99865   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99866     goto trigger_cleanup;
99867   }
99868   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99869   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99870                       zName, sqlite3Strlen30(zName)) ){
99871     if( !noErr ){
99872       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
99873     }else{
99874       assert( !db->init.busy );
99875       sqlite3CodeVerifySchema(pParse, iDb);
99876     }
99877     goto trigger_cleanup;
99878   }
99879 
99880   /* Do not create a trigger on a system table */
99881   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
99882     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
99883     pParse->nErr++;
99884     goto trigger_cleanup;
99885   }
99886 
99887   /* INSTEAD of triggers are only for views and views only support INSTEAD
99888   ** of triggers.
99889   */
99890   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99891     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
99892         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99893     goto trigger_cleanup;
99894   }
99895   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99896     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
99897         " trigger on table: %S", pTableName, 0);
99898     goto trigger_cleanup;
99899   }
99900   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99901 
99902 #ifndef SQLITE_OMIT_AUTHORIZATION
99903   {
99904     int code = SQLITE_CREATE_TRIGGER;
99905     const char *zDb = db->aDb[iTabDb].zName;
99906     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99907     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
99908     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99909       goto trigger_cleanup;
99910     }
99911     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99912       goto trigger_cleanup;
99913     }
99914   }
99915 #endif
99916 
99917   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99918   ** cannot appear on views.  So we might as well translate every
99919   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99920   ** elsewhere.
99921   */
99922   if (tr_tm == TK_INSTEAD){
99923     tr_tm = TK_BEFORE;
99924   }
99925 
99926   /* Build the Trigger object */
99927   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
99928   if( pTrigger==0 ) goto trigger_cleanup;
99929   pTrigger->zName = zName;
99930   zName = 0;
99931   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
99932   pTrigger->pSchema = db->aDb[iDb].pSchema;
99933   pTrigger->pTabSchema = pTab->pSchema;
99934   pTrigger->op = (u8)op;
99935   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99936   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99937   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
99938   assert( pParse->pNewTrigger==0 );
99939   pParse->pNewTrigger = pTrigger;
99940 
99941 trigger_cleanup:
99942   sqlite3DbFree(db, zName);
99943   sqlite3SrcListDelete(db, pTableName);
99944   sqlite3IdListDelete(db, pColumns);
99945   sqlite3ExprDelete(db, pWhen);
99946   if( !pParse->pNewTrigger ){
99947     sqlite3DeleteTrigger(db, pTrigger);
99948   }else{
99949     assert( pParse->pNewTrigger==pTrigger );
99950   }
99951 }
99952 
99953 /*
99954 ** This routine is called after all of the trigger actions have been parsed
99955 ** in order to complete the process of building the trigger.
99956 */
99957 SQLITE_PRIVATE void sqlite3FinishTrigger(
99958   Parse *pParse,          /* Parser context */
99959   TriggerStep *pStepList, /* The triggered program */
99960   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99961 ){
99962   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99963   char *zName;                            /* Name of trigger */
99964   sqlite3 *db = pParse->db;               /* The database */
99965   DbFixer sFix;                           /* Fixer object */
99966   int iDb;                                /* Database containing the trigger */
99967   Token nameToken;                        /* Trigger name for error reporting */
99968 
99969   pParse->pNewTrigger = 0;
99970   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99971   zName = pTrig->zName;
99972   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
99973   pTrig->step_list = pStepList;
99974   while( pStepList ){
99975     pStepList->pTrig = pTrig;
99976     pStepList = pStepList->pNext;
99977   }
99978   nameToken.z = pTrig->zName;
99979   nameToken.n = sqlite3Strlen30(nameToken.z);
99980   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
99981           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
99982     goto triggerfinish_cleanup;
99983   }
99984 
99985   /* if we are not initializing,
99986   ** build the sqlite_master entry
99987   */
99988   if( !db->init.busy ){
99989     Vdbe *v;
99990     char *z;
99991 
99992     /* Make an entry in the sqlite_master table */
99993     v = sqlite3GetVdbe(pParse);
99994     if( v==0 ) goto triggerfinish_cleanup;
99995     sqlite3BeginWriteOperation(pParse, 0, iDb);
99996     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
99997     sqlite3NestedParse(pParse,
99998        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
99999        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
100000        pTrig->table, z);
100001     sqlite3DbFree(db, z);
100002     sqlite3ChangeCookie(pParse, iDb);
100003     sqlite3VdbeAddParseSchemaOp(v, iDb,
100004         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
100005   }
100006 
100007   if( db->init.busy ){
100008     Trigger *pLink = pTrig;
100009     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
100010     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100011     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
100012     if( pTrig ){
100013       db->mallocFailed = 1;
100014     }else if( pLink->pSchema==pLink->pTabSchema ){
100015       Table *pTab;
100016       int n = sqlite3Strlen30(pLink->table);
100017       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
100018       assert( pTab!=0 );
100019       pLink->pNext = pTab->pTrigger;
100020       pTab->pTrigger = pLink;
100021     }
100022   }
100023 
100024 triggerfinish_cleanup:
100025   sqlite3DeleteTrigger(db, pTrig);
100026   assert( !pParse->pNewTrigger );
100027   sqlite3DeleteTriggerStep(db, pStepList);
100028 }
100029 
100030 /*
100031 ** Turn a SELECT statement (that the pSelect parameter points to) into
100032 ** a trigger step.  Return a pointer to a TriggerStep structure.
100033 **
100034 ** The parser calls this routine when it finds a SELECT statement in
100035 ** body of a TRIGGER.
100036 */
100037 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
100038   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
100039   if( pTriggerStep==0 ) {
100040     sqlite3SelectDelete(db, pSelect);
100041     return 0;
100042   }
100043   pTriggerStep->op = TK_SELECT;
100044   pTriggerStep->pSelect = pSelect;
100045   pTriggerStep->orconf = OE_Default;
100046   return pTriggerStep;
100047 }
100048 
100049 /*
100050 ** Allocate space to hold a new trigger step.  The allocated space
100051 ** holds both the TriggerStep object and the TriggerStep.target.z string.
100052 **
100053 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
100054 */
100055 static TriggerStep *triggerStepAllocate(
100056   sqlite3 *db,                /* Database connection */
100057   u8 op,                      /* Trigger opcode */
100058   Token *pName                /* The target name */
100059 ){
100060   TriggerStep *pTriggerStep;
100061 
100062   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
100063   if( pTriggerStep ){
100064     char *z = (char*)&pTriggerStep[1];
100065     memcpy(z, pName->z, pName->n);
100066     pTriggerStep->target.z = z;
100067     pTriggerStep->target.n = pName->n;
100068     pTriggerStep->op = op;
100069   }
100070   return pTriggerStep;
100071 }
100072 
100073 /*
100074 ** Build a trigger step out of an INSERT statement.  Return a pointer
100075 ** to the new trigger step.
100076 **
100077 ** The parser calls this routine when it sees an INSERT inside the
100078 ** body of a trigger.
100079 */
100080 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
100081   sqlite3 *db,        /* The database connection */
100082   Token *pTableName,  /* Name of the table into which we insert */
100083   IdList *pColumn,    /* List of columns in pTableName to insert into */
100084   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
100085   Select *pSelect,    /* A SELECT statement that supplies values */
100086   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
100087 ){
100088   TriggerStep *pTriggerStep;
100089 
100090   assert(pEList == 0 || pSelect == 0);
100091   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
100092 
100093   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
100094   if( pTriggerStep ){
100095     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
100096     pTriggerStep->pIdList = pColumn;
100097     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
100098     pTriggerStep->orconf = orconf;
100099   }else{
100100     sqlite3IdListDelete(db, pColumn);
100101   }
100102   sqlite3ExprListDelete(db, pEList);
100103   sqlite3SelectDelete(db, pSelect);
100104 
100105   return pTriggerStep;
100106 }
100107 
100108 /*
100109 ** Construct a trigger step that implements an UPDATE statement and return
100110 ** a pointer to that trigger step.  The parser calls this routine when it
100111 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
100112 */
100113 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
100114   sqlite3 *db,         /* The database connection */
100115   Token *pTableName,   /* Name of the table to be updated */
100116   ExprList *pEList,    /* The SET clause: list of column and new values */
100117   Expr *pWhere,        /* The WHERE clause */
100118   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
100119 ){
100120   TriggerStep *pTriggerStep;
100121 
100122   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
100123   if( pTriggerStep ){
100124     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
100125     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
100126     pTriggerStep->orconf = orconf;
100127   }
100128   sqlite3ExprListDelete(db, pEList);
100129   sqlite3ExprDelete(db, pWhere);
100130   return pTriggerStep;
100131 }
100132 
100133 /*
100134 ** Construct a trigger step that implements a DELETE statement and return
100135 ** a pointer to that trigger step.  The parser calls this routine when it
100136 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
100137 */
100138 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
100139   sqlite3 *db,            /* Database connection */
100140   Token *pTableName,      /* The table from which rows are deleted */
100141   Expr *pWhere            /* The WHERE clause */
100142 ){
100143   TriggerStep *pTriggerStep;
100144 
100145   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
100146   if( pTriggerStep ){
100147     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
100148     pTriggerStep->orconf = OE_Default;
100149   }
100150   sqlite3ExprDelete(db, pWhere);
100151   return pTriggerStep;
100152 }
100153 
100154 /*
100155 ** Recursively delete a Trigger structure
100156 */
100157 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
100158   if( pTrigger==0 ) return;
100159   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
100160   sqlite3DbFree(db, pTrigger->zName);
100161   sqlite3DbFree(db, pTrigger->table);
100162   sqlite3ExprDelete(db, pTrigger->pWhen);
100163   sqlite3IdListDelete(db, pTrigger->pColumns);
100164   sqlite3DbFree(db, pTrigger);
100165 }
100166 
100167 /*
100168 ** This function is called to drop a trigger from the database schema.
100169 **
100170 ** This may be called directly from the parser and therefore identifies
100171 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
100172 ** same job as this routine except it takes a pointer to the trigger
100173 ** instead of the trigger name.
100174 **/
100175 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
100176   Trigger *pTrigger = 0;
100177   int i;
100178   const char *zDb;
100179   const char *zName;
100180   int nName;
100181   sqlite3 *db = pParse->db;
100182 
100183   if( db->mallocFailed ) goto drop_trigger_cleanup;
100184   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100185     goto drop_trigger_cleanup;
100186   }
100187 
100188   assert( pName->nSrc==1 );
100189   zDb = pName->a[0].zDatabase;
100190   zName = pName->a[0].zName;
100191   nName = sqlite3Strlen30(zName);
100192   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
100193   for(i=OMIT_TEMPDB; i<db->nDb; i++){
100194     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
100195     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
100196     assert( sqlite3SchemaMutexHeld(db, j, 0) );
100197     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
100198     if( pTrigger ) break;
100199   }
100200   if( !pTrigger ){
100201     if( !noErr ){
100202       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
100203     }else{
100204       sqlite3CodeVerifyNamedSchema(pParse, zDb);
100205     }
100206     pParse->checkSchema = 1;
100207     goto drop_trigger_cleanup;
100208   }
100209   sqlite3DropTriggerPtr(pParse, pTrigger);
100210 
100211 drop_trigger_cleanup:
100212   sqlite3SrcListDelete(db, pName);
100213 }
100214 
100215 /*
100216 ** Return a pointer to the Table structure for the table that a trigger
100217 ** is set on.
100218 */
100219 static Table *tableOfTrigger(Trigger *pTrigger){
100220   int n = sqlite3Strlen30(pTrigger->table);
100221   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
100222 }
100223 
100224 
100225 /*
100226 ** Drop a trigger given a pointer to that trigger.
100227 */
100228 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
100229   Table   *pTable;
100230   Vdbe *v;
100231   sqlite3 *db = pParse->db;
100232   int iDb;
100233 
100234   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
100235   assert( iDb>=0 && iDb<db->nDb );
100236   pTable = tableOfTrigger(pTrigger);
100237   assert( pTable );
100238   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
100239 #ifndef SQLITE_OMIT_AUTHORIZATION
100240   {
100241     int code = SQLITE_DROP_TRIGGER;
100242     const char *zDb = db->aDb[iDb].zName;
100243     const char *zTab = SCHEMA_TABLE(iDb);
100244     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
100245     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
100246       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100247       return;
100248     }
100249   }
100250 #endif
100251 
100252   /* Generate code to destroy the database record of the trigger.
100253   */
100254   assert( pTable!=0 );
100255   if( (v = sqlite3GetVdbe(pParse))!=0 ){
100256     int base;
100257     static const VdbeOpList dropTrigger[] = {
100258       { OP_Rewind,     0, ADDR(9),  0},
100259       { OP_String8,    0, 1,        0}, /* 1 */
100260       { OP_Column,     0, 1,        2},
100261       { OP_Ne,         2, ADDR(8),  1},
100262       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
100263       { OP_Column,     0, 0,        2},
100264       { OP_Ne,         2, ADDR(8),  1},
100265       { OP_Delete,     0, 0,        0},
100266       { OP_Next,       0, ADDR(1),  0}, /* 8 */
100267     };
100268 
100269     sqlite3BeginWriteOperation(pParse, 0, iDb);
100270     sqlite3OpenMasterTable(pParse, iDb);
100271     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
100272     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
100273     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
100274     sqlite3ChangeCookie(pParse, iDb);
100275     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
100276     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
100277     if( pParse->nMem<3 ){
100278       pParse->nMem = 3;
100279     }
100280   }
100281 }
100282 
100283 /*
100284 ** Remove a trigger from the hash tables of the sqlite* pointer.
100285 */
100286 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
100287   Trigger *pTrigger;
100288   Hash *pHash;
100289 
100290   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100291   pHash = &(db->aDb[iDb].pSchema->trigHash);
100292   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
100293   if( ALWAYS(pTrigger) ){
100294     if( pTrigger->pSchema==pTrigger->pTabSchema ){
100295       Table *pTab = tableOfTrigger(pTrigger);
100296       Trigger **pp;
100297       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
100298       *pp = (*pp)->pNext;
100299     }
100300     sqlite3DeleteTrigger(db, pTrigger);
100301     db->flags |= SQLITE_InternChanges;
100302   }
100303 }
100304 
100305 /*
100306 ** pEList is the SET clause of an UPDATE statement.  Each entry
100307 ** in pEList is of the format <id>=<expr>.  If any of the entries
100308 ** in pEList have an <id> which matches an identifier in pIdList,
100309 ** then return TRUE.  If pIdList==NULL, then it is considered a
100310 ** wildcard that matches anything.  Likewise if pEList==NULL then
100311 ** it matches anything so always return true.  Return false only
100312 ** if there is no match.
100313 */
100314 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
100315   int e;
100316   if( pIdList==0 || NEVER(pEList==0) ) return 1;
100317   for(e=0; e<pEList->nExpr; e++){
100318     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
100319   }
100320   return 0;
100321 }
100322 
100323 /*
100324 ** Return a list of all triggers on table pTab if there exists at least
100325 ** one trigger that must be fired when an operation of type 'op' is
100326 ** performed on the table, and, if that operation is an UPDATE, if at
100327 ** least one of the columns in pChanges is being modified.
100328 */
100329 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
100330   Parse *pParse,          /* Parse context */
100331   Table *pTab,            /* The table the contains the triggers */
100332   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
100333   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
100334   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100335 ){
100336   int mask = 0;
100337   Trigger *pList = 0;
100338   Trigger *p;
100339 
100340   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
100341     pList = sqlite3TriggerList(pParse, pTab);
100342   }
100343   assert( pList==0 || IsVirtual(pTab)==0 );
100344   for(p=pList; p; p=p->pNext){
100345     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
100346       mask |= p->tr_tm;
100347     }
100348   }
100349   if( pMask ){
100350     *pMask = mask;
100351   }
100352   return (mask ? pList : 0);
100353 }
100354 
100355 /*
100356 ** Convert the pStep->target token into a SrcList and return a pointer
100357 ** to that SrcList.
100358 **
100359 ** This routine adds a specific database name, if needed, to the target when
100360 ** forming the SrcList.  This prevents a trigger in one database from
100361 ** referring to a target in another database.  An exception is when the
100362 ** trigger is in TEMP in which case it can refer to any other database it
100363 ** wants.
100364 */
100365 static SrcList *targetSrcList(
100366   Parse *pParse,       /* The parsing context */
100367   TriggerStep *pStep   /* The trigger containing the target token */
100368 ){
100369   int iDb;             /* Index of the database to use */
100370   SrcList *pSrc;       /* SrcList to be returned */
100371 
100372   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
100373   if( pSrc ){
100374     assert( pSrc->nSrc>0 );
100375     assert( pSrc->a!=0 );
100376     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
100377     if( iDb==0 || iDb>=2 ){
100378       sqlite3 *db = pParse->db;
100379       assert( iDb<pParse->db->nDb );
100380       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
100381     }
100382   }
100383   return pSrc;
100384 }
100385 
100386 /*
100387 ** Generate VDBE code for the statements inside the body of a single
100388 ** trigger.
100389 */
100390 static int codeTriggerProgram(
100391   Parse *pParse,            /* The parser context */
100392   TriggerStep *pStepList,   /* List of statements inside the trigger body */
100393   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
100394 ){
100395   TriggerStep *pStep;
100396   Vdbe *v = pParse->pVdbe;
100397   sqlite3 *db = pParse->db;
100398 
100399   assert( pParse->pTriggerTab && pParse->pToplevel );
100400   assert( pStepList );
100401   assert( v!=0 );
100402   for(pStep=pStepList; pStep; pStep=pStep->pNext){
100403     /* Figure out the ON CONFLICT policy that will be used for this step
100404     ** of the trigger program. If the statement that caused this trigger
100405     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
100406     ** the ON CONFLICT policy that was specified as part of the trigger
100407     ** step statement. Example:
100408     **
100409     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
100410     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
100411     **   END;
100412     **
100413     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
100414     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
100415     */
100416     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
100417 
100418     /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
100419     ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
100420     ** that it is not safe to refactor constants (this happens after the
100421     ** start of the first loop in the SQL statement is coded - at that
100422     ** point code may be conditionally executed, so it is no longer safe to
100423     ** initialize constant register values).  */
100424     assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
100425     pParse->cookieGoto = 0;
100426 
100427     switch( pStep->op ){
100428       case TK_UPDATE: {
100429         sqlite3Update(pParse,
100430           targetSrcList(pParse, pStep),
100431           sqlite3ExprListDup(db, pStep->pExprList, 0),
100432           sqlite3ExprDup(db, pStep->pWhere, 0),
100433           pParse->eOrconf
100434         );
100435         break;
100436       }
100437       case TK_INSERT: {
100438         sqlite3Insert(pParse,
100439           targetSrcList(pParse, pStep),
100440           sqlite3ExprListDup(db, pStep->pExprList, 0),
100441           sqlite3SelectDup(db, pStep->pSelect, 0),
100442           sqlite3IdListDup(db, pStep->pIdList),
100443           pParse->eOrconf
100444         );
100445         break;
100446       }
100447       case TK_DELETE: {
100448         sqlite3DeleteFrom(pParse,
100449           targetSrcList(pParse, pStep),
100450           sqlite3ExprDup(db, pStep->pWhere, 0)
100451         );
100452         break;
100453       }
100454       default: assert( pStep->op==TK_SELECT ); {
100455         SelectDest sDest;
100456         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
100457         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
100458         sqlite3Select(pParse, pSelect, &sDest);
100459         sqlite3SelectDelete(db, pSelect);
100460         break;
100461       }
100462     }
100463     if( pStep->op!=TK_SELECT ){
100464       sqlite3VdbeAddOp0(v, OP_ResetCount);
100465     }
100466   }
100467 
100468   return 0;
100469 }
100470 
100471 #ifdef SQLITE_DEBUG
100472 /*
100473 ** This function is used to add VdbeComment() annotations to a VDBE
100474 ** program. It is not used in production code, only for debugging.
100475 */
100476 static const char *onErrorText(int onError){
100477   switch( onError ){
100478     case OE_Abort:    return "abort";
100479     case OE_Rollback: return "rollback";
100480     case OE_Fail:     return "fail";
100481     case OE_Replace:  return "replace";
100482     case OE_Ignore:   return "ignore";
100483     case OE_Default:  return "default";
100484   }
100485   return "n/a";
100486 }
100487 #endif
100488 
100489 /*
100490 ** Parse context structure pFrom has just been used to create a sub-vdbe
100491 ** (trigger program). If an error has occurred, transfer error information
100492 ** from pFrom to pTo.
100493 */
100494 static void transferParseError(Parse *pTo, Parse *pFrom){
100495   assert( pFrom->zErrMsg==0 || pFrom->nErr );
100496   assert( pTo->zErrMsg==0 || pTo->nErr );
100497   if( pTo->nErr==0 ){
100498     pTo->zErrMsg = pFrom->zErrMsg;
100499     pTo->nErr = pFrom->nErr;
100500   }else{
100501     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
100502   }
100503 }
100504 
100505 /*
100506 ** Create and populate a new TriggerPrg object with a sub-program
100507 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
100508 */
100509 static TriggerPrg *codeRowTrigger(
100510   Parse *pParse,       /* Current parse context */
100511   Trigger *pTrigger,   /* Trigger to code */
100512   Table *pTab,         /* The table pTrigger is attached to */
100513   int orconf           /* ON CONFLICT policy to code trigger program with */
100514 ){
100515   Parse *pTop = sqlite3ParseToplevel(pParse);
100516   sqlite3 *db = pParse->db;   /* Database handle */
100517   TriggerPrg *pPrg;           /* Value to return */
100518   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
100519   Vdbe *v;                    /* Temporary VM */
100520   NameContext sNC;            /* Name context for sub-vdbe */
100521   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
100522   Parse *pSubParse;           /* Parse context for sub-vdbe */
100523   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
100524 
100525   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100526   assert( pTop->pVdbe );
100527 
100528   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
100529   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
100530   ** list of the top-level Parse object sooner rather than later.  */
100531   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
100532   if( !pPrg ) return 0;
100533   pPrg->pNext = pTop->pTriggerPrg;
100534   pTop->pTriggerPrg = pPrg;
100535   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
100536   if( !pProgram ) return 0;
100537   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
100538   pPrg->pTrigger = pTrigger;
100539   pPrg->orconf = orconf;
100540   pPrg->aColmask[0] = 0xffffffff;
100541   pPrg->aColmask[1] = 0xffffffff;
100542 
100543   /* Allocate and populate a new Parse context to use for coding the
100544   ** trigger sub-program.  */
100545   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
100546   if( !pSubParse ) return 0;
100547   memset(&sNC, 0, sizeof(sNC));
100548   sNC.pParse = pSubParse;
100549   pSubParse->db = db;
100550   pSubParse->pTriggerTab = pTab;
100551   pSubParse->pToplevel = pTop;
100552   pSubParse->zAuthContext = pTrigger->zName;
100553   pSubParse->eTriggerOp = pTrigger->op;
100554   pSubParse->nQueryLoop = pParse->nQueryLoop;
100555 
100556   v = sqlite3GetVdbe(pSubParse);
100557   if( v ){
100558     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
100559       pTrigger->zName, onErrorText(orconf),
100560       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
100561         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
100562         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
100563         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
100564       pTab->zName
100565     ));
100566 #ifndef SQLITE_OMIT_TRACE
100567     sqlite3VdbeChangeP4(v, -1,
100568       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
100569     );
100570 #endif
100571 
100572     /* If one was specified, code the WHEN clause. If it evaluates to false
100573     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
100574     ** OP_Halt inserted at the end of the program.  */
100575     if( pTrigger->pWhen ){
100576       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
100577       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
100578        && db->mallocFailed==0
100579       ){
100580         iEndTrigger = sqlite3VdbeMakeLabel(v);
100581         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
100582       }
100583       sqlite3ExprDelete(db, pWhen);
100584     }
100585 
100586     /* Code the trigger program into the sub-vdbe. */
100587     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
100588 
100589     /* Insert an OP_Halt at the end of the sub-program. */
100590     if( iEndTrigger ){
100591       sqlite3VdbeResolveLabel(v, iEndTrigger);
100592     }
100593     sqlite3VdbeAddOp0(v, OP_Halt);
100594     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
100595 
100596     transferParseError(pParse, pSubParse);
100597     if( db->mallocFailed==0 ){
100598       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
100599     }
100600     pProgram->nMem = pSubParse->nMem;
100601     pProgram->nCsr = pSubParse->nTab;
100602     pProgram->nOnce = pSubParse->nOnce;
100603     pProgram->token = (void *)pTrigger;
100604     pPrg->aColmask[0] = pSubParse->oldmask;
100605     pPrg->aColmask[1] = pSubParse->newmask;
100606     sqlite3VdbeDelete(v);
100607   }
100608 
100609   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
100610   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
100611   sqlite3StackFree(db, pSubParse);
100612 
100613   return pPrg;
100614 }
100615 
100616 /*
100617 ** Return a pointer to a TriggerPrg object containing the sub-program for
100618 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
100619 ** TriggerPrg object exists, a new object is allocated and populated before
100620 ** being returned.
100621 */
100622 static TriggerPrg *getRowTrigger(
100623   Parse *pParse,       /* Current parse context */
100624   Trigger *pTrigger,   /* Trigger to code */
100625   Table *pTab,         /* The table trigger pTrigger is attached to */
100626   int orconf           /* ON CONFLICT algorithm. */
100627 ){
100628   Parse *pRoot = sqlite3ParseToplevel(pParse);
100629   TriggerPrg *pPrg;
100630 
100631   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100632 
100633   /* It may be that this trigger has already been coded (or is in the
100634   ** process of being coded). If this is the case, then an entry with
100635   ** a matching TriggerPrg.pTrigger field will be present somewhere
100636   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
100637   for(pPrg=pRoot->pTriggerPrg;
100638       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
100639       pPrg=pPrg->pNext
100640   );
100641 
100642   /* If an existing TriggerPrg could not be located, create a new one. */
100643   if( !pPrg ){
100644     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
100645   }
100646 
100647   return pPrg;
100648 }
100649 
100650 /*
100651 ** Generate code for the trigger program associated with trigger p on
100652 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
100653 ** function are the same as those described in the header function for
100654 ** sqlite3CodeRowTrigger()
100655 */
100656 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
100657   Parse *pParse,       /* Parse context */
100658   Trigger *p,          /* Trigger to code */
100659   Table *pTab,         /* The table to code triggers from */
100660   int reg,             /* Reg array containing OLD.* and NEW.* values */
100661   int orconf,          /* ON CONFLICT policy */
100662   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100663 ){
100664   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
100665   TriggerPrg *pPrg;
100666   pPrg = getRowTrigger(pParse, p, pTab, orconf);
100667   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
100668 
100669   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
100670   ** is a pointer to the sub-vdbe containing the trigger program.  */
100671   if( pPrg ){
100672     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
100673 
100674     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
100675     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
100676     VdbeComment(
100677         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
100678 
100679     /* Set the P5 operand of the OP_Program instruction to non-zero if
100680     ** recursive invocation of this trigger program is disallowed. Recursive
100681     ** invocation is disallowed if (a) the sub-program is really a trigger,
100682     ** not a foreign key action, and (b) the flag to enable recursive triggers
100683     ** is clear.  */
100684     sqlite3VdbeChangeP5(v, (u8)bRecursive);
100685   }
100686 }
100687 
100688 /*
100689 ** This is called to code the required FOR EACH ROW triggers for an operation
100690 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
100691 ** is given by the op paramater. The tr_tm parameter determines whether the
100692 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
100693 ** parameter pChanges is passed the list of columns being modified.
100694 **
100695 ** If there are no triggers that fire at the specified time for the specified
100696 ** operation on pTab, this function is a no-op.
100697 **
100698 ** The reg argument is the address of the first in an array of registers
100699 ** that contain the values substituted for the new.* and old.* references
100700 ** in the trigger program. If N is the number of columns in table pTab
100701 ** (a copy of pTab->nCol), then registers are populated as follows:
100702 **
100703 **   Register       Contains
100704 **   ------------------------------------------------------
100705 **   reg+0          OLD.rowid
100706 **   reg+1          OLD.* value of left-most column of pTab
100707 **   ...            ...
100708 **   reg+N          OLD.* value of right-most column of pTab
100709 **   reg+N+1        NEW.rowid
100710 **   reg+N+2        OLD.* value of left-most column of pTab
100711 **   ...            ...
100712 **   reg+N+N+1      NEW.* value of right-most column of pTab
100713 **
100714 ** For ON DELETE triggers, the registers containing the NEW.* values will
100715 ** never be accessed by the trigger program, so they are not allocated or
100716 ** populated by the caller (there is no data to populate them with anyway).
100717 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
100718 ** are never accessed, and so are not allocated by the caller. So, for an
100719 ** ON INSERT trigger, the value passed to this function as parameter reg
100720 ** is not a readable register, although registers (reg+N) through
100721 ** (reg+N+N+1) are.
100722 **
100723 ** Parameter orconf is the default conflict resolution algorithm for the
100724 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
100725 ** is the instruction that control should jump to if a trigger program
100726 ** raises an IGNORE exception.
100727 */
100728 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
100729   Parse *pParse,       /* Parse context */
100730   Trigger *pTrigger,   /* List of triggers on table pTab */
100731   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
100732   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100733   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
100734   Table *pTab,         /* The table to code triggers from */
100735   int reg,             /* The first in an array of registers (see above) */
100736   int orconf,          /* ON CONFLICT policy */
100737   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100738 ){
100739   Trigger *p;          /* Used to iterate through pTrigger list */
100740 
100741   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
100742   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
100743   assert( (op==TK_UPDATE)==(pChanges!=0) );
100744 
100745   for(p=pTrigger; p; p=p->pNext){
100746 
100747     /* Sanity checking:  The schema for the trigger and for the table are
100748     ** always defined.  The trigger must be in the same schema as the table
100749     ** or else it must be a TEMP trigger. */
100750     assert( p->pSchema!=0 );
100751     assert( p->pTabSchema!=0 );
100752     assert( p->pSchema==p->pTabSchema
100753          || p->pSchema==pParse->db->aDb[1].pSchema );
100754 
100755     /* Determine whether we should code this trigger */
100756     if( p->op==op
100757      && p->tr_tm==tr_tm
100758      && checkColumnOverlap(p->pColumns, pChanges)
100759     ){
100760       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
100761     }
100762   }
100763 }
100764 
100765 /*
100766 ** Triggers may access values stored in the old.* or new.* pseudo-table.
100767 ** This function returns a 32-bit bitmask indicating which columns of the
100768 ** old.* or new.* tables actually are used by triggers. This information
100769 ** may be used by the caller, for example, to avoid having to load the entire
100770 ** old.* record into memory when executing an UPDATE or DELETE command.
100771 **
100772 ** Bit 0 of the returned mask is set if the left-most column of the
100773 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100774 ** the second leftmost column value is required, and so on. If there
100775 ** are more than 32 columns in the table, and at least one of the columns
100776 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
100777 **
100778 ** It is not possible to determine if the old.rowid or new.rowid column is
100779 ** accessed by triggers. The caller must always assume that it is.
100780 **
100781 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100782 ** applies to the old.* table. If 1, the new.* table.
100783 **
100784 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100785 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100786 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100787 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100788 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100789 */
100790 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
100791   Parse *pParse,       /* Parse context */
100792   Trigger *pTrigger,   /* List of triggers on table pTab */
100793   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100794   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100795   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100796   Table *pTab,         /* The table to code triggers from */
100797   int orconf           /* Default ON CONFLICT policy for trigger steps */
100798 ){
100799   const int op = pChanges ? TK_UPDATE : TK_DELETE;
100800   u32 mask = 0;
100801   Trigger *p;
100802 
100803   assert( isNew==1 || isNew==0 );
100804   for(p=pTrigger; p; p=p->pNext){
100805     if( p->op==op && (tr_tm&p->tr_tm)
100806      && checkColumnOverlap(p->pColumns,pChanges)
100807     ){
100808       TriggerPrg *pPrg;
100809       pPrg = getRowTrigger(pParse, p, pTab, orconf);
100810       if( pPrg ){
100811         mask |= pPrg->aColmask[isNew];
100812       }
100813     }
100814   }
100815 
100816   return mask;
100817 }
100818 
100819 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
100820 
100821 /************** End of trigger.c *********************************************/
100822 /************** Begin file update.c ******************************************/
100823 /*
100824 ** 2001 September 15
100825 **
100826 ** The author disclaims copyright to this source code.  In place of
100827 ** a legal notice, here is a blessing:
100828 **
100829 **    May you do good and not evil.
100830 **    May you find forgiveness for yourself and forgive others.
100831 **    May you share freely, never taking more than you give.
100832 **
100833 *************************************************************************
100834 ** This file contains C code routines that are called by the parser
100835 ** to handle UPDATE statements.
100836 */
100837 
100838 #ifndef SQLITE_OMIT_VIRTUALTABLE
100839 /* Forward declaration */
100840 static void updateVirtualTable(
100841   Parse *pParse,       /* The parsing context */
100842   SrcList *pSrc,       /* The virtual table to be modified */
100843   Table *pTab,         /* The virtual table */
100844   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100845   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100846   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100847   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100848   int onError          /* ON CONFLICT strategy */
100849 );
100850 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100851 
100852 /*
100853 ** The most recently coded instruction was an OP_Column to retrieve the
100854 ** i-th column of table pTab. This routine sets the P4 parameter of the
100855 ** OP_Column to the default value, if any.
100856 **
100857 ** The default value of a column is specified by a DEFAULT clause in the
100858 ** column definition. This was either supplied by the user when the table
100859 ** was created, or added later to the table definition by an ALTER TABLE
100860 ** command. If the latter, then the row-records in the table btree on disk
100861 ** may not contain a value for the column and the default value, taken
100862 ** from the P4 parameter of the OP_Column instruction, is returned instead.
100863 ** If the former, then all row-records are guaranteed to include a value
100864 ** for the column and the P4 value is not required.
100865 **
100866 ** Column definitions created by an ALTER TABLE command may only have
100867 ** literal default values specified: a number, null or a string. (If a more
100868 ** complicated default expression value was provided, it is evaluated
100869 ** when the ALTER TABLE is executed and one of the literal values written
100870 ** into the sqlite_master table.)
100871 **
100872 ** Therefore, the P4 parameter is only required if the default value for
100873 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
100874 ** function is capable of transforming these types of expressions into
100875 ** sqlite3_value objects.
100876 **
100877 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
100878 ** on register iReg. This is used when an equivalent integer value is
100879 ** stored in place of an 8-byte floating point value in order to save
100880 ** space.
100881 */
100882 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100883   assert( pTab!=0 );
100884   if( !pTab->pSelect ){
100885     sqlite3_value *pValue;
100886     u8 enc = ENC(sqlite3VdbeDb(v));
100887     Column *pCol = &pTab->aCol[i];
100888     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100889     assert( i<pTab->nCol );
100890     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
100891                          pCol->affinity, &pValue);
100892     if( pValue ){
100893       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100894     }
100895 #ifndef SQLITE_OMIT_FLOATING_POINT
100896     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
100897       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
100898     }
100899 #endif
100900   }
100901 }
100902 
100903 /*
100904 ** Process an UPDATE statement.
100905 **
100906 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100907 **          \_______/ \________/     \______/       \________________/
100908 *            onError   pTabList      pChanges             pWhere
100909 */
100910 SQLITE_PRIVATE void sqlite3Update(
100911   Parse *pParse,         /* The parser context */
100912   SrcList *pTabList,     /* The table in which we should change things */
100913   ExprList *pChanges,    /* Things to be changed */
100914   Expr *pWhere,          /* The WHERE clause.  May be null */
100915   int onError            /* How to handle constraint errors */
100916 ){
100917   int i, j;              /* Loop counters */
100918   Table *pTab;           /* The table to be updated */
100919   int addr = 0;          /* VDBE instruction address of the start of the loop */
100920   WhereInfo *pWInfo;     /* Information about the WHERE clause */
100921   Vdbe *v;               /* The virtual database engine */
100922   Index *pIdx;           /* For looping over indices */
100923   int nIdx;              /* Number of indices that need updating */
100924   int iCur;              /* VDBE Cursor number of pTab */
100925   sqlite3 *db;           /* The database structure */
100926   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100927   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100928                          ** an expression for the i-th column of the table.
100929                          ** aXRef[i]==-1 if the i-th column is not changed. */
100930   int chngRowid;         /* True if the record number is being changed */
100931   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100932   int openAll = 0;       /* True if all indices need to be opened */
100933   AuthContext sContext;  /* The authorization context */
100934   NameContext sNC;       /* The name-context to resolve expressions in */
100935   int iDb;               /* Database containing the table being updated */
100936   int okOnePass;         /* True for one-pass algorithm without the FIFO */
100937   int hasFK;             /* True if foreign key processing is required */
100938 
100939 #ifndef SQLITE_OMIT_TRIGGER
100940   int isView;            /* True when updating a view (INSTEAD OF trigger) */
100941   Trigger *pTrigger;     /* List of triggers on pTab, if required */
100942   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100943 #endif
100944   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100945 
100946   /* Register Allocations */
100947   int regRowCount = 0;   /* A count of rows changed */
100948   int regOldRowid;       /* The old rowid */
100949   int regNewRowid;       /* The new rowid */
100950   int regNew;            /* Content of the NEW.* table in triggers */
100951   int regOld = 0;        /* Content of OLD.* table in triggers */
100952   int regRowSet = 0;     /* Rowset of rows to be updated */
100953 
100954   memset(&sContext, 0, sizeof(sContext));
100955   db = pParse->db;
100956   if( pParse->nErr || db->mallocFailed ){
100957     goto update_cleanup;
100958   }
100959   assert( pTabList->nSrc==1 );
100960 
100961   /* Locate the table which we want to update.
100962   */
100963   pTab = sqlite3SrcListLookup(pParse, pTabList);
100964   if( pTab==0 ) goto update_cleanup;
100965   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100966 
100967   /* Figure out if we have any triggers and if the table being
100968   ** updated is a view.
100969   */
100970 #ifndef SQLITE_OMIT_TRIGGER
100971   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100972   isView = pTab->pSelect!=0;
100973   assert( pTrigger || tmask==0 );
100974 #else
100975 # define pTrigger 0
100976 # define isView 0
100977 # define tmask 0
100978 #endif
100979 #ifdef SQLITE_OMIT_VIEW
100980 # undef isView
100981 # define isView 0
100982 #endif
100983 
100984   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
100985     goto update_cleanup;
100986   }
100987   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
100988     goto update_cleanup;
100989   }
100990   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100991   if( aXRef==0 ) goto update_cleanup;
100992   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100993 
100994   /* Allocate a cursors for the main database table and for all indices.
100995   ** The index cursors might not be used, but if they are used they
100996   ** need to occur right after the database cursor.  So go ahead and
100997   ** allocate enough space, just in case.
100998   */
100999   pTabList->a[0].iCursor = iCur = pParse->nTab++;
101000   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101001     pParse->nTab++;
101002   }
101003 
101004   /* Initialize the name-context */
101005   memset(&sNC, 0, sizeof(sNC));
101006   sNC.pParse = pParse;
101007   sNC.pSrcList = pTabList;
101008 
101009   /* Resolve the column names in all the expressions of the
101010   ** of the UPDATE statement.  Also find the column index
101011   ** for each column to be updated in the pChanges array.  For each
101012   ** column to be updated, make sure we have authorization to change
101013   ** that column.
101014   */
101015   chngRowid = 0;
101016   for(i=0; i<pChanges->nExpr; i++){
101017     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
101018       goto update_cleanup;
101019     }
101020     for(j=0; j<pTab->nCol; j++){
101021       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
101022         if( j==pTab->iPKey ){
101023           chngRowid = 1;
101024           pRowidExpr = pChanges->a[i].pExpr;
101025         }
101026         aXRef[j] = i;
101027         break;
101028       }
101029     }
101030     if( j>=pTab->nCol ){
101031       if( sqlite3IsRowid(pChanges->a[i].zName) ){
101032         chngRowid = 1;
101033         pRowidExpr = pChanges->a[i].pExpr;
101034       }else{
101035         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
101036         pParse->checkSchema = 1;
101037         goto update_cleanup;
101038       }
101039     }
101040 #ifndef SQLITE_OMIT_AUTHORIZATION
101041     {
101042       int rc;
101043       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
101044                            pTab->aCol[j].zName, db->aDb[iDb].zName);
101045       if( rc==SQLITE_DENY ){
101046         goto update_cleanup;
101047       }else if( rc==SQLITE_IGNORE ){
101048         aXRef[j] = -1;
101049       }
101050     }
101051 #endif
101052   }
101053 
101054   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
101055 
101056   /* Allocate memory for the array aRegIdx[].  There is one entry in the
101057   ** array for each index associated with table being updated.  Fill in
101058   ** the value with a register number for indices that are to be used
101059   ** and with zero for unused indices.
101060   */
101061   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
101062   if( nIdx>0 ){
101063     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
101064     if( aRegIdx==0 ) goto update_cleanup;
101065   }
101066   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
101067     int reg;
101068     if( hasFK || chngRowid ){
101069       reg = ++pParse->nMem;
101070     }else{
101071       reg = 0;
101072       for(i=0; i<pIdx->nColumn; i++){
101073         if( aXRef[pIdx->aiColumn[i]]>=0 ){
101074           reg = ++pParse->nMem;
101075           break;
101076         }
101077       }
101078     }
101079     aRegIdx[j] = reg;
101080   }
101081 
101082   /* Begin generating code. */
101083   v = sqlite3GetVdbe(pParse);
101084   if( v==0 ) goto update_cleanup;
101085   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
101086   sqlite3BeginWriteOperation(pParse, 1, iDb);
101087 
101088 #ifndef SQLITE_OMIT_VIRTUALTABLE
101089   /* Virtual tables must be handled separately */
101090   if( IsVirtual(pTab) ){
101091     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
101092                        pWhere, onError);
101093     pWhere = 0;
101094     pTabList = 0;
101095     goto update_cleanup;
101096   }
101097 #endif
101098 
101099   /* Allocate required registers. */
101100   regRowSet = ++pParse->nMem;
101101   regOldRowid = regNewRowid = ++pParse->nMem;
101102   if( pTrigger || hasFK ){
101103     regOld = pParse->nMem + 1;
101104     pParse->nMem += pTab->nCol;
101105   }
101106   if( chngRowid || pTrigger || hasFK ){
101107     regNewRowid = ++pParse->nMem;
101108   }
101109   regNew = pParse->nMem + 1;
101110   pParse->nMem += pTab->nCol;
101111 
101112   /* Start the view context. */
101113   if( isView ){
101114     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
101115   }
101116 
101117   /* If we are trying to update a view, realize that view into
101118   ** a ephemeral table.
101119   */
101120 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
101121   if( isView ){
101122     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
101123   }
101124 #endif
101125 
101126   /* Resolve the column names in all the expressions in the
101127   ** WHERE clause.
101128   */
101129   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
101130     goto update_cleanup;
101131   }
101132 
101133   /* Begin the database scan
101134   */
101135   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
101136   pWInfo = sqlite3WhereBegin(
101137       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
101138   );
101139   if( pWInfo==0 ) goto update_cleanup;
101140   okOnePass = pWInfo->okOnePass;
101141 
101142   /* Remember the rowid of every item to be updated.
101143   */
101144   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
101145   if( !okOnePass ){
101146     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
101147   }
101148 
101149   /* End the database scan loop.
101150   */
101151   sqlite3WhereEnd(pWInfo);
101152 
101153   /* Initialize the count of updated rows
101154   */
101155   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
101156     regRowCount = ++pParse->nMem;
101157     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
101158   }
101159 
101160   if( !isView ){
101161     /*
101162     ** Open every index that needs updating.  Note that if any
101163     ** index could potentially invoke a REPLACE conflict resolution
101164     ** action, then we need to open all indices because we might need
101165     ** to be deleting some records.
101166     */
101167     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
101168     if( onError==OE_Replace ){
101169       openAll = 1;
101170     }else{
101171       openAll = 0;
101172       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101173         if( pIdx->onError==OE_Replace ){
101174           openAll = 1;
101175           break;
101176         }
101177       }
101178     }
101179     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101180       assert( aRegIdx );
101181       if( openAll || aRegIdx[i]>0 ){
101182         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
101183         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
101184                        (char*)pKey, P4_KEYINFO_HANDOFF);
101185         assert( pParse->nTab>iCur+i+1 );
101186       }
101187     }
101188   }
101189 
101190   /* Top of the update loop */
101191   if( okOnePass ){
101192     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
101193     addr = sqlite3VdbeAddOp0(v, OP_Goto);
101194     sqlite3VdbeJumpHere(v, a1);
101195   }else{
101196     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
101197   }
101198 
101199   /* Make cursor iCur point to the record that is being updated. If
101200   ** this record does not exist for some reason (deleted by a trigger,
101201   ** for example, then jump to the next iteration of the RowSet loop.  */
101202   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
101203 
101204   /* If the record number will change, set register regNewRowid to
101205   ** contain the new value. If the record number is not being modified,
101206   ** then regNewRowid is the same register as regOldRowid, which is
101207   ** already populated.  */
101208   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
101209   if( chngRowid ){
101210     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
101211     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
101212   }
101213 
101214   /* If there are triggers on this table, populate an array of registers
101215   ** with the required old.* column data.  */
101216   if( hasFK || pTrigger ){
101217     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
101218     oldmask |= sqlite3TriggerColmask(pParse,
101219         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
101220     );
101221     for(i=0; i<pTab->nCol; i++){
101222       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
101223         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
101224       }else{
101225         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
101226       }
101227     }
101228     if( chngRowid==0 ){
101229       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
101230     }
101231   }
101232 
101233   /* Populate the array of registers beginning at regNew with the new
101234   ** row data. This array is used to check constaints, create the new
101235   ** table and index records, and as the values for any new.* references
101236   ** made by triggers.
101237   **
101238   ** If there are one or more BEFORE triggers, then do not populate the
101239   ** registers associated with columns that are (a) not modified by
101240   ** this UPDATE statement and (b) not accessed by new.* references. The
101241   ** values for registers not modified by the UPDATE must be reloaded from
101242   ** the database after the BEFORE triggers are fired anyway (as the trigger
101243   ** may have modified them). So not loading those that are not going to
101244   ** be used eliminates some redundant opcodes.
101245   */
101246   newmask = sqlite3TriggerColmask(
101247       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
101248   );
101249   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
101250   for(i=0; i<pTab->nCol; i++){
101251     if( i==pTab->iPKey ){
101252       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
101253     }else{
101254       j = aXRef[i];
101255       if( j>=0 ){
101256         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
101257       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
101258         /* This branch loads the value of a column that will not be changed
101259         ** into a register. This is done if there are no BEFORE triggers, or
101260         ** if there are one or more BEFORE triggers that use this value via
101261         ** a new.* reference in a trigger program.
101262         */
101263         testcase( i==31 );
101264         testcase( i==32 );
101265         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
101266         sqlite3ColumnDefault(v, pTab, i, regNew+i);
101267       }
101268     }
101269   }
101270 
101271   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
101272   ** verified. One could argue that this is wrong.
101273   */
101274   if( tmask&TRIGGER_BEFORE ){
101275     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
101276     sqlite3TableAffinityStr(v, pTab);
101277     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
101278         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
101279 
101280     /* The row-trigger may have deleted the row being updated. In this
101281     ** case, jump to the next row. No updates or AFTER triggers are
101282     ** required. This behavior - what happens when the row being updated
101283     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
101284     ** documentation.
101285     */
101286     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
101287 
101288     /* If it did not delete it, the row-trigger may still have modified
101289     ** some of the columns of the row being updated. Load the values for
101290     ** all columns not modified by the update statement into their
101291     ** registers in case this has happened.
101292     */
101293     for(i=0; i<pTab->nCol; i++){
101294       if( aXRef[i]<0 && i!=pTab->iPKey ){
101295         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
101296         sqlite3ColumnDefault(v, pTab, i, regNew+i);
101297       }
101298     }
101299   }
101300 
101301   if( !isView ){
101302     int j1;                       /* Address of jump instruction */
101303 
101304     /* Do constraint checks. */
101305     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
101306         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
101307 
101308     /* Do FK constraint checks. */
101309     if( hasFK ){
101310       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
101311     }
101312 
101313     /* Delete the index entries associated with the current record.  */
101314     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
101315     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
101316 
101317     /* If changing the record number, delete the old record.  */
101318     if( hasFK || chngRowid ){
101319       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
101320     }
101321     sqlite3VdbeJumpHere(v, j1);
101322 
101323     if( hasFK ){
101324       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
101325     }
101326 
101327     /* Insert the new index entries and the new record. */
101328     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
101329 
101330     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
101331     ** handle rows (possibly in other tables) that refer via a foreign key
101332     ** to the row just updated. */
101333     if( hasFK ){
101334       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
101335     }
101336   }
101337 
101338   /* Increment the row counter
101339   */
101340   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
101341     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
101342   }
101343 
101344   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
101345       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
101346 
101347   /* Repeat the above with the next record to be updated, until
101348   ** all record selected by the WHERE clause have been updated.
101349   */
101350   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
101351   sqlite3VdbeJumpHere(v, addr);
101352 
101353   /* Close all tables */
101354   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101355     assert( aRegIdx );
101356     if( openAll || aRegIdx[i]>0 ){
101357       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
101358     }
101359   }
101360   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
101361 
101362   /* Update the sqlite_sequence table by storing the content of the
101363   ** maximum rowid counter values recorded while inserting into
101364   ** autoincrement tables.
101365   */
101366   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
101367     sqlite3AutoincrementEnd(pParse);
101368   }
101369 
101370   /*
101371   ** Return the number of rows that were changed. If this routine is
101372   ** generating code because of a call to sqlite3NestedParse(), do not
101373   ** invoke the callback function.
101374   */
101375   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
101376     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
101377     sqlite3VdbeSetNumCols(v, 1);
101378     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
101379   }
101380 
101381 update_cleanup:
101382   sqlite3AuthContextPop(&sContext);
101383   sqlite3DbFree(db, aRegIdx);
101384   sqlite3DbFree(db, aXRef);
101385   sqlite3SrcListDelete(db, pTabList);
101386   sqlite3ExprListDelete(db, pChanges);
101387   sqlite3ExprDelete(db, pWhere);
101388   return;
101389 }
101390 /* Make sure "isView" and other macros defined above are undefined. Otherwise
101391 ** thely may interfere with compilation of other functions in this file
101392 ** (or in another file, if this file becomes part of the amalgamation).  */
101393 #ifdef isView
101394  #undef isView
101395 #endif
101396 #ifdef pTrigger
101397  #undef pTrigger
101398 #endif
101399 
101400 #ifndef SQLITE_OMIT_VIRTUALTABLE
101401 /*
101402 ** Generate code for an UPDATE of a virtual table.
101403 **
101404 ** The strategy is that we create an ephemerial table that contains
101405 ** for each row to be changed:
101406 **
101407 **   (A)  The original rowid of that row.
101408 **   (B)  The revised rowid for the row. (note1)
101409 **   (C)  The content of every column in the row.
101410 **
101411 ** Then we loop over this ephemeral table and for each row in
101412 ** the ephermeral table call VUpdate.
101413 **
101414 ** When finished, drop the ephemeral table.
101415 **
101416 ** (note1) Actually, if we know in advance that (A) is always the same
101417 ** as (B) we only store (A), then duplicate (A) when pulling
101418 ** it out of the ephemeral table before calling VUpdate.
101419 */
101420 static void updateVirtualTable(
101421   Parse *pParse,       /* The parsing context */
101422   SrcList *pSrc,       /* The virtual table to be modified */
101423   Table *pTab,         /* The virtual table */
101424   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
101425   Expr *pRowid,        /* Expression used to recompute the rowid */
101426   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
101427   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
101428   int onError          /* ON CONFLICT strategy */
101429 ){
101430   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
101431   ExprList *pEList = 0;     /* The result set of the SELECT statement */
101432   Select *pSelect = 0;      /* The SELECT statement */
101433   Expr *pExpr;              /* Temporary expression */
101434   int ephemTab;             /* Table holding the result of the SELECT */
101435   int i;                    /* Loop counter */
101436   int addr;                 /* Address of top of loop */
101437   int iReg;                 /* First register in set passed to OP_VUpdate */
101438   sqlite3 *db = pParse->db; /* Database connection */
101439   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
101440   SelectDest dest;
101441 
101442   /* Construct the SELECT statement that will find the new values for
101443   ** all updated rows.
101444   */
101445   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
101446   if( pRowid ){
101447     pEList = sqlite3ExprListAppend(pParse, pEList,
101448                                    sqlite3ExprDup(db, pRowid, 0));
101449   }
101450   assert( pTab->iPKey<0 );
101451   for(i=0; i<pTab->nCol; i++){
101452     if( aXRef[i]>=0 ){
101453       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
101454     }else{
101455       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
101456     }
101457     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
101458   }
101459   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
101460 
101461   /* Create the ephemeral table into which the update results will
101462   ** be stored.
101463   */
101464   assert( v );
101465   ephemTab = pParse->nTab++;
101466   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
101467   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
101468 
101469   /* fill the ephemeral table
101470   */
101471   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
101472   sqlite3Select(pParse, pSelect, &dest);
101473 
101474   /* Generate code to scan the ephemeral table and call VUpdate. */
101475   iReg = ++pParse->nMem;
101476   pParse->nMem += pTab->nCol+1;
101477   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
101478   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
101479   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
101480   for(i=0; i<pTab->nCol; i++){
101481     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
101482   }
101483   sqlite3VtabMakeWritable(pParse, pTab);
101484   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
101485   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
101486   sqlite3MayAbort(pParse);
101487   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
101488   sqlite3VdbeJumpHere(v, addr);
101489   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
101490 
101491   /* Cleanup */
101492   sqlite3SelectDelete(db, pSelect);
101493 }
101494 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101495 
101496 /************** End of update.c **********************************************/
101497 /************** Begin file vacuum.c ******************************************/
101498 /*
101499 ** 2003 April 6
101500 **
101501 ** The author disclaims copyright to this source code.  In place of
101502 ** a legal notice, here is a blessing:
101503 **
101504 **    May you do good and not evil.
101505 **    May you find forgiveness for yourself and forgive others.
101506 **    May you share freely, never taking more than you give.
101507 **
101508 *************************************************************************
101509 ** This file contains code used to implement the VACUUM command.
101510 **
101511 ** Most of the code in this file may be omitted by defining the
101512 ** SQLITE_OMIT_VACUUM macro.
101513 */
101514 
101515 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
101516 /*
101517 ** Finalize a prepared statement.  If there was an error, store the
101518 ** text of the error message in *pzErrMsg.  Return the result code.
101519 */
101520 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
101521   int rc;
101522   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
101523   if( rc ){
101524     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101525   }
101526   return rc;
101527 }
101528 
101529 /*
101530 ** Execute zSql on database db. Return an error code.
101531 */
101532 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101533   sqlite3_stmt *pStmt;
101534   VVA_ONLY( int rc; )
101535   if( !zSql ){
101536     return SQLITE_NOMEM;
101537   }
101538   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
101539     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101540     return sqlite3_errcode(db);
101541   }
101542   VVA_ONLY( rc = ) sqlite3_step(pStmt);
101543   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
101544   return vacuumFinalize(db, pStmt, pzErrMsg);
101545 }
101546 
101547 /*
101548 ** Execute zSql on database db. The statement returns exactly
101549 ** one column. Execute this as SQL on the same database.
101550 */
101551 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101552   sqlite3_stmt *pStmt;
101553   int rc;
101554 
101555   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
101556   if( rc!=SQLITE_OK ) return rc;
101557 
101558   while( SQLITE_ROW==sqlite3_step(pStmt) ){
101559     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
101560     if( rc!=SQLITE_OK ){
101561       vacuumFinalize(db, pStmt, pzErrMsg);
101562       return rc;
101563     }
101564   }
101565 
101566   return vacuumFinalize(db, pStmt, pzErrMsg);
101567 }
101568 
101569 /*
101570 ** The non-standard VACUUM command is used to clean up the database,
101571 ** collapse free space, etc.  It is modelled after the VACUUM command
101572 ** in PostgreSQL.
101573 **
101574 ** In version 1.0.x of SQLite, the VACUUM command would call
101575 ** gdbm_reorganize() on all the database tables.  But beginning
101576 ** with 2.0.0, SQLite no longer uses GDBM so this command has
101577 ** become a no-op.
101578 */
101579 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
101580   Vdbe *v = sqlite3GetVdbe(pParse);
101581   if( v ){
101582     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
101583     sqlite3VdbeUsesBtree(v, 0);
101584   }
101585   return;
101586 }
101587 
101588 /*
101589 ** This routine implements the OP_Vacuum opcode of the VDBE.
101590 */
101591 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
101592   int rc = SQLITE_OK;     /* Return code from service routines */
101593   Btree *pMain;           /* The database being vacuumed */
101594   Btree *pTemp;           /* The temporary database we vacuum into */
101595   char *zSql = 0;         /* SQL statements */
101596   int saved_flags;        /* Saved value of the db->flags */
101597   int saved_nChange;      /* Saved value of db->nChange */
101598   int saved_nTotalChange; /* Saved value of db->nTotalChange */
101599   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
101600   Db *pDb = 0;            /* Database to detach at end of vacuum */
101601   int isMemDb;            /* True if vacuuming a :memory: database */
101602   int nRes;               /* Bytes of reserved space at the end of each page */
101603   int nDb;                /* Number of attached databases */
101604 
101605   if( !db->autoCommit ){
101606     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
101607     return SQLITE_ERROR;
101608   }
101609   if( db->activeVdbeCnt>1 ){
101610     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
101611     return SQLITE_ERROR;
101612   }
101613 
101614   /* Save the current value of the database flags so that it can be
101615   ** restored before returning. Then set the writable-schema flag, and
101616   ** disable CHECK and foreign key constraints.  */
101617   saved_flags = db->flags;
101618   saved_nChange = db->nChange;
101619   saved_nTotalChange = db->nTotalChange;
101620   saved_xTrace = db->xTrace;
101621   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
101622   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
101623   db->xTrace = 0;
101624 
101625   pMain = db->aDb[0].pBt;
101626   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
101627 
101628   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
101629   ** can be set to 'off' for this file, as it is not recovered if a crash
101630   ** occurs anyway. The integrity of the database is maintained by a
101631   ** (possibly synchronous) transaction opened on the main database before
101632   ** sqlite3BtreeCopyFile() is called.
101633   **
101634   ** An optimisation would be to use a non-journaled pager.
101635   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
101636   ** that actually made the VACUUM run slower.  Very little journalling
101637   ** actually occurs when doing a vacuum since the vacuum_db is initially
101638   ** empty.  Only the journal header is written.  Apparently it takes more
101639   ** time to parse and run the PRAGMA to turn journalling off than it does
101640   ** to write the journal header file.
101641   */
101642   nDb = db->nDb;
101643   if( sqlite3TempInMemory(db) ){
101644     zSql = "ATTACH ':memory:' AS vacuum_db;";
101645   }else{
101646     zSql = "ATTACH '' AS vacuum_db;";
101647   }
101648   rc = execSql(db, pzErrMsg, zSql);
101649   if( db->nDb>nDb ){
101650     pDb = &db->aDb[db->nDb-1];
101651     assert( strcmp(pDb->zName,"vacuum_db")==0 );
101652   }
101653   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101654   pTemp = db->aDb[db->nDb-1].pBt;
101655 
101656   /* The call to execSql() to attach the temp database has left the file
101657   ** locked (as there was more than one active statement when the transaction
101658   ** to read the schema was concluded. Unlock it here so that this doesn't
101659   ** cause problems for the call to BtreeSetPageSize() below.  */
101660   sqlite3BtreeCommit(pTemp);
101661 
101662   nRes = sqlite3BtreeGetReserve(pMain);
101663 
101664   /* A VACUUM cannot change the pagesize of an encrypted database. */
101665 #ifdef SQLITE_HAS_CODEC
101666   if( db->nextPagesize ){
101667     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
101668     int nKey;
101669     char *zKey;
101670     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
101671     if( nKey ) db->nextPagesize = 0;
101672   }
101673 #endif
101674 
101675   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
101676   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101677 
101678   /* Begin a transaction and take an exclusive lock on the main database
101679   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
101680   ** to ensure that we do not try to change the page-size on a WAL database.
101681   */
101682   rc = execSql(db, pzErrMsg, "BEGIN;");
101683   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101684   rc = sqlite3BtreeBeginTrans(pMain, 2);
101685   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101686 
101687   /* Do not attempt to change the page size for a WAL database */
101688   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
101689                                                ==PAGER_JOURNALMODE_WAL ){
101690     db->nextPagesize = 0;
101691   }
101692 
101693   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
101694    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
101695    || NEVER(db->mallocFailed)
101696   ){
101697     rc = SQLITE_NOMEM;
101698     goto end_of_vacuum;
101699   }
101700 
101701 #ifndef SQLITE_OMIT_AUTOVACUUM
101702   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
101703                                            sqlite3BtreeGetAutoVacuum(pMain));
101704 #endif
101705 
101706   /* Query the schema of the main database. Create a mirror schema
101707   ** in the temporary database.
101708   */
101709   rc = execExecSql(db, pzErrMsg,
101710       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
101711       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
101712       "   AND rootpage>0"
101713   );
101714   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101715   rc = execExecSql(db, pzErrMsg,
101716       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
101717       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
101718   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101719   rc = execExecSql(db, pzErrMsg,
101720       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
101721       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
101722   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101723 
101724   /* Loop through the tables in the main database. For each, do
101725   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
101726   ** the contents to the temporary database.
101727   */
101728   rc = execExecSql(db, pzErrMsg,
101729       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101730       "|| ' SELECT * FROM main.' || quote(name) || ';'"
101731       "FROM main.sqlite_master "
101732       "WHERE type = 'table' AND name!='sqlite_sequence' "
101733       "  AND rootpage>0"
101734   );
101735   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101736 
101737   /* Copy over the sequence table
101738   */
101739   rc = execExecSql(db, pzErrMsg,
101740       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
101741       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
101742   );
101743   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101744   rc = execExecSql(db, pzErrMsg,
101745       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101746       "|| ' SELECT * FROM main.' || quote(name) || ';' "
101747       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
101748   );
101749   if( rc!=SQLITE_OK ) goto end_of_vacuum;
101750 
101751 
101752   /* Copy the triggers, views, and virtual tables from the main database
101753   ** over to the temporary database.  None of these objects has any
101754   ** associated storage, so all we have to do is copy their entries
101755   ** from the SQLITE_MASTER table.
101756   */
101757   rc = execSql(db, pzErrMsg,
101758       "INSERT INTO vacuum_db.sqlite_master "
101759       "  SELECT type, name, tbl_name, rootpage, sql"
101760       "    FROM main.sqlite_master"
101761       "   WHERE type='view' OR type='trigger'"
101762       "      OR (type='table' AND rootpage=0)"
101763   );
101764   if( rc ) goto end_of_vacuum;
101765 
101766   /* At this point, there is a write transaction open on both the
101767   ** vacuum database and the main database. Assuming no error occurs,
101768   ** both transactions are closed by this block - the main database
101769   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
101770   ** call to sqlite3BtreeCommit().
101771   */
101772   {
101773     u32 meta;
101774     int i;
101775 
101776     /* This array determines which meta meta values are preserved in the
101777     ** vacuum.  Even entries are the meta value number and odd entries
101778     ** are an increment to apply to the meta value after the vacuum.
101779     ** The increment is used to increase the schema cookie so that other
101780     ** connections to the same database will know to reread the schema.
101781     */
101782     static const unsigned char aCopy[] = {
101783        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101784        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101785        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101786        BTREE_USER_VERSION,       0,  /* Preserve the user version */
101787     };
101788 
101789     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
101790     assert( 1==sqlite3BtreeIsInTrans(pMain) );
101791 
101792     /* Copy Btree meta values */
101793     for(i=0; i<ArraySize(aCopy); i+=2){
101794       /* GetMeta() and UpdateMeta() cannot fail in this context because
101795       ** we already have page 1 loaded into cache and marked dirty. */
101796       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
101797       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101798       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
101799     }
101800 
101801     rc = sqlite3BtreeCopyFile(pMain, pTemp);
101802     if( rc!=SQLITE_OK ) goto end_of_vacuum;
101803     rc = sqlite3BtreeCommit(pTemp);
101804     if( rc!=SQLITE_OK ) goto end_of_vacuum;
101805 #ifndef SQLITE_OMIT_AUTOVACUUM
101806     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
101807 #endif
101808   }
101809 
101810   assert( rc==SQLITE_OK );
101811   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
101812 
101813 end_of_vacuum:
101814   /* Restore the original value of db->flags */
101815   db->flags = saved_flags;
101816   db->nChange = saved_nChange;
101817   db->nTotalChange = saved_nTotalChange;
101818   db->xTrace = saved_xTrace;
101819   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
101820 
101821   /* Currently there is an SQL level transaction open on the vacuum
101822   ** database. No locks are held on any other files (since the main file
101823   ** was committed at the btree level). So it safe to end the transaction
101824   ** by manually setting the autoCommit flag to true and detaching the
101825   ** vacuum database. The vacuum_db journal file is deleted when the pager
101826   ** is closed by the DETACH.
101827   */
101828   db->autoCommit = 1;
101829 
101830   if( pDb ){
101831     sqlite3BtreeClose(pDb->pBt);
101832     pDb->pBt = 0;
101833     pDb->pSchema = 0;
101834   }
101835 
101836   /* This both clears the schemas and reduces the size of the db->aDb[]
101837   ** array. */
101838   sqlite3ResetAllSchemasOfConnection(db);
101839 
101840   return rc;
101841 }
101842 
101843 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
101844 
101845 /************** End of vacuum.c **********************************************/
101846 /************** Begin file vtab.c ********************************************/
101847 /*
101848 ** 2006 June 10
101849 **
101850 ** The author disclaims copyright to this source code.  In place of
101851 ** a legal notice, here is a blessing:
101852 **
101853 **    May you do good and not evil.
101854 **    May you find forgiveness for yourself and forgive others.
101855 **    May you share freely, never taking more than you give.
101856 **
101857 *************************************************************************
101858 ** This file contains code used to help implement virtual tables.
101859 */
101860 #ifndef SQLITE_OMIT_VIRTUALTABLE
101861 
101862 /*
101863 ** Before a virtual table xCreate() or xConnect() method is invoked, the
101864 ** sqlite3.pVtabCtx member variable is set to point to an instance of
101865 ** this struct allocated on the stack. It is used by the implementation of
101866 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
101867 ** are invoked only from within xCreate and xConnect methods.
101868 */
101869 struct VtabCtx {
101870   VTable *pVTable;    /* The virtual table being constructed */
101871   Table *pTab;        /* The Table object to which the virtual table belongs */
101872 };
101873 
101874 /*
101875 ** The actual function that does the work of creating a new module.
101876 ** This function implements the sqlite3_create_module() and
101877 ** sqlite3_create_module_v2() interfaces.
101878 */
101879 static int createModule(
101880   sqlite3 *db,                    /* Database in which module is registered */
101881   const char *zName,              /* Name assigned to this module */
101882   const sqlite3_module *pModule,  /* The definition of the module */
101883   void *pAux,                     /* Context pointer for xCreate/xConnect */
101884   void (*xDestroy)(void *)        /* Module destructor function */
101885 ){
101886   int rc = SQLITE_OK;
101887   int nName;
101888 
101889   sqlite3_mutex_enter(db->mutex);
101890   nName = sqlite3Strlen30(zName);
101891   if( sqlite3HashFind(&db->aModule, zName, nName) ){
101892     rc = SQLITE_MISUSE_BKPT;
101893   }else{
101894     Module *pMod;
101895     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
101896     if( pMod ){
101897       Module *pDel;
101898       char *zCopy = (char *)(&pMod[1]);
101899       memcpy(zCopy, zName, nName+1);
101900       pMod->zName = zCopy;
101901       pMod->pModule = pModule;
101902       pMod->pAux = pAux;
101903       pMod->xDestroy = xDestroy;
101904       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
101905       assert( pDel==0 || pDel==pMod );
101906       if( pDel ){
101907         db->mallocFailed = 1;
101908         sqlite3DbFree(db, pDel);
101909       }
101910     }
101911   }
101912   rc = sqlite3ApiExit(db, rc);
101913   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
101914 
101915   sqlite3_mutex_leave(db->mutex);
101916   return rc;
101917 }
101918 
101919 
101920 /*
101921 ** External API function used to create a new virtual-table module.
101922 */
101923 SQLITE_API int sqlite3_create_module(
101924   sqlite3 *db,                    /* Database in which module is registered */
101925   const char *zName,              /* Name assigned to this module */
101926   const sqlite3_module *pModule,  /* The definition of the module */
101927   void *pAux                      /* Context pointer for xCreate/xConnect */
101928 ){
101929   return createModule(db, zName, pModule, pAux, 0);
101930 }
101931 
101932 /*
101933 ** External API function used to create a new virtual-table module.
101934 */
101935 SQLITE_API int sqlite3_create_module_v2(
101936   sqlite3 *db,                    /* Database in which module is registered */
101937   const char *zName,              /* Name assigned to this module */
101938   const sqlite3_module *pModule,  /* The definition of the module */
101939   void *pAux,                     /* Context pointer for xCreate/xConnect */
101940   void (*xDestroy)(void *)        /* Module destructor function */
101941 ){
101942   return createModule(db, zName, pModule, pAux, xDestroy);
101943 }
101944 
101945 /*
101946 ** Lock the virtual table so that it cannot be disconnected.
101947 ** Locks nest.  Every lock should have a corresponding unlock.
101948 ** If an unlock is omitted, resources leaks will occur.
101949 **
101950 ** If a disconnect is attempted while a virtual table is locked,
101951 ** the disconnect is deferred until all locks have been removed.
101952 */
101953 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
101954   pVTab->nRef++;
101955 }
101956 
101957 
101958 /*
101959 ** pTab is a pointer to a Table structure representing a virtual-table.
101960 ** Return a pointer to the VTable object used by connection db to access
101961 ** this virtual-table, if one has been created, or NULL otherwise.
101962 */
101963 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
101964   VTable *pVtab;
101965   assert( IsVirtual(pTab) );
101966   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101967   return pVtab;
101968 }
101969 
101970 /*
101971 ** Decrement the ref-count on a virtual table object. When the ref-count
101972 ** reaches zero, call the xDisconnect() method to delete the object.
101973 */
101974 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
101975   sqlite3 *db = pVTab->db;
101976 
101977   assert( db );
101978   assert( pVTab->nRef>0 );
101979   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
101980 
101981   pVTab->nRef--;
101982   if( pVTab->nRef==0 ){
101983     sqlite3_vtab *p = pVTab->pVtab;
101984     if( p ){
101985       p->pModule->xDisconnect(p);
101986     }
101987     sqlite3DbFree(db, pVTab);
101988   }
101989 }
101990 
101991 /*
101992 ** Table p is a virtual table. This function moves all elements in the
101993 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
101994 ** database connections to be disconnected at the next opportunity.
101995 ** Except, if argument db is not NULL, then the entry associated with
101996 ** connection db is left in the p->pVTable list.
101997 */
101998 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
101999   VTable *pRet = 0;
102000   VTable *pVTable = p->pVTable;
102001   p->pVTable = 0;
102002 
102003   /* Assert that the mutex (if any) associated with the BtShared database
102004   ** that contains table p is held by the caller. See header comments
102005   ** above function sqlite3VtabUnlockList() for an explanation of why
102006   ** this makes it safe to access the sqlite3.pDisconnect list of any
102007   ** database connection that may have an entry in the p->pVTable list.
102008   */
102009   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
102010 
102011   while( pVTable ){
102012     sqlite3 *db2 = pVTable->db;
102013     VTable *pNext = pVTable->pNext;
102014     assert( db2 );
102015     if( db2==db ){
102016       pRet = pVTable;
102017       p->pVTable = pRet;
102018       pRet->pNext = 0;
102019     }else{
102020       pVTable->pNext = db2->pDisconnect;
102021       db2->pDisconnect = pVTable;
102022     }
102023     pVTable = pNext;
102024   }
102025 
102026   assert( !db || pRet );
102027   return pRet;
102028 }
102029 
102030 /*
102031 ** Table *p is a virtual table. This function removes the VTable object
102032 ** for table *p associated with database connection db from the linked
102033 ** list in p->pVTab. It also decrements the VTable ref count. This is
102034 ** used when closing database connection db to free all of its VTable
102035 ** objects without disturbing the rest of the Schema object (which may
102036 ** be being used by other shared-cache connections).
102037 */
102038 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
102039   VTable **ppVTab;
102040 
102041   assert( IsVirtual(p) );
102042   assert( sqlite3BtreeHoldsAllMutexes(db) );
102043   assert( sqlite3_mutex_held(db->mutex) );
102044 
102045   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
102046     if( (*ppVTab)->db==db  ){
102047       VTable *pVTab = *ppVTab;
102048       *ppVTab = pVTab->pNext;
102049       sqlite3VtabUnlock(pVTab);
102050       break;
102051     }
102052   }
102053 }
102054 
102055 
102056 /*
102057 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
102058 **
102059 ** This function may only be called when the mutexes associated with all
102060 ** shared b-tree databases opened using connection db are held by the
102061 ** caller. This is done to protect the sqlite3.pDisconnect list. The
102062 ** sqlite3.pDisconnect list is accessed only as follows:
102063 **
102064 **   1) By this function. In this case, all BtShared mutexes and the mutex
102065 **      associated with the database handle itself must be held.
102066 **
102067 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
102068 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
102069 **      associated with the database the virtual table is stored in is held
102070 **      or, if the virtual table is stored in a non-sharable database, then
102071 **      the database handle mutex is held.
102072 **
102073 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
102074 ** by multiple threads. It is thread-safe.
102075 */
102076 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
102077   VTable *p = db->pDisconnect;
102078   db->pDisconnect = 0;
102079 
102080   assert( sqlite3BtreeHoldsAllMutexes(db) );
102081   assert( sqlite3_mutex_held(db->mutex) );
102082 
102083   if( p ){
102084     sqlite3ExpirePreparedStatements(db);
102085     do {
102086       VTable *pNext = p->pNext;
102087       sqlite3VtabUnlock(p);
102088       p = pNext;
102089     }while( p );
102090   }
102091 }
102092 
102093 /*
102094 ** Clear any and all virtual-table information from the Table record.
102095 ** This routine is called, for example, just before deleting the Table
102096 ** record.
102097 **
102098 ** Since it is a virtual-table, the Table structure contains a pointer
102099 ** to the head of a linked list of VTable structures. Each VTable
102100 ** structure is associated with a single sqlite3* user of the schema.
102101 ** The reference count of the VTable structure associated with database
102102 ** connection db is decremented immediately (which may lead to the
102103 ** structure being xDisconnected and free). Any other VTable structures
102104 ** in the list are moved to the sqlite3.pDisconnect list of the associated
102105 ** database connection.
102106 */
102107 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
102108   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
102109   if( p->azModuleArg ){
102110     int i;
102111     for(i=0; i<p->nModuleArg; i++){
102112       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
102113     }
102114     sqlite3DbFree(db, p->azModuleArg);
102115   }
102116 }
102117 
102118 /*
102119 ** Add a new module argument to pTable->azModuleArg[].
102120 ** The string is not copied - the pointer is stored.  The
102121 ** string will be freed automatically when the table is
102122 ** deleted.
102123 */
102124 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
102125   int i = pTable->nModuleArg++;
102126   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
102127   char **azModuleArg;
102128   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
102129   if( azModuleArg==0 ){
102130     int j;
102131     for(j=0; j<i; j++){
102132       sqlite3DbFree(db, pTable->azModuleArg[j]);
102133     }
102134     sqlite3DbFree(db, zArg);
102135     sqlite3DbFree(db, pTable->azModuleArg);
102136     pTable->nModuleArg = 0;
102137   }else{
102138     azModuleArg[i] = zArg;
102139     azModuleArg[i+1] = 0;
102140   }
102141   pTable->azModuleArg = azModuleArg;
102142 }
102143 
102144 /*
102145 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
102146 ** statement.  The module name has been parsed, but the optional list
102147 ** of parameters that follow the module name are still pending.
102148 */
102149 SQLITE_PRIVATE void sqlite3VtabBeginParse(
102150   Parse *pParse,        /* Parsing context */
102151   Token *pName1,        /* Name of new table, or database name */
102152   Token *pName2,        /* Name of new table or NULL */
102153   Token *pModuleName,   /* Name of the module for the virtual table */
102154   int ifNotExists       /* No error if the table already exists */
102155 ){
102156   int iDb;              /* The database the table is being created in */
102157   Table *pTable;        /* The new virtual table */
102158   sqlite3 *db;          /* Database connection */
102159 
102160   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
102161   pTable = pParse->pNewTable;
102162   if( pTable==0 ) return;
102163   assert( 0==pTable->pIndex );
102164 
102165   db = pParse->db;
102166   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
102167   assert( iDb>=0 );
102168 
102169   pTable->tabFlags |= TF_Virtual;
102170   pTable->nModuleArg = 0;
102171   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
102172   addModuleArgument(db, pTable, 0);
102173   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
102174   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
102175 
102176 #ifndef SQLITE_OMIT_AUTHORIZATION
102177   /* Creating a virtual table invokes the authorization callback twice.
102178   ** The first invocation, to obtain permission to INSERT a row into the
102179   ** sqlite_master table, has already been made by sqlite3StartTable().
102180   ** The second call, to obtain permission to create the table, is made now.
102181   */
102182   if( pTable->azModuleArg ){
102183     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
102184             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
102185   }
102186 #endif
102187 }
102188 
102189 /*
102190 ** This routine takes the module argument that has been accumulating
102191 ** in pParse->zArg[] and appends it to the list of arguments on the
102192 ** virtual table currently under construction in pParse->pTable.
102193 */
102194 static void addArgumentToVtab(Parse *pParse){
102195   if( pParse->sArg.z && pParse->pNewTable ){
102196     const char *z = (const char*)pParse->sArg.z;
102197     int n = pParse->sArg.n;
102198     sqlite3 *db = pParse->db;
102199     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
102200   }
102201 }
102202 
102203 /*
102204 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
102205 ** has been completely parsed.
102206 */
102207 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
102208   Table *pTab = pParse->pNewTable;  /* The table being constructed */
102209   sqlite3 *db = pParse->db;         /* The database connection */
102210 
102211   if( pTab==0 ) return;
102212   addArgumentToVtab(pParse);
102213   pParse->sArg.z = 0;
102214   if( pTab->nModuleArg<1 ) return;
102215 
102216   /* If the CREATE VIRTUAL TABLE statement is being entered for the
102217   ** first time (in other words if the virtual table is actually being
102218   ** created now instead of just being read out of sqlite_master) then
102219   ** do additional initialization work and store the statement text
102220   ** in the sqlite_master table.
102221   */
102222   if( !db->init.busy ){
102223     char *zStmt;
102224     char *zWhere;
102225     int iDb;
102226     Vdbe *v;
102227 
102228     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
102229     if( pEnd ){
102230       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
102231     }
102232     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
102233 
102234     /* A slot for the record has already been allocated in the
102235     ** SQLITE_MASTER table.  We just need to update that slot with all
102236     ** the information we've collected.
102237     **
102238     ** The VM register number pParse->regRowid holds the rowid of an
102239     ** entry in the sqlite_master table tht was created for this vtab
102240     ** by sqlite3StartTable().
102241     */
102242     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102243     sqlite3NestedParse(pParse,
102244       "UPDATE %Q.%s "
102245          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
102246        "WHERE rowid=#%d",
102247       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
102248       pTab->zName,
102249       pTab->zName,
102250       zStmt,
102251       pParse->regRowid
102252     );
102253     sqlite3DbFree(db, zStmt);
102254     v = sqlite3GetVdbe(pParse);
102255     sqlite3ChangeCookie(pParse, iDb);
102256 
102257     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
102258     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
102259     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
102260     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
102261                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
102262   }
102263 
102264   /* If we are rereading the sqlite_master table create the in-memory
102265   ** record of the table. The xConnect() method is not called until
102266   ** the first time the virtual table is used in an SQL statement. This
102267   ** allows a schema that contains virtual tables to be loaded before
102268   ** the required virtual table implementations are registered.  */
102269   else {
102270     Table *pOld;
102271     Schema *pSchema = pTab->pSchema;
102272     const char *zName = pTab->zName;
102273     int nName = sqlite3Strlen30(zName);
102274     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
102275     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
102276     if( pOld ){
102277       db->mallocFailed = 1;
102278       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
102279       return;
102280     }
102281     pParse->pNewTable = 0;
102282   }
102283 }
102284 
102285 /*
102286 ** The parser calls this routine when it sees the first token
102287 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
102288 */
102289 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
102290   addArgumentToVtab(pParse);
102291   pParse->sArg.z = 0;
102292   pParse->sArg.n = 0;
102293 }
102294 
102295 /*
102296 ** The parser calls this routine for each token after the first token
102297 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
102298 */
102299 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
102300   Token *pArg = &pParse->sArg;
102301   if( pArg->z==0 ){
102302     pArg->z = p->z;
102303     pArg->n = p->n;
102304   }else{
102305     assert(pArg->z < p->z);
102306     pArg->n = (int)(&p->z[p->n] - pArg->z);
102307   }
102308 }
102309 
102310 /*
102311 ** Invoke a virtual table constructor (either xCreate or xConnect). The
102312 ** pointer to the function to invoke is passed as the fourth parameter
102313 ** to this procedure.
102314 */
102315 static int vtabCallConstructor(
102316   sqlite3 *db,
102317   Table *pTab,
102318   Module *pMod,
102319   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
102320   char **pzErr
102321 ){
102322   VtabCtx sCtx, *pPriorCtx;
102323   VTable *pVTable;
102324   int rc;
102325   const char *const*azArg = (const char *const*)pTab->azModuleArg;
102326   int nArg = pTab->nModuleArg;
102327   char *zErr = 0;
102328   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
102329   int iDb;
102330 
102331   if( !zModuleName ){
102332     return SQLITE_NOMEM;
102333   }
102334 
102335   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
102336   if( !pVTable ){
102337     sqlite3DbFree(db, zModuleName);
102338     return SQLITE_NOMEM;
102339   }
102340   pVTable->db = db;
102341   pVTable->pMod = pMod;
102342 
102343   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102344   pTab->azModuleArg[1] = db->aDb[iDb].zName;
102345 
102346   /* Invoke the virtual table constructor */
102347   assert( &db->pVtabCtx );
102348   assert( xConstruct );
102349   sCtx.pTab = pTab;
102350   sCtx.pVTable = pVTable;
102351   pPriorCtx = db->pVtabCtx;
102352   db->pVtabCtx = &sCtx;
102353   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
102354   db->pVtabCtx = pPriorCtx;
102355   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
102356 
102357   if( SQLITE_OK!=rc ){
102358     if( zErr==0 ){
102359       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
102360     }else {
102361       *pzErr = sqlite3MPrintf(db, "%s", zErr);
102362       sqlite3_free(zErr);
102363     }
102364     sqlite3DbFree(db, pVTable);
102365   }else if( ALWAYS(pVTable->pVtab) ){
102366     /* Justification of ALWAYS():  A correct vtab constructor must allocate
102367     ** the sqlite3_vtab object if successful.  */
102368     pVTable->pVtab->pModule = pMod->pModule;
102369     pVTable->nRef = 1;
102370     if( sCtx.pTab ){
102371       const char *zFormat = "vtable constructor did not declare schema: %s";
102372       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
102373       sqlite3VtabUnlock(pVTable);
102374       rc = SQLITE_ERROR;
102375     }else{
102376       int iCol;
102377       /* If everything went according to plan, link the new VTable structure
102378       ** into the linked list headed by pTab->pVTable. Then loop through the
102379       ** columns of the table to see if any of them contain the token "hidden".
102380       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
102381       ** the type string.  */
102382       pVTable->pNext = pTab->pVTable;
102383       pTab->pVTable = pVTable;
102384 
102385       for(iCol=0; iCol<pTab->nCol; iCol++){
102386         char *zType = pTab->aCol[iCol].zType;
102387         int nType;
102388         int i = 0;
102389         if( !zType ) continue;
102390         nType = sqlite3Strlen30(zType);
102391         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
102392           for(i=0; i<nType; i++){
102393             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
102394              && (zType[i+7]=='\0' || zType[i+7]==' ')
102395             ){
102396               i++;
102397               break;
102398             }
102399           }
102400         }
102401         if( i<nType ){
102402           int j;
102403           int nDel = 6 + (zType[i+6] ? 1 : 0);
102404           for(j=i; (j+nDel)<=nType; j++){
102405             zType[j] = zType[j+nDel];
102406           }
102407           if( zType[i]=='\0' && i>0 ){
102408             assert(zType[i-1]==' ');
102409             zType[i-1] = '\0';
102410           }
102411           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
102412         }
102413       }
102414     }
102415   }
102416 
102417   sqlite3DbFree(db, zModuleName);
102418   return rc;
102419 }
102420 
102421 /*
102422 ** This function is invoked by the parser to call the xConnect() method
102423 ** of the virtual table pTab. If an error occurs, an error code is returned
102424 ** and an error left in pParse.
102425 **
102426 ** This call is a no-op if table pTab is not a virtual table.
102427 */
102428 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
102429   sqlite3 *db = pParse->db;
102430   const char *zMod;
102431   Module *pMod;
102432   int rc;
102433 
102434   assert( pTab );
102435   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
102436     return SQLITE_OK;
102437   }
102438 
102439   /* Locate the required virtual table module */
102440   zMod = pTab->azModuleArg[0];
102441   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102442 
102443   if( !pMod ){
102444     const char *zModule = pTab->azModuleArg[0];
102445     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
102446     rc = SQLITE_ERROR;
102447   }else{
102448     char *zErr = 0;
102449     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
102450     if( rc!=SQLITE_OK ){
102451       sqlite3ErrorMsg(pParse, "%s", zErr);
102452     }
102453     sqlite3DbFree(db, zErr);
102454   }
102455 
102456   return rc;
102457 }
102458 /*
102459 ** Grow the db->aVTrans[] array so that there is room for at least one
102460 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
102461 */
102462 static int growVTrans(sqlite3 *db){
102463   const int ARRAY_INCR = 5;
102464 
102465   /* Grow the sqlite3.aVTrans array if required */
102466   if( (db->nVTrans%ARRAY_INCR)==0 ){
102467     VTable **aVTrans;
102468     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
102469     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
102470     if( !aVTrans ){
102471       return SQLITE_NOMEM;
102472     }
102473     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
102474     db->aVTrans = aVTrans;
102475   }
102476 
102477   return SQLITE_OK;
102478 }
102479 
102480 /*
102481 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
102482 ** have already been reserved using growVTrans().
102483 */
102484 static void addToVTrans(sqlite3 *db, VTable *pVTab){
102485   /* Add pVtab to the end of sqlite3.aVTrans */
102486   db->aVTrans[db->nVTrans++] = pVTab;
102487   sqlite3VtabLock(pVTab);
102488 }
102489 
102490 /*
102491 ** This function is invoked by the vdbe to call the xCreate method
102492 ** of the virtual table named zTab in database iDb.
102493 **
102494 ** If an error occurs, *pzErr is set to point an an English language
102495 ** description of the error and an SQLITE_XXX error code is returned.
102496 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
102497 */
102498 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
102499   int rc = SQLITE_OK;
102500   Table *pTab;
102501   Module *pMod;
102502   const char *zMod;
102503 
102504   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102505   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
102506 
102507   /* Locate the required virtual table module */
102508   zMod = pTab->azModuleArg[0];
102509   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102510 
102511   /* If the module has been registered and includes a Create method,
102512   ** invoke it now. If the module has not been registered, return an
102513   ** error. Otherwise, do nothing.
102514   */
102515   if( !pMod ){
102516     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
102517     rc = SQLITE_ERROR;
102518   }else{
102519     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
102520   }
102521 
102522   /* Justification of ALWAYS():  The xConstructor method is required to
102523   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
102524   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
102525     rc = growVTrans(db);
102526     if( rc==SQLITE_OK ){
102527       addToVTrans(db, sqlite3GetVTable(db, pTab));
102528     }
102529   }
102530 
102531   return rc;
102532 }
102533 
102534 /*
102535 ** This function is used to set the schema of a virtual table.  It is only
102536 ** valid to call this function from within the xCreate() or xConnect() of a
102537 ** virtual table module.
102538 */
102539 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
102540   Parse *pParse;
102541 
102542   int rc = SQLITE_OK;
102543   Table *pTab;
102544   char *zErr = 0;
102545 
102546   sqlite3_mutex_enter(db->mutex);
102547   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
102548     sqlite3Error(db, SQLITE_MISUSE, 0);
102549     sqlite3_mutex_leave(db->mutex);
102550     return SQLITE_MISUSE_BKPT;
102551   }
102552   assert( (pTab->tabFlags & TF_Virtual)!=0 );
102553 
102554   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
102555   if( pParse==0 ){
102556     rc = SQLITE_NOMEM;
102557   }else{
102558     pParse->declareVtab = 1;
102559     pParse->db = db;
102560     pParse->nQueryLoop = 1;
102561 
102562     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
102563      && pParse->pNewTable
102564      && !db->mallocFailed
102565      && !pParse->pNewTable->pSelect
102566      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
102567     ){
102568       if( !pTab->aCol ){
102569         pTab->aCol = pParse->pNewTable->aCol;
102570         pTab->nCol = pParse->pNewTable->nCol;
102571         pParse->pNewTable->nCol = 0;
102572         pParse->pNewTable->aCol = 0;
102573       }
102574       db->pVtabCtx->pTab = 0;
102575     }else{
102576       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
102577       sqlite3DbFree(db, zErr);
102578       rc = SQLITE_ERROR;
102579     }
102580     pParse->declareVtab = 0;
102581 
102582     if( pParse->pVdbe ){
102583       sqlite3VdbeFinalize(pParse->pVdbe);
102584     }
102585     sqlite3DeleteTable(db, pParse->pNewTable);
102586     sqlite3StackFree(db, pParse);
102587   }
102588 
102589   assert( (rc&0xff)==rc );
102590   rc = sqlite3ApiExit(db, rc);
102591   sqlite3_mutex_leave(db->mutex);
102592   return rc;
102593 }
102594 
102595 /*
102596 ** This function is invoked by the vdbe to call the xDestroy method
102597 ** of the virtual table named zTab in database iDb. This occurs
102598 ** when a DROP TABLE is mentioned.
102599 **
102600 ** This call is a no-op if zTab is not a virtual table.
102601 */
102602 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
102603   int rc = SQLITE_OK;
102604   Table *pTab;
102605 
102606   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102607   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
102608     VTable *p = vtabDisconnectAll(db, pTab);
102609 
102610     assert( rc==SQLITE_OK );
102611     rc = p->pMod->pModule->xDestroy(p->pVtab);
102612 
102613     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
102614     if( rc==SQLITE_OK ){
102615       assert( pTab->pVTable==p && p->pNext==0 );
102616       p->pVtab = 0;
102617       pTab->pVTable = 0;
102618       sqlite3VtabUnlock(p);
102619     }
102620   }
102621 
102622   return rc;
102623 }
102624 
102625 /*
102626 ** This function invokes either the xRollback or xCommit method
102627 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
102628 ** called is identified by the second argument, "offset", which is
102629 ** the offset of the method to call in the sqlite3_module structure.
102630 **
102631 ** The array is cleared after invoking the callbacks.
102632 */
102633 static void callFinaliser(sqlite3 *db, int offset){
102634   int i;
102635   if( db->aVTrans ){
102636     for(i=0; i<db->nVTrans; i++){
102637       VTable *pVTab = db->aVTrans[i];
102638       sqlite3_vtab *p = pVTab->pVtab;
102639       if( p ){
102640         int (*x)(sqlite3_vtab *);
102641         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
102642         if( x ) x(p);
102643       }
102644       pVTab->iSavepoint = 0;
102645       sqlite3VtabUnlock(pVTab);
102646     }
102647     sqlite3DbFree(db, db->aVTrans);
102648     db->nVTrans = 0;
102649     db->aVTrans = 0;
102650   }
102651 }
102652 
102653 /*
102654 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
102655 ** array. Return the error code for the first error that occurs, or
102656 ** SQLITE_OK if all xSync operations are successful.
102657 **
102658 ** Set *pzErrmsg to point to a buffer that should be released using
102659 ** sqlite3DbFree() containing an error message, if one is available.
102660 */
102661 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
102662   int i;
102663   int rc = SQLITE_OK;
102664   VTable **aVTrans = db->aVTrans;
102665 
102666   db->aVTrans = 0;
102667   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102668     int (*x)(sqlite3_vtab *);
102669     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
102670     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
102671       rc = x(pVtab);
102672       sqlite3DbFree(db, *pzErrmsg);
102673       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
102674       sqlite3_free(pVtab->zErrMsg);
102675     }
102676   }
102677   db->aVTrans = aVTrans;
102678   return rc;
102679 }
102680 
102681 /*
102682 ** Invoke the xRollback method of all virtual tables in the
102683 ** sqlite3.aVTrans array. Then clear the array itself.
102684 */
102685 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
102686   callFinaliser(db, offsetof(sqlite3_module,xRollback));
102687   return SQLITE_OK;
102688 }
102689 
102690 /*
102691 ** Invoke the xCommit method of all virtual tables in the
102692 ** sqlite3.aVTrans array. Then clear the array itself.
102693 */
102694 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
102695   callFinaliser(db, offsetof(sqlite3_module,xCommit));
102696   return SQLITE_OK;
102697 }
102698 
102699 /*
102700 ** If the virtual table pVtab supports the transaction interface
102701 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
102702 ** not currently open, invoke the xBegin method now.
102703 **
102704 ** If the xBegin call is successful, place the sqlite3_vtab pointer
102705 ** in the sqlite3.aVTrans array.
102706 */
102707 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
102708   int rc = SQLITE_OK;
102709   const sqlite3_module *pModule;
102710 
102711   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
102712   ** than zero, then this function is being called from within a
102713   ** virtual module xSync() callback. It is illegal to write to
102714   ** virtual module tables in this case, so return SQLITE_LOCKED.
102715   */
102716   if( sqlite3VtabInSync(db) ){
102717     return SQLITE_LOCKED;
102718   }
102719   if( !pVTab ){
102720     return SQLITE_OK;
102721   }
102722   pModule = pVTab->pVtab->pModule;
102723 
102724   if( pModule->xBegin ){
102725     int i;
102726 
102727     /* If pVtab is already in the aVTrans array, return early */
102728     for(i=0; i<db->nVTrans; i++){
102729       if( db->aVTrans[i]==pVTab ){
102730         return SQLITE_OK;
102731       }
102732     }
102733 
102734     /* Invoke the xBegin method. If successful, add the vtab to the
102735     ** sqlite3.aVTrans[] array. */
102736     rc = growVTrans(db);
102737     if( rc==SQLITE_OK ){
102738       rc = pModule->xBegin(pVTab->pVtab);
102739       if( rc==SQLITE_OK ){
102740         addToVTrans(db, pVTab);
102741       }
102742     }
102743   }
102744   return rc;
102745 }
102746 
102747 /*
102748 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
102749 ** virtual tables that currently have an open transaction. Pass iSavepoint
102750 ** as the second argument to the virtual table method invoked.
102751 **
102752 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
102753 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
102754 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
102755 ** an open transaction is invoked.
102756 **
102757 ** If any virtual table method returns an error code other than SQLITE_OK,
102758 ** processing is abandoned and the error returned to the caller of this
102759 ** function immediately. If all calls to virtual table methods are successful,
102760 ** SQLITE_OK is returned.
102761 */
102762 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
102763   int rc = SQLITE_OK;
102764 
102765   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
102766   assert( iSavepoint>=0 );
102767   if( db->aVTrans ){
102768     int i;
102769     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102770       VTable *pVTab = db->aVTrans[i];
102771       const sqlite3_module *pMod = pVTab->pMod->pModule;
102772       if( pVTab->pVtab && pMod->iVersion>=2 ){
102773         int (*xMethod)(sqlite3_vtab *, int);
102774         switch( op ){
102775           case SAVEPOINT_BEGIN:
102776             xMethod = pMod->xSavepoint;
102777             pVTab->iSavepoint = iSavepoint+1;
102778             break;
102779           case SAVEPOINT_ROLLBACK:
102780             xMethod = pMod->xRollbackTo;
102781             break;
102782           default:
102783             xMethod = pMod->xRelease;
102784             break;
102785         }
102786         if( xMethod && pVTab->iSavepoint>iSavepoint ){
102787           rc = xMethod(pVTab->pVtab, iSavepoint);
102788         }
102789       }
102790     }
102791   }
102792   return rc;
102793 }
102794 
102795 /*
102796 ** The first parameter (pDef) is a function implementation.  The
102797 ** second parameter (pExpr) is the first argument to this function.
102798 ** If pExpr is a column in a virtual table, then let the virtual
102799 ** table implementation have an opportunity to overload the function.
102800 **
102801 ** This routine is used to allow virtual table implementations to
102802 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
102803 **
102804 ** Return either the pDef argument (indicating no change) or a
102805 ** new FuncDef structure that is marked as ephemeral using the
102806 ** SQLITE_FUNC_EPHEM flag.
102807 */
102808 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
102809   sqlite3 *db,    /* Database connection for reporting malloc problems */
102810   FuncDef *pDef,  /* Function to possibly overload */
102811   int nArg,       /* Number of arguments to the function */
102812   Expr *pExpr     /* First argument to the function */
102813 ){
102814   Table *pTab;
102815   sqlite3_vtab *pVtab;
102816   sqlite3_module *pMod;
102817   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
102818   void *pArg = 0;
102819   FuncDef *pNew;
102820   int rc = 0;
102821   char *zLowerName;
102822   unsigned char *z;
102823 
102824 
102825   /* Check to see the left operand is a column in a virtual table */
102826   if( NEVER(pExpr==0) ) return pDef;
102827   if( pExpr->op!=TK_COLUMN ) return pDef;
102828   pTab = pExpr->pTab;
102829   if( NEVER(pTab==0) ) return pDef;
102830   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102831   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
102832   assert( pVtab!=0 );
102833   assert( pVtab->pModule!=0 );
102834   pMod = (sqlite3_module *)pVtab->pModule;
102835   if( pMod->xFindFunction==0 ) return pDef;
102836 
102837   /* Call the xFindFunction method on the virtual table implementation
102838   ** to see if the implementation wants to overload this function
102839   */
102840   zLowerName = sqlite3DbStrDup(db, pDef->zName);
102841   if( zLowerName ){
102842     for(z=(unsigned char*)zLowerName; *z; z++){
102843       *z = sqlite3UpperToLower[*z];
102844     }
102845     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102846     sqlite3DbFree(db, zLowerName);
102847   }
102848   if( rc==0 ){
102849     return pDef;
102850   }
102851 
102852   /* Create a new ephemeral function definition for the overloaded
102853   ** function */
102854   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
102855                              + sqlite3Strlen30(pDef->zName) + 1);
102856   if( pNew==0 ){
102857     return pDef;
102858   }
102859   *pNew = *pDef;
102860   pNew->zName = (char *)&pNew[1];
102861   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
102862   pNew->xFunc = xFunc;
102863   pNew->pUserData = pArg;
102864   pNew->flags |= SQLITE_FUNC_EPHEM;
102865   return pNew;
102866 }
102867 
102868 /*
102869 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102870 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
102871 ** array if it is missing.  If pTab is already in the array, this routine
102872 ** is a no-op.
102873 */
102874 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
102875   Parse *pToplevel = sqlite3ParseToplevel(pParse);
102876   int i, n;
102877   Table **apVtabLock;
102878 
102879   assert( IsVirtual(pTab) );
102880   for(i=0; i<pToplevel->nVtabLock; i++){
102881     if( pTab==pToplevel->apVtabLock[i] ) return;
102882   }
102883   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102884   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
102885   if( apVtabLock ){
102886     pToplevel->apVtabLock = apVtabLock;
102887     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102888   }else{
102889     pToplevel->db->mallocFailed = 1;
102890   }
102891 }
102892 
102893 /*
102894 ** Return the ON CONFLICT resolution mode in effect for the virtual
102895 ** table update operation currently in progress.
102896 **
102897 ** The results of this routine are undefined unless it is called from
102898 ** within an xUpdate method.
102899 */
102900 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
102901   static const unsigned char aMap[] = {
102902     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
102903   };
102904   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102905   assert( OE_Ignore==4 && OE_Replace==5 );
102906   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102907   return (int)aMap[db->vtabOnConflict-1];
102908 }
102909 
102910 /*
102911 ** Call from within the xCreate() or xConnect() methods to provide
102912 ** the SQLite core with additional information about the behavior
102913 ** of the virtual table being implemented.
102914 */
102915 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
102916   va_list ap;
102917   int rc = SQLITE_OK;
102918 
102919   sqlite3_mutex_enter(db->mutex);
102920 
102921   va_start(ap, op);
102922   switch( op ){
102923     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
102924       VtabCtx *p = db->pVtabCtx;
102925       if( !p ){
102926         rc = SQLITE_MISUSE_BKPT;
102927       }else{
102928         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102929         p->pVTable->bConstraint = (u8)va_arg(ap, int);
102930       }
102931       break;
102932     }
102933     default:
102934       rc = SQLITE_MISUSE_BKPT;
102935       break;
102936   }
102937   va_end(ap);
102938 
102939   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
102940   sqlite3_mutex_leave(db->mutex);
102941   return rc;
102942 }
102943 
102944 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102945 
102946 /************** End of vtab.c ************************************************/
102947 /************** Begin file where.c *******************************************/
102948 /*
102949 ** 2001 September 15
102950 **
102951 ** The author disclaims copyright to this source code.  In place of
102952 ** a legal notice, here is a blessing:
102953 **
102954 **    May you do good and not evil.
102955 **    May you find forgiveness for yourself and forgive others.
102956 **    May you share freely, never taking more than you give.
102957 **
102958 *************************************************************************
102959 ** This module contains C code that generates VDBE code used to process
102960 ** the WHERE clause of SQL statements.  This module is responsible for
102961 ** generating the code that loops through a table looking for applicable
102962 ** rows.  Indices are selected and used to speed the search when doing
102963 ** so is applicable.  Because this module is responsible for selecting
102964 ** indices, you might also think of this module as the "query optimizer".
102965 */
102966 
102967 
102968 /*
102969 ** Trace output macros
102970 */
102971 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
102972 /***/ int sqlite3WhereTrace = 0;
102973 #endif
102974 #if defined(SQLITE_DEBUG) \
102975     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
102976 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
102977 #else
102978 # define WHERETRACE(X)
102979 #endif
102980 
102981 /* Forward reference
102982 */
102983 typedef struct WhereClause WhereClause;
102984 typedef struct WhereMaskSet WhereMaskSet;
102985 typedef struct WhereOrInfo WhereOrInfo;
102986 typedef struct WhereAndInfo WhereAndInfo;
102987 typedef struct WhereCost WhereCost;
102988 
102989 /*
102990 ** The query generator uses an array of instances of this structure to
102991 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102992 ** clause subexpression is separated from the others by AND operators,
102993 ** usually, or sometimes subexpressions separated by OR.
102994 **
102995 ** All WhereTerms are collected into a single WhereClause structure.
102996 ** The following identity holds:
102997 **
102998 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
102999 **
103000 ** When a term is of the form:
103001 **
103002 **              X <op> <expr>
103003 **
103004 ** where X is a column name and <op> is one of certain operators,
103005 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
103006 ** cursor number and column number for X.  WhereTerm.eOperator records
103007 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
103008 ** use of a bitmask encoding for the operator allows us to search
103009 ** quickly for terms that match any of several different operators.
103010 **
103011 ** A WhereTerm might also be two or more subterms connected by OR:
103012 **
103013 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
103014 **
103015 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
103016 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
103017 ** is collected about the
103018 **
103019 ** If a term in the WHERE clause does not match either of the two previous
103020 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
103021 ** to the original subexpression content and wtFlags is set up appropriately
103022 ** but no other fields in the WhereTerm object are meaningful.
103023 **
103024 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
103025 ** but they do so indirectly.  A single WhereMaskSet structure translates
103026 ** cursor number into bits and the translated bit is stored in the prereq
103027 ** fields.  The translation is used in order to maximize the number of
103028 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
103029 ** spread out over the non-negative integers.  For example, the cursor
103030 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
103031 ** translates these sparse cursor numbers into consecutive integers
103032 ** beginning with 0 in order to make the best possible use of the available
103033 ** bits in the Bitmask.  So, in the example above, the cursor numbers
103034 ** would be mapped into integers 0 through 7.
103035 **
103036 ** The number of terms in a join is limited by the number of bits
103037 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
103038 ** is only able to process joins with 64 or fewer tables.
103039 */
103040 typedef struct WhereTerm WhereTerm;
103041 struct WhereTerm {
103042   Expr *pExpr;            /* Pointer to the subexpression that is this term */
103043   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
103044   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
103045   union {
103046     int leftColumn;         /* Column number of X in "X <op> <expr>" */
103047     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
103048     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
103049   } u;
103050   u16 eOperator;          /* A WO_xx value describing <op> */
103051   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
103052   u8 nChild;              /* Number of children that must disable us */
103053   WhereClause *pWC;       /* The clause this term is part of */
103054   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
103055   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
103056 };
103057 
103058 /*
103059 ** Allowed values of WhereTerm.wtFlags
103060 */
103061 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
103062 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
103063 #define TERM_CODED      0x04   /* This term is already coded */
103064 #define TERM_COPIED     0x08   /* Has a child */
103065 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
103066 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
103067 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
103068 #ifdef SQLITE_ENABLE_STAT3
103069 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
103070 #else
103071 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
103072 #endif
103073 
103074 /*
103075 ** An instance of the following structure holds all information about a
103076 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
103077 **
103078 ** Explanation of pOuter:  For a WHERE clause of the form
103079 **
103080 **           a AND ((b AND c) OR (d AND e)) AND f
103081 **
103082 ** There are separate WhereClause objects for the whole clause and for
103083 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
103084 ** subclauses points to the WhereClause object for the whole clause.
103085 */
103086 struct WhereClause {
103087   Parse *pParse;           /* The parser context */
103088   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
103089   WhereClause *pOuter;     /* Outer conjunction */
103090   u8 op;                   /* Split operator.  TK_AND or TK_OR */
103091   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
103092   int nTerm;               /* Number of terms */
103093   int nSlot;               /* Number of entries in a[] */
103094   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
103095 #if defined(SQLITE_SMALL_STACK)
103096   WhereTerm aStatic[1];    /* Initial static space for a[] */
103097 #else
103098   WhereTerm aStatic[8];    /* Initial static space for a[] */
103099 #endif
103100 };
103101 
103102 /*
103103 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
103104 ** a dynamically allocated instance of the following structure.
103105 */
103106 struct WhereOrInfo {
103107   WhereClause wc;          /* Decomposition into subterms */
103108   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
103109 };
103110 
103111 /*
103112 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
103113 ** a dynamically allocated instance of the following structure.
103114 */
103115 struct WhereAndInfo {
103116   WhereClause wc;          /* The subexpression broken out */
103117 };
103118 
103119 /*
103120 ** An instance of the following structure keeps track of a mapping
103121 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
103122 **
103123 ** The VDBE cursor numbers are small integers contained in
103124 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
103125 ** clause, the cursor numbers might not begin with 0 and they might
103126 ** contain gaps in the numbering sequence.  But we want to make maximum
103127 ** use of the bits in our bitmasks.  This structure provides a mapping
103128 ** from the sparse cursor numbers into consecutive integers beginning
103129 ** with 0.
103130 **
103131 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
103132 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
103133 **
103134 ** For example, if the WHERE clause expression used these VDBE
103135 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
103136 ** would map those cursor numbers into bits 0 through 5.
103137 **
103138 ** Note that the mapping is not necessarily ordered.  In the example
103139 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
103140 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
103141 ** does not really matter.  What is important is that sparse cursor
103142 ** numbers all get mapped into bit numbers that begin with 0 and contain
103143 ** no gaps.
103144 */
103145 struct WhereMaskSet {
103146   int n;                        /* Number of assigned cursor values */
103147   int ix[BMS];                  /* Cursor assigned to each bit */
103148 };
103149 
103150 /*
103151 ** A WhereCost object records a lookup strategy and the estimated
103152 ** cost of pursuing that strategy.
103153 */
103154 struct WhereCost {
103155   WherePlan plan;    /* The lookup strategy */
103156   double rCost;      /* Overall cost of pursuing this search strategy */
103157   Bitmask used;      /* Bitmask of cursors used by this plan */
103158 };
103159 
103160 /*
103161 ** Bitmasks for the operators that indices are able to exploit.  An
103162 ** OR-ed combination of these values can be used when searching for
103163 ** terms in the where clause.
103164 */
103165 #define WO_IN     0x001
103166 #define WO_EQ     0x002
103167 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
103168 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
103169 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
103170 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
103171 #define WO_MATCH  0x040
103172 #define WO_ISNULL 0x080
103173 #define WO_OR     0x100       /* Two or more OR-connected terms */
103174 #define WO_AND    0x200       /* Two or more AND-connected terms */
103175 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
103176 #define WO_NOOP   0x800       /* This term does not restrict search space */
103177 
103178 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
103179 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
103180 
103181 /*
103182 ** Value for wsFlags returned by bestIndex() and stored in
103183 ** WhereLevel.wsFlags.  These flags determine which search
103184 ** strategies are appropriate.
103185 **
103186 ** The least significant 12 bits is reserved as a mask for WO_ values above.
103187 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
103188 ** But if the table is the right table of a left join, WhereLevel.wsFlags
103189 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
103190 ** the "op" parameter to findTerm when we are resolving equality constraints.
103191 ** ISNULL constraints will then not be used on the right table of a left
103192 ** join.  Tickets #2177 and #2189.
103193 */
103194 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
103195 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
103196 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
103197 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
103198 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
103199 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
103200 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
103201 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
103202 #define WHERE_IN_ABLE      0x080f1000  /* Able to support an IN operator */
103203 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
103204 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
103205 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
103206 #define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
103207 #define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
103208 #define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
103209 #define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
103210 #define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
103211 #define WHERE_OB_UNIQUE    0x00004000  /* Values in ORDER BY columns are
103212                                        ** different for every output row */
103213 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
103214 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
103215 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
103216 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
103217 #define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
103218 
103219 /*
103220 ** This module contains many separate subroutines that work together to
103221 ** find the best indices to use for accessing a particular table in a query.
103222 ** An instance of the following structure holds context information about the
103223 ** index search so that it can be more easily passed between the various
103224 ** routines.
103225 */
103226 typedef struct WhereBestIdx WhereBestIdx;
103227 struct WhereBestIdx {
103228   Parse *pParse;                  /* Parser context */
103229   WhereClause *pWC;               /* The WHERE clause */
103230   struct SrcList_item *pSrc;      /* The FROM clause term to search */
103231   Bitmask notReady;               /* Mask of cursors not available */
103232   Bitmask notValid;               /* Cursors not available for any purpose */
103233   ExprList *pOrderBy;             /* The ORDER BY clause */
103234   ExprList *pDistinct;            /* The select-list if query is DISTINCT */
103235   sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
103236   int i, n;                       /* Which loop is being coded; # of loops */
103237   WhereLevel *aLevel;             /* Info about outer loops */
103238   WhereCost cost;                 /* Lowest cost query plan */
103239 };
103240 
103241 /*
103242 ** Return TRUE if the probe cost is less than the baseline cost
103243 */
103244 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
103245   if( pProbe->rCost<pBaseline->rCost ) return 1;
103246   if( pProbe->rCost>pBaseline->rCost ) return 0;
103247   if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
103248   if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
103249   return 0;
103250 }
103251 
103252 /*
103253 ** Initialize a preallocated WhereClause structure.
103254 */
103255 static void whereClauseInit(
103256   WhereClause *pWC,        /* The WhereClause to be initialized */
103257   Parse *pParse,           /* The parsing context */
103258   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
103259   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
103260 ){
103261   pWC->pParse = pParse;
103262   pWC->pMaskSet = pMaskSet;
103263   pWC->pOuter = 0;
103264   pWC->nTerm = 0;
103265   pWC->nSlot = ArraySize(pWC->aStatic);
103266   pWC->a = pWC->aStatic;
103267   pWC->wctrlFlags = wctrlFlags;
103268 }
103269 
103270 /* Forward reference */
103271 static void whereClauseClear(WhereClause*);
103272 
103273 /*
103274 ** Deallocate all memory associated with a WhereOrInfo object.
103275 */
103276 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
103277   whereClauseClear(&p->wc);
103278   sqlite3DbFree(db, p);
103279 }
103280 
103281 /*
103282 ** Deallocate all memory associated with a WhereAndInfo object.
103283 */
103284 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
103285   whereClauseClear(&p->wc);
103286   sqlite3DbFree(db, p);
103287 }
103288 
103289 /*
103290 ** Deallocate a WhereClause structure.  The WhereClause structure
103291 ** itself is not freed.  This routine is the inverse of whereClauseInit().
103292 */
103293 static void whereClauseClear(WhereClause *pWC){
103294   int i;
103295   WhereTerm *a;
103296   sqlite3 *db = pWC->pParse->db;
103297   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
103298     if( a->wtFlags & TERM_DYNAMIC ){
103299       sqlite3ExprDelete(db, a->pExpr);
103300     }
103301     if( a->wtFlags & TERM_ORINFO ){
103302       whereOrInfoDelete(db, a->u.pOrInfo);
103303     }else if( a->wtFlags & TERM_ANDINFO ){
103304       whereAndInfoDelete(db, a->u.pAndInfo);
103305     }
103306   }
103307   if( pWC->a!=pWC->aStatic ){
103308     sqlite3DbFree(db, pWC->a);
103309   }
103310 }
103311 
103312 /*
103313 ** Add a single new WhereTerm entry to the WhereClause object pWC.
103314 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
103315 ** The index in pWC->a[] of the new WhereTerm is returned on success.
103316 ** 0 is returned if the new WhereTerm could not be added due to a memory
103317 ** allocation error.  The memory allocation failure will be recorded in
103318 ** the db->mallocFailed flag so that higher-level functions can detect it.
103319 **
103320 ** This routine will increase the size of the pWC->a[] array as necessary.
103321 **
103322 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
103323 ** for freeing the expression p is assumed by the WhereClause object pWC.
103324 ** This is true even if this routine fails to allocate a new WhereTerm.
103325 **
103326 ** WARNING:  This routine might reallocate the space used to store
103327 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
103328 ** calling this routine.  Such pointers may be reinitialized by referencing
103329 ** the pWC->a[] array.
103330 */
103331 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
103332   WhereTerm *pTerm;
103333   int idx;
103334   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
103335   if( pWC->nTerm>=pWC->nSlot ){
103336     WhereTerm *pOld = pWC->a;
103337     sqlite3 *db = pWC->pParse->db;
103338     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
103339     if( pWC->a==0 ){
103340       if( wtFlags & TERM_DYNAMIC ){
103341         sqlite3ExprDelete(db, p);
103342       }
103343       pWC->a = pOld;
103344       return 0;
103345     }
103346     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
103347     if( pOld!=pWC->aStatic ){
103348       sqlite3DbFree(db, pOld);
103349     }
103350     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
103351   }
103352   pTerm = &pWC->a[idx = pWC->nTerm++];
103353   pTerm->pExpr = sqlite3ExprSkipCollate(p);
103354   pTerm->wtFlags = wtFlags;
103355   pTerm->pWC = pWC;
103356   pTerm->iParent = -1;
103357   return idx;
103358 }
103359 
103360 /*
103361 ** This routine identifies subexpressions in the WHERE clause where
103362 ** each subexpression is separated by the AND operator or some other
103363 ** operator specified in the op parameter.  The WhereClause structure
103364 ** is filled with pointers to subexpressions.  For example:
103365 **
103366 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
103367 **           \________/     \_______________/     \________________/
103368 **            slot[0]            slot[1]               slot[2]
103369 **
103370 ** The original WHERE clause in pExpr is unaltered.  All this routine
103371 ** does is make slot[] entries point to substructure within pExpr.
103372 **
103373 ** In the previous sentence and in the diagram, "slot[]" refers to
103374 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
103375 ** all terms of the WHERE clause.
103376 */
103377 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
103378   pWC->op = (u8)op;
103379   if( pExpr==0 ) return;
103380   if( pExpr->op!=op ){
103381     whereClauseInsert(pWC, pExpr, 0);
103382   }else{
103383     whereSplit(pWC, pExpr->pLeft, op);
103384     whereSplit(pWC, pExpr->pRight, op);
103385   }
103386 }
103387 
103388 /*
103389 ** Initialize an expression mask set (a WhereMaskSet object)
103390 */
103391 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
103392 
103393 /*
103394 ** Return the bitmask for the given cursor number.  Return 0 if
103395 ** iCursor is not in the set.
103396 */
103397 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
103398   int i;
103399   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
103400   for(i=0; i<pMaskSet->n; i++){
103401     if( pMaskSet->ix[i]==iCursor ){
103402       return ((Bitmask)1)<<i;
103403     }
103404   }
103405   return 0;
103406 }
103407 
103408 /*
103409 ** Create a new mask for cursor iCursor.
103410 **
103411 ** There is one cursor per table in the FROM clause.  The number of
103412 ** tables in the FROM clause is limited by a test early in the
103413 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
103414 ** array will never overflow.
103415 */
103416 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
103417   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
103418   pMaskSet->ix[pMaskSet->n++] = iCursor;
103419 }
103420 
103421 /*
103422 ** This routine walks (recursively) an expression tree and generates
103423 ** a bitmask indicating which tables are used in that expression
103424 ** tree.
103425 **
103426 ** In order for this routine to work, the calling function must have
103427 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
103428 ** the header comment on that routine for additional information.
103429 ** The sqlite3ResolveExprNames() routines looks for column names and
103430 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
103431 ** the VDBE cursor number of the table.  This routine just has to
103432 ** translate the cursor numbers into bitmask values and OR all
103433 ** the bitmasks together.
103434 */
103435 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
103436 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
103437 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
103438   Bitmask mask = 0;
103439   if( p==0 ) return 0;
103440   if( p->op==TK_COLUMN ){
103441     mask = getMask(pMaskSet, p->iTable);
103442     return mask;
103443   }
103444   mask = exprTableUsage(pMaskSet, p->pRight);
103445   mask |= exprTableUsage(pMaskSet, p->pLeft);
103446   if( ExprHasProperty(p, EP_xIsSelect) ){
103447     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
103448   }else{
103449     mask |= exprListTableUsage(pMaskSet, p->x.pList);
103450   }
103451   return mask;
103452 }
103453 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
103454   int i;
103455   Bitmask mask = 0;
103456   if( pList ){
103457     for(i=0; i<pList->nExpr; i++){
103458       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
103459     }
103460   }
103461   return mask;
103462 }
103463 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
103464   Bitmask mask = 0;
103465   while( pS ){
103466     SrcList *pSrc = pS->pSrc;
103467     mask |= exprListTableUsage(pMaskSet, pS->pEList);
103468     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
103469     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
103470     mask |= exprTableUsage(pMaskSet, pS->pWhere);
103471     mask |= exprTableUsage(pMaskSet, pS->pHaving);
103472     if( ALWAYS(pSrc!=0) ){
103473       int i;
103474       for(i=0; i<pSrc->nSrc; i++){
103475         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
103476         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
103477       }
103478     }
103479     pS = pS->pPrior;
103480   }
103481   return mask;
103482 }
103483 
103484 /*
103485 ** Return TRUE if the given operator is one of the operators that is
103486 ** allowed for an indexable WHERE clause term.  The allowed operators are
103487 ** "=", "<", ">", "<=", ">=", and "IN".
103488 **
103489 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
103490 ** of one of the following forms: column = expression column > expression
103491 ** column >= expression column < expression column <= expression
103492 ** expression = column expression > column expression >= column
103493 ** expression < column expression <= column column IN
103494 ** (expression-list) column IN (subquery) column IS NULL
103495 */
103496 static int allowedOp(int op){
103497   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103498   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
103499   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
103500   assert( TK_GE==TK_EQ+4 );
103501   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
103502 }
103503 
103504 /*
103505 ** Swap two objects of type TYPE.
103506 */
103507 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
103508 
103509 /*
103510 ** Commute a comparison operator.  Expressions of the form "X op Y"
103511 ** are converted into "Y op X".
103512 **
103513 ** If left/right precedence rules come into play when determining the
103514 ** collating
103515 ** side of the comparison, it remains associated with the same side after
103516 ** the commutation. So "Y collate NOCASE op X" becomes
103517 ** "X op Y". This is because any collation sequence on
103518 ** the left hand side of a comparison overrides any collation sequence
103519 ** attached to the right. For the same reason the EP_Collate flag
103520 ** is not commuted.
103521 */
103522 static void exprCommute(Parse *pParse, Expr *pExpr){
103523   u16 expRight = (pExpr->pRight->flags & EP_Collate);
103524   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
103525   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
103526   if( expRight==expLeft ){
103527     /* Either X and Y both have COLLATE operator or neither do */
103528     if( expRight ){
103529       /* Both X and Y have COLLATE operators.  Make sure X is always
103530       ** used by clearing the EP_Collate flag from Y. */
103531       pExpr->pRight->flags &= ~EP_Collate;
103532     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
103533       /* Neither X nor Y have COLLATE operators, but X has a non-default
103534       ** collating sequence.  So add the EP_Collate marker on X to cause
103535       ** it to be searched first. */
103536       pExpr->pLeft->flags |= EP_Collate;
103537     }
103538   }
103539   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
103540   if( pExpr->op>=TK_GT ){
103541     assert( TK_LT==TK_GT+2 );
103542     assert( TK_GE==TK_LE+2 );
103543     assert( TK_GT>TK_EQ );
103544     assert( TK_GT<TK_LE );
103545     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
103546     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
103547   }
103548 }
103549 
103550 /*
103551 ** Translate from TK_xx operator to WO_xx bitmask.
103552 */
103553 static u16 operatorMask(int op){
103554   u16 c;
103555   assert( allowedOp(op) );
103556   if( op==TK_IN ){
103557     c = WO_IN;
103558   }else if( op==TK_ISNULL ){
103559     c = WO_ISNULL;
103560   }else{
103561     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
103562     c = (u16)(WO_EQ<<(op-TK_EQ));
103563   }
103564   assert( op!=TK_ISNULL || c==WO_ISNULL );
103565   assert( op!=TK_IN || c==WO_IN );
103566   assert( op!=TK_EQ || c==WO_EQ );
103567   assert( op!=TK_LT || c==WO_LT );
103568   assert( op!=TK_LE || c==WO_LE );
103569   assert( op!=TK_GT || c==WO_GT );
103570   assert( op!=TK_GE || c==WO_GE );
103571   return c;
103572 }
103573 
103574 /*
103575 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
103576 ** where X is a reference to the iColumn of table iCur and <op> is one of
103577 ** the WO_xx operator codes specified by the op parameter.
103578 ** Return a pointer to the term.  Return 0 if not found.
103579 **
103580 ** The term returned might by Y=<expr> if there is another constraint in
103581 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
103582 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
103583 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
103584 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
103585 ** and the second is for the column number.  There are 22 slots in aEquiv[]
103586 ** so that means we can look for X plus up to 10 other equivalent values.
103587 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
103588 ** and ... and A9=A10 and A10=<expr>.
103589 **
103590 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
103591 ** then try for the one with no dependencies on <expr> - in other words where
103592 ** <expr> is a constant expression of some kind.  Only return entries of
103593 ** the form "X <op> Y" where Y is a column in another table if no terms of
103594 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
103595 ** exist, try to return a term that does not use WO_EQUIV.
103596 */
103597 static WhereTerm *findTerm(
103598   WhereClause *pWC,     /* The WHERE clause to be searched */
103599   int iCur,             /* Cursor number of LHS */
103600   int iColumn,          /* Column number of LHS */
103601   Bitmask notReady,     /* RHS must not overlap with this mask */
103602   u32 op,               /* Mask of WO_xx values describing operator */
103603   Index *pIdx           /* Must be compatible with this index, if not NULL */
103604 ){
103605   WhereTerm *pTerm;            /* Term being examined as possible result */
103606   WhereTerm *pResult = 0;      /* The answer to return */
103607   WhereClause *pWCOrig = pWC;  /* Original pWC value */
103608   int j, k;                    /* Loop counters */
103609   Expr *pX;                /* Pointer to an expression */
103610   Parse *pParse;           /* Parsing context */
103611   int iOrigCol = iColumn;  /* Original value of iColumn */
103612   int nEquiv = 2;          /* Number of entires in aEquiv[] */
103613   int iEquiv = 2;          /* Number of entries of aEquiv[] processed so far */
103614   int aEquiv[22];          /* iCur,iColumn and up to 10 other equivalents */
103615 
103616   assert( iCur>=0 );
103617   aEquiv[0] = iCur;
103618   aEquiv[1] = iColumn;
103619   for(;;){
103620     for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
103621       for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
103622         if( pTerm->leftCursor==iCur
103623           && pTerm->u.leftColumn==iColumn
103624         ){
103625           if( (pTerm->prereqRight & notReady)==0
103626            && (pTerm->eOperator & op & WO_ALL)!=0
103627           ){
103628             if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
103629               CollSeq *pColl;
103630               char idxaff;
103631 
103632               pX = pTerm->pExpr;
103633               pParse = pWC->pParse;
103634               idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
103635               if( !sqlite3IndexAffinityOk(pX, idxaff) ){
103636                 continue;
103637               }
103638 
103639               /* Figure out the collation sequence required from an index for
103640               ** it to be useful for optimising expression pX. Store this
103641               ** value in variable pColl.
103642               */
103643               assert(pX->pLeft);
103644               pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
103645               if( pColl==0 ) pColl = pParse->db->pDfltColl;
103646 
103647               for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
103648                 if( NEVER(j>=pIdx->nColumn) ) return 0;
103649               }
103650               if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
103651                 continue;
103652               }
103653             }
103654             if( pTerm->prereqRight==0 ){
103655               pResult = pTerm;
103656               goto findTerm_success;
103657             }else if( pResult==0 ){
103658               pResult = pTerm;
103659             }
103660           }
103661           if( (pTerm->eOperator & WO_EQUIV)!=0
103662            && nEquiv<ArraySize(aEquiv)
103663           ){
103664             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
103665             assert( pX->op==TK_COLUMN );
103666             for(j=0; j<nEquiv; j+=2){
103667               if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
103668             }
103669             if( j==nEquiv ){
103670               aEquiv[j] = pX->iTable;
103671               aEquiv[j+1] = pX->iColumn;
103672               nEquiv += 2;
103673             }
103674           }
103675         }
103676       }
103677     }
103678     if( iEquiv>=nEquiv ) break;
103679     iCur = aEquiv[iEquiv++];
103680     iColumn = aEquiv[iEquiv++];
103681   }
103682 findTerm_success:
103683   return pResult;
103684 }
103685 
103686 /* Forward reference */
103687 static void exprAnalyze(SrcList*, WhereClause*, int);
103688 
103689 /*
103690 ** Call exprAnalyze on all terms in a WHERE clause.
103691 **
103692 **
103693 */
103694 static void exprAnalyzeAll(
103695   SrcList *pTabList,       /* the FROM clause */
103696   WhereClause *pWC         /* the WHERE clause to be analyzed */
103697 ){
103698   int i;
103699   for(i=pWC->nTerm-1; i>=0; i--){
103700     exprAnalyze(pTabList, pWC, i);
103701   }
103702 }
103703 
103704 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103705 /*
103706 ** Check to see if the given expression is a LIKE or GLOB operator that
103707 ** can be optimized using inequality constraints.  Return TRUE if it is
103708 ** so and false if not.
103709 **
103710 ** In order for the operator to be optimizible, the RHS must be a string
103711 ** literal that does not begin with a wildcard.
103712 */
103713 static int isLikeOrGlob(
103714   Parse *pParse,    /* Parsing and code generating context */
103715   Expr *pExpr,      /* Test this expression */
103716   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
103717   int *pisComplete, /* True if the only wildcard is % in the last character */
103718   int *pnoCase      /* True if uppercase is equivalent to lowercase */
103719 ){
103720   const char *z = 0;         /* String on RHS of LIKE operator */
103721   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
103722   ExprList *pList;           /* List of operands to the LIKE operator */
103723   int c;                     /* One character in z[] */
103724   int cnt;                   /* Number of non-wildcard prefix characters */
103725   char wc[3];                /* Wildcard characters */
103726   sqlite3 *db = pParse->db;  /* Database connection */
103727   sqlite3_value *pVal = 0;
103728   int op;                    /* Opcode of pRight */
103729 
103730   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
103731     return 0;
103732   }
103733 #ifdef SQLITE_EBCDIC
103734   if( *pnoCase ) return 0;
103735 #endif
103736   pList = pExpr->x.pList;
103737   pLeft = pList->a[1].pExpr;
103738   if( pLeft->op!=TK_COLUMN
103739    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
103740    || IsVirtual(pLeft->pTab)
103741   ){
103742     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
103743     ** be the name of an indexed column with TEXT affinity. */
103744     return 0;
103745   }
103746   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
103747 
103748   pRight = pList->a[0].pExpr;
103749   op = pRight->op;
103750   if( op==TK_REGISTER ){
103751     op = pRight->op2;
103752   }
103753   if( op==TK_VARIABLE ){
103754     Vdbe *pReprepare = pParse->pReprepare;
103755     int iCol = pRight->iColumn;
103756     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
103757     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
103758       z = (char *)sqlite3_value_text(pVal);
103759     }
103760     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
103761     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
103762   }else if( op==TK_STRING ){
103763     z = pRight->u.zToken;
103764   }
103765   if( z ){
103766     cnt = 0;
103767     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
103768       cnt++;
103769     }
103770     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
103771       Expr *pPrefix;
103772       *pisComplete = c==wc[0] && z[cnt+1]==0;
103773       pPrefix = sqlite3Expr(db, TK_STRING, z);
103774       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
103775       *ppPrefix = pPrefix;
103776       if( op==TK_VARIABLE ){
103777         Vdbe *v = pParse->pVdbe;
103778         sqlite3VdbeSetVarmask(v, pRight->iColumn);
103779         if( *pisComplete && pRight->u.zToken[1] ){
103780           /* If the rhs of the LIKE expression is a variable, and the current
103781           ** value of the variable means there is no need to invoke the LIKE
103782           ** function, then no OP_Variable will be added to the program.
103783           ** This causes problems for the sqlite3_bind_parameter_name()
103784           ** API. To workaround them, add a dummy OP_Variable here.
103785           */
103786           int r1 = sqlite3GetTempReg(pParse);
103787           sqlite3ExprCodeTarget(pParse, pRight, r1);
103788           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
103789           sqlite3ReleaseTempReg(pParse, r1);
103790         }
103791       }
103792     }else{
103793       z = 0;
103794     }
103795   }
103796 
103797   sqlite3ValueFree(pVal);
103798   return (z!=0);
103799 }
103800 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103801 
103802 
103803 #ifndef SQLITE_OMIT_VIRTUALTABLE
103804 /*
103805 ** Check to see if the given expression is of the form
103806 **
103807 **         column MATCH expr
103808 **
103809 ** If it is then return TRUE.  If not, return FALSE.
103810 */
103811 static int isMatchOfColumn(
103812   Expr *pExpr      /* Test this expression */
103813 ){
103814   ExprList *pList;
103815 
103816   if( pExpr->op!=TK_FUNCTION ){
103817     return 0;
103818   }
103819   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
103820     return 0;
103821   }
103822   pList = pExpr->x.pList;
103823   if( pList->nExpr!=2 ){
103824     return 0;
103825   }
103826   if( pList->a[1].pExpr->op != TK_COLUMN ){
103827     return 0;
103828   }
103829   return 1;
103830 }
103831 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103832 
103833 /*
103834 ** If the pBase expression originated in the ON or USING clause of
103835 ** a join, then transfer the appropriate markings over to derived.
103836 */
103837 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
103838   pDerived->flags |= pBase->flags & EP_FromJoin;
103839   pDerived->iRightJoinTable = pBase->iRightJoinTable;
103840 }
103841 
103842 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103843 /*
103844 ** Analyze a term that consists of two or more OR-connected
103845 ** subterms.  So in:
103846 **
103847 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
103848 **                          ^^^^^^^^^^^^^^^^^^^^
103849 **
103850 ** This routine analyzes terms such as the middle term in the above example.
103851 ** A WhereOrTerm object is computed and attached to the term under
103852 ** analysis, regardless of the outcome of the analysis.  Hence:
103853 **
103854 **     WhereTerm.wtFlags   |=  TERM_ORINFO
103855 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
103856 **
103857 ** The term being analyzed must have two or more of OR-connected subterms.
103858 ** A single subterm might be a set of AND-connected sub-subterms.
103859 ** Examples of terms under analysis:
103860 **
103861 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
103862 **     (B)     x=expr1 OR expr2=x OR x=expr3
103863 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
103864 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
103865 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
103866 **
103867 ** CASE 1:
103868 **
103869 ** If all subterms are of the form T.C=expr for some single column of C and
103870 ** a single table T (as shown in example B above) then create a new virtual
103871 ** term that is an equivalent IN expression.  In other words, if the term
103872 ** being analyzed is:
103873 **
103874 **      x = expr1  OR  expr2 = x  OR  x = expr3
103875 **
103876 ** then create a new virtual term like this:
103877 **
103878 **      x IN (expr1,expr2,expr3)
103879 **
103880 ** CASE 2:
103881 **
103882 ** If all subterms are indexable by a single table T, then set
103883 **
103884 **     WhereTerm.eOperator              =  WO_OR
103885 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
103886 **
103887 ** A subterm is "indexable" if it is of the form
103888 ** "T.C <op> <expr>" where C is any column of table T and
103889 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
103890 ** A subterm is also indexable if it is an AND of two or more
103891 ** subsubterms at least one of which is indexable.  Indexable AND
103892 ** subterms have their eOperator set to WO_AND and they have
103893 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
103894 **
103895 ** From another point of view, "indexable" means that the subterm could
103896 ** potentially be used with an index if an appropriate index exists.
103897 ** This analysis does not consider whether or not the index exists; that
103898 ** is something the bestIndex() routine will determine.  This analysis
103899 ** only looks at whether subterms appropriate for indexing exist.
103900 **
103901 ** All examples A through E above all satisfy case 2.  But if a term
103902 ** also statisfies case 1 (such as B) we know that the optimizer will
103903 ** always prefer case 1, so in that case we pretend that case 2 is not
103904 ** satisfied.
103905 **
103906 ** It might be the case that multiple tables are indexable.  For example,
103907 ** (E) above is indexable on tables P, Q, and R.
103908 **
103909 ** Terms that satisfy case 2 are candidates for lookup by using
103910 ** separate indices to find rowids for each subterm and composing
103911 ** the union of all rowids using a RowSet object.  This is similar
103912 ** to "bitmap indices" in other database engines.
103913 **
103914 ** OTHERWISE:
103915 **
103916 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
103917 ** zero.  This term is not useful for search.
103918 */
103919 static void exprAnalyzeOrTerm(
103920   SrcList *pSrc,            /* the FROM clause */
103921   WhereClause *pWC,         /* the complete WHERE clause */
103922   int idxTerm               /* Index of the OR-term to be analyzed */
103923 ){
103924   Parse *pParse = pWC->pParse;            /* Parser context */
103925   sqlite3 *db = pParse->db;               /* Database connection */
103926   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103927   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103928   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103929   int i;                                  /* Loop counters */
103930   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103931   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103932   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103933   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103934   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103935 
103936   /*
103937   ** Break the OR clause into its separate subterms.  The subterms are
103938   ** stored in a WhereClause structure containing within the WhereOrInfo
103939   ** object that is attached to the original OR clause term.
103940   */
103941   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103942   assert( pExpr->op==TK_OR );
103943   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
103944   if( pOrInfo==0 ) return;
103945   pTerm->wtFlags |= TERM_ORINFO;
103946   pOrWc = &pOrInfo->wc;
103947   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103948   whereSplit(pOrWc, pExpr, TK_OR);
103949   exprAnalyzeAll(pSrc, pOrWc);
103950   if( db->mallocFailed ) return;
103951   assert( pOrWc->nTerm>=2 );
103952 
103953   /*
103954   ** Compute the set of tables that might satisfy cases 1 or 2.
103955   */
103956   indexable = ~(Bitmask)0;
103957   chngToIN = ~(Bitmask)0;
103958   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103959     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103960       WhereAndInfo *pAndInfo;
103961       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103962       chngToIN = 0;
103963       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
103964       if( pAndInfo ){
103965         WhereClause *pAndWC;
103966         WhereTerm *pAndTerm;
103967         int j;
103968         Bitmask b = 0;
103969         pOrTerm->u.pAndInfo = pAndInfo;
103970         pOrTerm->wtFlags |= TERM_ANDINFO;
103971         pOrTerm->eOperator = WO_AND;
103972         pAndWC = &pAndInfo->wc;
103973         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103974         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103975         exprAnalyzeAll(pSrc, pAndWC);
103976         pAndWC->pOuter = pWC;
103977         testcase( db->mallocFailed );
103978         if( !db->mallocFailed ){
103979           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103980             assert( pAndTerm->pExpr );
103981             if( allowedOp(pAndTerm->pExpr->op) ){
103982               b |= getMask(pMaskSet, pAndTerm->leftCursor);
103983             }
103984           }
103985         }
103986         indexable &= b;
103987       }
103988     }else if( pOrTerm->wtFlags & TERM_COPIED ){
103989       /* Skip this term for now.  We revisit it when we process the
103990       ** corresponding TERM_VIRTUAL term */
103991     }else{
103992       Bitmask b;
103993       b = getMask(pMaskSet, pOrTerm->leftCursor);
103994       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103995         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
103996         b |= getMask(pMaskSet, pOther->leftCursor);
103997       }
103998       indexable &= b;
103999       if( (pOrTerm->eOperator & WO_EQ)==0 ){
104000         chngToIN = 0;
104001       }else{
104002         chngToIN &= b;
104003       }
104004     }
104005   }
104006 
104007   /*
104008   ** Record the set of tables that satisfy case 2.  The set might be
104009   ** empty.
104010   */
104011   pOrInfo->indexable = indexable;
104012   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
104013 
104014   /*
104015   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
104016   ** we have to do some additional checking to see if case 1 really
104017   ** is satisfied.
104018   **
104019   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
104020   ** that there is no possibility of transforming the OR clause into an
104021   ** IN operator because one or more terms in the OR clause contain
104022   ** something other than == on a column in the single table.  The 1-bit
104023   ** case means that every term of the OR clause is of the form
104024   ** "table.column=expr" for some single table.  The one bit that is set
104025   ** will correspond to the common table.  We still need to check to make
104026   ** sure the same column is used on all terms.  The 2-bit case is when
104027   ** the all terms are of the form "table1.column=table2.column".  It
104028   ** might be possible to form an IN operator with either table1.column
104029   ** or table2.column as the LHS if either is common to every term of
104030   ** the OR clause.
104031   **
104032   ** Note that terms of the form "table.column1=table.column2" (the
104033   ** same table on both sizes of the ==) cannot be optimized.
104034   */
104035   if( chngToIN ){
104036     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
104037     int iColumn = -1;         /* Column index on lhs of IN operator */
104038     int iCursor = -1;         /* Table cursor common to all terms */
104039     int j = 0;                /* Loop counter */
104040 
104041     /* Search for a table and column that appears on one side or the
104042     ** other of the == operator in every subterm.  That table and column
104043     ** will be recorded in iCursor and iColumn.  There might not be any
104044     ** such table and column.  Set okToChngToIN if an appropriate table
104045     ** and column is found but leave okToChngToIN false if not found.
104046     */
104047     for(j=0; j<2 && !okToChngToIN; j++){
104048       pOrTerm = pOrWc->a;
104049       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
104050         assert( pOrTerm->eOperator & WO_EQ );
104051         pOrTerm->wtFlags &= ~TERM_OR_OK;
104052         if( pOrTerm->leftCursor==iCursor ){
104053           /* This is the 2-bit case and we are on the second iteration and
104054           ** current term is from the first iteration.  So skip this term. */
104055           assert( j==1 );
104056           continue;
104057         }
104058         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
104059           /* This term must be of the form t1.a==t2.b where t2 is in the
104060           ** chngToIN set but t1 is not.  This term will be either preceeded
104061           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
104062           ** and use its inversion. */
104063           testcase( pOrTerm->wtFlags & TERM_COPIED );
104064           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
104065           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
104066           continue;
104067         }
104068         iColumn = pOrTerm->u.leftColumn;
104069         iCursor = pOrTerm->leftCursor;
104070         break;
104071       }
104072       if( i<0 ){
104073         /* No candidate table+column was found.  This can only occur
104074         ** on the second iteration */
104075         assert( j==1 );
104076         assert( IsPowerOfTwo(chngToIN) );
104077         assert( chngToIN==getMask(pMaskSet, iCursor) );
104078         break;
104079       }
104080       testcase( j==1 );
104081 
104082       /* We have found a candidate table and column.  Check to see if that
104083       ** table and column is common to every term in the OR clause */
104084       okToChngToIN = 1;
104085       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
104086         assert( pOrTerm->eOperator & WO_EQ );
104087         if( pOrTerm->leftCursor!=iCursor ){
104088           pOrTerm->wtFlags &= ~TERM_OR_OK;
104089         }else if( pOrTerm->u.leftColumn!=iColumn ){
104090           okToChngToIN = 0;
104091         }else{
104092           int affLeft, affRight;
104093           /* If the right-hand side is also a column, then the affinities
104094           ** of both right and left sides must be such that no type
104095           ** conversions are required on the right.  (Ticket #2249)
104096           */
104097           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
104098           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
104099           if( affRight!=0 && affRight!=affLeft ){
104100             okToChngToIN = 0;
104101           }else{
104102             pOrTerm->wtFlags |= TERM_OR_OK;
104103           }
104104         }
104105       }
104106     }
104107 
104108     /* At this point, okToChngToIN is true if original pTerm satisfies
104109     ** case 1.  In that case, construct a new virtual term that is
104110     ** pTerm converted into an IN operator.
104111     **
104112     ** EV: R-00211-15100
104113     */
104114     if( okToChngToIN ){
104115       Expr *pDup;            /* A transient duplicate expression */
104116       ExprList *pList = 0;   /* The RHS of the IN operator */
104117       Expr *pLeft = 0;       /* The LHS of the IN operator */
104118       Expr *pNew;            /* The complete IN operator */
104119 
104120       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
104121         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
104122         assert( pOrTerm->eOperator & WO_EQ );
104123         assert( pOrTerm->leftCursor==iCursor );
104124         assert( pOrTerm->u.leftColumn==iColumn );
104125         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
104126         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
104127         pLeft = pOrTerm->pExpr->pLeft;
104128       }
104129       assert( pLeft!=0 );
104130       pDup = sqlite3ExprDup(db, pLeft, 0);
104131       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
104132       if( pNew ){
104133         int idxNew;
104134         transferJoinMarkings(pNew, pExpr);
104135         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
104136         pNew->x.pList = pList;
104137         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
104138         testcase( idxNew==0 );
104139         exprAnalyze(pSrc, pWC, idxNew);
104140         pTerm = &pWC->a[idxTerm];
104141         pWC->a[idxNew].iParent = idxTerm;
104142         pTerm->nChild = 1;
104143       }else{
104144         sqlite3ExprListDelete(db, pList);
104145       }
104146       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
104147     }
104148   }
104149 }
104150 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
104151 
104152 /*
104153 ** The input to this routine is an WhereTerm structure with only the
104154 ** "pExpr" field filled in.  The job of this routine is to analyze the
104155 ** subexpression and populate all the other fields of the WhereTerm
104156 ** structure.
104157 **
104158 ** If the expression is of the form "<expr> <op> X" it gets commuted
104159 ** to the standard form of "X <op> <expr>".
104160 **
104161 ** If the expression is of the form "X <op> Y" where both X and Y are
104162 ** columns, then the original expression is unchanged and a new virtual
104163 ** term of the form "Y <op> X" is added to the WHERE clause and
104164 ** analyzed separately.  The original term is marked with TERM_COPIED
104165 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
104166 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
104167 ** is a commuted copy of a prior term.)  The original term has nChild=1
104168 ** and the copy has idxParent set to the index of the original term.
104169 */
104170 static void exprAnalyze(
104171   SrcList *pSrc,            /* the FROM clause */
104172   WhereClause *pWC,         /* the WHERE clause */
104173   int idxTerm               /* Index of the term to be analyzed */
104174 ){
104175   WhereTerm *pTerm;                /* The term to be analyzed */
104176   WhereMaskSet *pMaskSet;          /* Set of table index masks */
104177   Expr *pExpr;                     /* The expression to be analyzed */
104178   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
104179   Bitmask prereqAll;               /* Prerequesites of pExpr */
104180   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
104181   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
104182   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
104183   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
104184   int op;                          /* Top-level operator.  pExpr->op */
104185   Parse *pParse = pWC->pParse;     /* Parsing context */
104186   sqlite3 *db = pParse->db;        /* Database connection */
104187 
104188   if( db->mallocFailed ){
104189     return;
104190   }
104191   pTerm = &pWC->a[idxTerm];
104192   pMaskSet = pWC->pMaskSet;
104193   pExpr = pTerm->pExpr;
104194   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
104195   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
104196   op = pExpr->op;
104197   if( op==TK_IN ){
104198     assert( pExpr->pRight==0 );
104199     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104200       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
104201     }else{
104202       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
104203     }
104204   }else if( op==TK_ISNULL ){
104205     pTerm->prereqRight = 0;
104206   }else{
104207     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
104208   }
104209   prereqAll = exprTableUsage(pMaskSet, pExpr);
104210   if( ExprHasProperty(pExpr, EP_FromJoin) ){
104211     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
104212     prereqAll |= x;
104213     extraRight = x-1;  /* ON clause terms may not be used with an index
104214                        ** on left table of a LEFT JOIN.  Ticket #3015 */
104215   }
104216   pTerm->prereqAll = prereqAll;
104217   pTerm->leftCursor = -1;
104218   pTerm->iParent = -1;
104219   pTerm->eOperator = 0;
104220   if( allowedOp(op) ){
104221     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
104222     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
104223     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
104224     if( pLeft->op==TK_COLUMN ){
104225       pTerm->leftCursor = pLeft->iTable;
104226       pTerm->u.leftColumn = pLeft->iColumn;
104227       pTerm->eOperator = operatorMask(op) & opMask;
104228     }
104229     if( pRight && pRight->op==TK_COLUMN ){
104230       WhereTerm *pNew;
104231       Expr *pDup;
104232       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
104233       if( pTerm->leftCursor>=0 ){
104234         int idxNew;
104235         pDup = sqlite3ExprDup(db, pExpr, 0);
104236         if( db->mallocFailed ){
104237           sqlite3ExprDelete(db, pDup);
104238           return;
104239         }
104240         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
104241         if( idxNew==0 ) return;
104242         pNew = &pWC->a[idxNew];
104243         pNew->iParent = idxTerm;
104244         pTerm = &pWC->a[idxTerm];
104245         pTerm->nChild = 1;
104246         pTerm->wtFlags |= TERM_COPIED;
104247         if( pExpr->op==TK_EQ
104248          && !ExprHasProperty(pExpr, EP_FromJoin)
104249          && OptimizationEnabled(db, SQLITE_Transitive)
104250         ){
104251           pTerm->eOperator |= WO_EQUIV;
104252           eExtraOp = WO_EQUIV;
104253         }
104254       }else{
104255         pDup = pExpr;
104256         pNew = pTerm;
104257       }
104258       exprCommute(pParse, pDup);
104259       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
104260       pNew->leftCursor = pLeft->iTable;
104261       pNew->u.leftColumn = pLeft->iColumn;
104262       testcase( (prereqLeft | extraRight) != prereqLeft );
104263       pNew->prereqRight = prereqLeft | extraRight;
104264       pNew->prereqAll = prereqAll;
104265       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
104266     }
104267   }
104268 
104269 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
104270   /* If a term is the BETWEEN operator, create two new virtual terms
104271   ** that define the range that the BETWEEN implements.  For example:
104272   **
104273   **      a BETWEEN b AND c
104274   **
104275   ** is converted into:
104276   **
104277   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
104278   **
104279   ** The two new terms are added onto the end of the WhereClause object.
104280   ** The new terms are "dynamic" and are children of the original BETWEEN
104281   ** term.  That means that if the BETWEEN term is coded, the children are
104282   ** skipped.  Or, if the children are satisfied by an index, the original
104283   ** BETWEEN term is skipped.
104284   */
104285   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
104286     ExprList *pList = pExpr->x.pList;
104287     int i;
104288     static const u8 ops[] = {TK_GE, TK_LE};
104289     assert( pList!=0 );
104290     assert( pList->nExpr==2 );
104291     for(i=0; i<2; i++){
104292       Expr *pNewExpr;
104293       int idxNew;
104294       pNewExpr = sqlite3PExpr(pParse, ops[i],
104295                              sqlite3ExprDup(db, pExpr->pLeft, 0),
104296                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
104297       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
104298       testcase( idxNew==0 );
104299       exprAnalyze(pSrc, pWC, idxNew);
104300       pTerm = &pWC->a[idxTerm];
104301       pWC->a[idxNew].iParent = idxTerm;
104302     }
104303     pTerm->nChild = 2;
104304   }
104305 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
104306 
104307 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
104308   /* Analyze a term that is composed of two or more subterms connected by
104309   ** an OR operator.
104310   */
104311   else if( pExpr->op==TK_OR ){
104312     assert( pWC->op==TK_AND );
104313     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
104314     pTerm = &pWC->a[idxTerm];
104315   }
104316 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104317 
104318 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
104319   /* Add constraints to reduce the search space on a LIKE or GLOB
104320   ** operator.
104321   **
104322   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
104323   **
104324   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
104325   **
104326   ** The last character of the prefix "abc" is incremented to form the
104327   ** termination condition "abd".
104328   */
104329   if( pWC->op==TK_AND
104330    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
104331   ){
104332     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
104333     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
104334     Expr *pNewExpr1;
104335     Expr *pNewExpr2;
104336     int idxNew1;
104337     int idxNew2;
104338     Token sCollSeqName;  /* Name of collating sequence */
104339 
104340     pLeft = pExpr->x.pList->a[1].pExpr;
104341     pStr2 = sqlite3ExprDup(db, pStr1, 0);
104342     if( !db->mallocFailed ){
104343       u8 c, *pC;       /* Last character before the first wildcard */
104344       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
104345       c = *pC;
104346       if( noCase ){
104347         /* The point is to increment the last character before the first
104348         ** wildcard.  But if we increment '@', that will push it into the
104349         ** alphabetic range where case conversions will mess up the
104350         ** inequality.  To avoid this, make sure to also run the full
104351         ** LIKE on all candidate expressions by clearing the isComplete flag
104352         */
104353         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
104354 
104355 
104356         c = sqlite3UpperToLower[c];
104357       }
104358       *pC = c + 1;
104359     }
104360     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
104361     sCollSeqName.n = 6;
104362     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
104363     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
104364            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
104365            pStr1, 0);
104366     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
104367     testcase( idxNew1==0 );
104368     exprAnalyze(pSrc, pWC, idxNew1);
104369     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
104370     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
104371            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
104372            pStr2, 0);
104373     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
104374     testcase( idxNew2==0 );
104375     exprAnalyze(pSrc, pWC, idxNew2);
104376     pTerm = &pWC->a[idxTerm];
104377     if( isComplete ){
104378       pWC->a[idxNew1].iParent = idxTerm;
104379       pWC->a[idxNew2].iParent = idxTerm;
104380       pTerm->nChild = 2;
104381     }
104382   }
104383 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
104384 
104385 #ifndef SQLITE_OMIT_VIRTUALTABLE
104386   /* Add a WO_MATCH auxiliary term to the constraint set if the
104387   ** current expression is of the form:  column MATCH expr.
104388   ** This information is used by the xBestIndex methods of
104389   ** virtual tables.  The native query optimizer does not attempt
104390   ** to do anything with MATCH functions.
104391   */
104392   if( isMatchOfColumn(pExpr) ){
104393     int idxNew;
104394     Expr *pRight, *pLeft;
104395     WhereTerm *pNewTerm;
104396     Bitmask prereqColumn, prereqExpr;
104397 
104398     pRight = pExpr->x.pList->a[0].pExpr;
104399     pLeft = pExpr->x.pList->a[1].pExpr;
104400     prereqExpr = exprTableUsage(pMaskSet, pRight);
104401     prereqColumn = exprTableUsage(pMaskSet, pLeft);
104402     if( (prereqExpr & prereqColumn)==0 ){
104403       Expr *pNewExpr;
104404       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
104405                               0, sqlite3ExprDup(db, pRight, 0), 0);
104406       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
104407       testcase( idxNew==0 );
104408       pNewTerm = &pWC->a[idxNew];
104409       pNewTerm->prereqRight = prereqExpr;
104410       pNewTerm->leftCursor = pLeft->iTable;
104411       pNewTerm->u.leftColumn = pLeft->iColumn;
104412       pNewTerm->eOperator = WO_MATCH;
104413       pNewTerm->iParent = idxTerm;
104414       pTerm = &pWC->a[idxTerm];
104415       pTerm->nChild = 1;
104416       pTerm->wtFlags |= TERM_COPIED;
104417       pNewTerm->prereqAll = pTerm->prereqAll;
104418     }
104419   }
104420 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104421 
104422 #ifdef SQLITE_ENABLE_STAT3
104423   /* When sqlite_stat3 histogram data is available an operator of the
104424   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
104425   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
104426   ** virtual term of that form.
104427   **
104428   ** Note that the virtual term must be tagged with TERM_VNULL.  This
104429   ** TERM_VNULL tag will suppress the not-null check at the beginning
104430   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
104431   ** the start of the loop will prevent any results from being returned.
104432   */
104433   if( pExpr->op==TK_NOTNULL
104434    && pExpr->pLeft->op==TK_COLUMN
104435    && pExpr->pLeft->iColumn>=0
104436   ){
104437     Expr *pNewExpr;
104438     Expr *pLeft = pExpr->pLeft;
104439     int idxNew;
104440     WhereTerm *pNewTerm;
104441 
104442     pNewExpr = sqlite3PExpr(pParse, TK_GT,
104443                             sqlite3ExprDup(db, pLeft, 0),
104444                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
104445 
104446     idxNew = whereClauseInsert(pWC, pNewExpr,
104447                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
104448     if( idxNew ){
104449       pNewTerm = &pWC->a[idxNew];
104450       pNewTerm->prereqRight = 0;
104451       pNewTerm->leftCursor = pLeft->iTable;
104452       pNewTerm->u.leftColumn = pLeft->iColumn;
104453       pNewTerm->eOperator = WO_GT;
104454       pNewTerm->iParent = idxTerm;
104455       pTerm = &pWC->a[idxTerm];
104456       pTerm->nChild = 1;
104457       pTerm->wtFlags |= TERM_COPIED;
104458       pNewTerm->prereqAll = pTerm->prereqAll;
104459     }
104460   }
104461 #endif /* SQLITE_ENABLE_STAT */
104462 
104463   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
104464   ** an index for tables to the left of the join.
104465   */
104466   pTerm->prereqRight |= extraRight;
104467 }
104468 
104469 /*
104470 ** This function searches the expression list passed as the second argument
104471 ** for an expression of type TK_COLUMN that refers to the same column and
104472 ** uses the same collation sequence as the iCol'th column of index pIdx.
104473 ** Argument iBase is the cursor number used for the table that pIdx refers
104474 ** to.
104475 **
104476 ** If such an expression is found, its index in pList->a[] is returned. If
104477 ** no expression is found, -1 is returned.
104478 */
104479 static int findIndexCol(
104480   Parse *pParse,                  /* Parse context */
104481   ExprList *pList,                /* Expression list to search */
104482   int iBase,                      /* Cursor for table associated with pIdx */
104483   Index *pIdx,                    /* Index to match column of */
104484   int iCol                        /* Column of index to match */
104485 ){
104486   int i;
104487   const char *zColl = pIdx->azColl[iCol];
104488 
104489   for(i=0; i<pList->nExpr; i++){
104490     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
104491     if( p->op==TK_COLUMN
104492      && p->iColumn==pIdx->aiColumn[iCol]
104493      && p->iTable==iBase
104494     ){
104495       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
104496       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
104497         return i;
104498       }
104499     }
104500   }
104501 
104502   return -1;
104503 }
104504 
104505 /*
104506 ** This routine determines if pIdx can be used to assist in processing a
104507 ** DISTINCT qualifier. In other words, it tests whether or not using this
104508 ** index for the outer loop guarantees that rows with equal values for
104509 ** all expressions in the pDistinct list are delivered grouped together.
104510 **
104511 ** For example, the query
104512 **
104513 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
104514 **
104515 ** can benefit from any index on columns "b" and "c".
104516 */
104517 static int isDistinctIndex(
104518   Parse *pParse,                  /* Parsing context */
104519   WhereClause *pWC,               /* The WHERE clause */
104520   Index *pIdx,                    /* The index being considered */
104521   int base,                       /* Cursor number for the table pIdx is on */
104522   ExprList *pDistinct,            /* The DISTINCT expressions */
104523   int nEqCol                      /* Number of index columns with == */
104524 ){
104525   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
104526   int i;                          /* Iterator variable */
104527 
104528   assert( pDistinct!=0 );
104529   if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
104530   testcase( pDistinct->nExpr==BMS-1 );
104531 
104532   /* Loop through all the expressions in the distinct list. If any of them
104533   ** are not simple column references, return early. Otherwise, test if the
104534   ** WHERE clause contains a "col=X" clause. If it does, the expression
104535   ** can be ignored. If it does not, and the column does not belong to the
104536   ** same table as index pIdx, return early. Finally, if there is no
104537   ** matching "col=X" expression and the column is on the same table as pIdx,
104538   ** set the corresponding bit in variable mask.
104539   */
104540   for(i=0; i<pDistinct->nExpr; i++){
104541     WhereTerm *pTerm;
104542     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
104543     if( p->op!=TK_COLUMN ) return 0;
104544     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
104545     if( pTerm ){
104546       Expr *pX = pTerm->pExpr;
104547       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104548       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
104549       if( p1==p2 ) continue;
104550     }
104551     if( p->iTable!=base ) return 0;
104552     mask |= (((Bitmask)1) << i);
104553   }
104554 
104555   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
104556     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
104557     if( iExpr<0 ) break;
104558     mask &= ~(((Bitmask)1) << iExpr);
104559   }
104560 
104561   return (mask==0);
104562 }
104563 
104564 
104565 /*
104566 ** Return true if the DISTINCT expression-list passed as the third argument
104567 ** is redundant. A DISTINCT list is redundant if the database contains a
104568 ** UNIQUE index that guarantees that the result of the query will be distinct
104569 ** anyway.
104570 */
104571 static int isDistinctRedundant(
104572   Parse *pParse,
104573   SrcList *pTabList,
104574   WhereClause *pWC,
104575   ExprList *pDistinct
104576 ){
104577   Table *pTab;
104578   Index *pIdx;
104579   int i;
104580   int iBase;
104581 
104582   /* If there is more than one table or sub-select in the FROM clause of
104583   ** this query, then it will not be possible to show that the DISTINCT
104584   ** clause is redundant. */
104585   if( pTabList->nSrc!=1 ) return 0;
104586   iBase = pTabList->a[0].iCursor;
104587   pTab = pTabList->a[0].pTab;
104588 
104589   /* If any of the expressions is an IPK column on table iBase, then return
104590   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
104591   ** current SELECT is a correlated sub-query.
104592   */
104593   for(i=0; i<pDistinct->nExpr; i++){
104594     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
104595     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
104596   }
104597 
104598   /* Loop through all indices on the table, checking each to see if it makes
104599   ** the DISTINCT qualifier redundant. It does so if:
104600   **
104601   **   1. The index is itself UNIQUE, and
104602   **
104603   **   2. All of the columns in the index are either part of the pDistinct
104604   **      list, or else the WHERE clause contains a term of the form "col=X",
104605   **      where X is a constant value. The collation sequences of the
104606   **      comparison and select-list expressions must match those of the index.
104607   **
104608   **   3. All of those index columns for which the WHERE clause does not
104609   **      contain a "col=X" term are subject to a NOT NULL constraint.
104610   */
104611   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104612     if( pIdx->onError==OE_None ) continue;
104613     for(i=0; i<pIdx->nColumn; i++){
104614       int iCol = pIdx->aiColumn[i];
104615       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
104616         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
104617         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
104618           break;
104619         }
104620       }
104621     }
104622     if( i==pIdx->nColumn ){
104623       /* This index implies that the DISTINCT qualifier is redundant. */
104624       return 1;
104625     }
104626   }
104627 
104628   return 0;
104629 }
104630 
104631 /*
104632 ** Prepare a crude estimate of the logarithm of the input value.
104633 ** The results need not be exact.  This is only used for estimating
104634 ** the total cost of performing operations with O(logN) or O(NlogN)
104635 ** complexity.  Because N is just a guess, it is no great tragedy if
104636 ** logN is a little off.
104637 */
104638 static double estLog(double N){
104639   double logN = 1;
104640   double x = 10;
104641   while( N>x ){
104642     logN += 1;
104643     x *= 10;
104644   }
104645   return logN;
104646 }
104647 
104648 /*
104649 ** Two routines for printing the content of an sqlite3_index_info
104650 ** structure.  Used for testing and debugging only.  If neither
104651 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
104652 ** are no-ops.
104653 */
104654 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
104655 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
104656   int i;
104657   if( !sqlite3WhereTrace ) return;
104658   for(i=0; i<p->nConstraint; i++){
104659     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
104660        i,
104661        p->aConstraint[i].iColumn,
104662        p->aConstraint[i].iTermOffset,
104663        p->aConstraint[i].op,
104664        p->aConstraint[i].usable);
104665   }
104666   for(i=0; i<p->nOrderBy; i++){
104667     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
104668        i,
104669        p->aOrderBy[i].iColumn,
104670        p->aOrderBy[i].desc);
104671   }
104672 }
104673 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
104674   int i;
104675   if( !sqlite3WhereTrace ) return;
104676   for(i=0; i<p->nConstraint; i++){
104677     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
104678        i,
104679        p->aConstraintUsage[i].argvIndex,
104680        p->aConstraintUsage[i].omit);
104681   }
104682   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
104683   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
104684   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
104685   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
104686 }
104687 #else
104688 #define TRACE_IDX_INPUTS(A)
104689 #define TRACE_IDX_OUTPUTS(A)
104690 #endif
104691 
104692 /*
104693 ** Required because bestIndex() is called by bestOrClauseIndex()
104694 */
104695 static void bestIndex(WhereBestIdx*);
104696 
104697 /*
104698 ** This routine attempts to find an scanning strategy that can be used
104699 ** to optimize an 'OR' expression that is part of a WHERE clause.
104700 **
104701 ** The table associated with FROM clause term pSrc may be either a
104702 ** regular B-Tree table or a virtual table.
104703 */
104704 static void bestOrClauseIndex(WhereBestIdx *p){
104705 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
104706   WhereClause *pWC = p->pWC;           /* The WHERE clause */
104707   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
104708   const int iCur = pSrc->iCursor;      /* The cursor of the table  */
104709   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
104710   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
104711   WhereTerm *pTerm;                    /* A single term of the WHERE clause */
104712 
104713   /* The OR-clause optimization is disallowed if the INDEXED BY or
104714   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
104715   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
104716     return;
104717   }
104718   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
104719     return;
104720   }
104721 
104722   /* Search the WHERE clause terms for a usable WO_OR term. */
104723   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104724     if( (pTerm->eOperator & WO_OR)!=0
104725      && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
104726      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
104727     ){
104728       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
104729       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
104730       WhereTerm *pOrTerm;
104731       int flags = WHERE_MULTI_OR;
104732       double rTotal = 0;
104733       double nRow = 0;
104734       Bitmask used = 0;
104735       WhereBestIdx sBOI;
104736 
104737       sBOI = *p;
104738       sBOI.pOrderBy = 0;
104739       sBOI.pDistinct = 0;
104740       sBOI.ppIdxInfo = 0;
104741       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
104742         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
104743           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
104744         ));
104745         if( (pOrTerm->eOperator& WO_AND)!=0 ){
104746           sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
104747           bestIndex(&sBOI);
104748         }else if( pOrTerm->leftCursor==iCur ){
104749           WhereClause tempWC;
104750           tempWC.pParse = pWC->pParse;
104751           tempWC.pMaskSet = pWC->pMaskSet;
104752           tempWC.pOuter = pWC;
104753           tempWC.op = TK_AND;
104754           tempWC.a = pOrTerm;
104755           tempWC.wctrlFlags = 0;
104756           tempWC.nTerm = 1;
104757           sBOI.pWC = &tempWC;
104758           bestIndex(&sBOI);
104759         }else{
104760           continue;
104761         }
104762         rTotal += sBOI.cost.rCost;
104763         nRow += sBOI.cost.plan.nRow;
104764         used |= sBOI.cost.used;
104765         if( rTotal>=p->cost.rCost ) break;
104766       }
104767 
104768       /* If there is an ORDER BY clause, increase the scan cost to account
104769       ** for the cost of the sort. */
104770       if( p->pOrderBy!=0 ){
104771         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104772                     rTotal, rTotal+nRow*estLog(nRow)));
104773         rTotal += nRow*estLog(nRow);
104774       }
104775 
104776       /* If the cost of scanning using this OR term for optimization is
104777       ** less than the current cost stored in pCost, replace the contents
104778       ** of pCost. */
104779       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104780       if( rTotal<p->cost.rCost ){
104781         p->cost.rCost = rTotal;
104782         p->cost.used = used;
104783         p->cost.plan.nRow = nRow;
104784         p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
104785         p->cost.plan.wsFlags = flags;
104786         p->cost.plan.u.pTerm = pTerm;
104787       }
104788     }
104789   }
104790 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104791 }
104792 
104793 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104794 /*
104795 ** Return TRUE if the WHERE clause term pTerm is of a form where it
104796 ** could be used with an index to access pSrc, assuming an appropriate
104797 ** index existed.
104798 */
104799 static int termCanDriveIndex(
104800   WhereTerm *pTerm,              /* WHERE clause term to check */
104801   struct SrcList_item *pSrc,     /* Table we are trying to access */
104802   Bitmask notReady               /* Tables in outer loops of the join */
104803 ){
104804   char aff;
104805   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104806   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
104807   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104808   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104809   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104810   return 1;
104811 }
104812 #endif
104813 
104814 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104815 /*
104816 ** If the query plan for pSrc specified in pCost is a full table scan
104817 ** and indexing is allows (if there is no NOT INDEXED clause) and it
104818 ** possible to construct a transient index that would perform better
104819 ** than a full table scan even when the cost of constructing the index
104820 ** is taken into account, then alter the query plan to use the
104821 ** transient index.
104822 */
104823 static void bestAutomaticIndex(WhereBestIdx *p){
104824   Parse *pParse = p->pParse;            /* The parsing context */
104825   WhereClause *pWC = p->pWC;            /* The WHERE clause */
104826   struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
104827   double nTableRow;                     /* Rows in the input table */
104828   double logN;                          /* log(nTableRow) */
104829   double costTempIdx;         /* per-query cost of the transient index */
104830   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104831   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104832   Table *pTable;              /* Table tht might be indexed */
104833 
104834   if( pParse->nQueryLoop<=(double)1 ){
104835     /* There is no point in building an automatic index for a single scan */
104836     return;
104837   }
104838   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
104839     /* Automatic indices are disabled at run-time */
104840     return;
104841   }
104842   if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
104843    && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
104844   ){
104845     /* We already have some kind of index in use for this query. */
104846     return;
104847   }
104848   if( pSrc->viaCoroutine ){
104849     /* Cannot index a co-routine */
104850     return;
104851   }
104852   if( pSrc->notIndexed ){
104853     /* The NOT INDEXED clause appears in the SQL. */
104854     return;
104855   }
104856   if( pSrc->isCorrelated ){
104857     /* The source is a correlated sub-query. No point in indexing it. */
104858     return;
104859   }
104860 
104861   assert( pParse->nQueryLoop >= (double)1 );
104862   pTable = pSrc->pTab;
104863   nTableRow = pTable->nRowEst;
104864   logN = estLog(nTableRow);
104865   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104866   if( costTempIdx>=p->cost.rCost ){
104867     /* The cost of creating the transient table would be greater than
104868     ** doing the full table scan */
104869     return;
104870   }
104871 
104872   /* Search for any equality comparison term */
104873   pWCEnd = &pWC->a[pWC->nTerm];
104874   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104875     if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
104876       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104877                     p->cost.rCost, costTempIdx));
104878       p->cost.rCost = costTempIdx;
104879       p->cost.plan.nRow = logN + 1;
104880       p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
104881       p->cost.used = pTerm->prereqRight;
104882       break;
104883     }
104884   }
104885 }
104886 #else
104887 # define bestAutomaticIndex(A)  /* no-op */
104888 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104889 
104890 
104891 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104892 /*
104893 ** Generate code to construct the Index object for an automatic index
104894 ** and to set up the WhereLevel object pLevel so that the code generator
104895 ** makes use of the automatic index.
104896 */
104897 static void constructAutomaticIndex(
104898   Parse *pParse,              /* The parsing context */
104899   WhereClause *pWC,           /* The WHERE clause */
104900   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104901   Bitmask notReady,           /* Mask of cursors that are not available */
104902   WhereLevel *pLevel          /* Write new index here */
104903 ){
104904   int nColumn;                /* Number of columns in the constructed index */
104905   WhereTerm *pTerm;           /* A single term of the WHERE clause */
104906   WhereTerm *pWCEnd;          /* End of pWC->a[] */
104907   int nByte;                  /* Byte of memory needed for pIdx */
104908   Index *pIdx;                /* Object describing the transient index */
104909   Vdbe *v;                    /* Prepared statement under construction */
104910   int addrInit;               /* Address of the initialization bypass jump */
104911   Table *pTable;              /* The table being indexed */
104912   KeyInfo *pKeyinfo;          /* Key information for the index */
104913   int addrTop;                /* Top of the index fill loop */
104914   int regRecord;              /* Register holding an index record */
104915   int n;                      /* Column counter */
104916   int i;                      /* Loop counter */
104917   int mxBitCol;               /* Maximum column in pSrc->colUsed */
104918   CollSeq *pColl;             /* Collating sequence to on a column */
104919   Bitmask idxCols;            /* Bitmap of columns used for indexing */
104920   Bitmask extraCols;          /* Bitmap of additional columns */
104921 
104922   /* Generate code to skip over the creation and initialization of the
104923   ** transient index on 2nd and subsequent iterations of the loop. */
104924   v = pParse->pVdbe;
104925   assert( v!=0 );
104926   addrInit = sqlite3CodeOnce(pParse);
104927 
104928   /* Count the number of columns that will be added to the index
104929   ** and used to match WHERE clause constraints */
104930   nColumn = 0;
104931   pTable = pSrc->pTab;
104932   pWCEnd = &pWC->a[pWC->nTerm];
104933   idxCols = 0;
104934   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104935     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104936       int iCol = pTerm->u.leftColumn;
104937       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104938       testcase( iCol==BMS );
104939       testcase( iCol==BMS-1 );
104940       if( (idxCols & cMask)==0 ){
104941         nColumn++;
104942         idxCols |= cMask;
104943       }
104944     }
104945   }
104946   assert( nColumn>0 );
104947   pLevel->plan.nEq = nColumn;
104948 
104949   /* Count the number of additional columns needed to create a
104950   ** covering index.  A "covering index" is an index that contains all
104951   ** columns that are needed by the query.  With a covering index, the
104952   ** original table never needs to be accessed.  Automatic indices must
104953   ** be a covering index because the index will not be updated if the
104954   ** original table changes and the index and table cannot both be used
104955   ** if they go out of sync.
104956   */
104957   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104958   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104959   testcase( pTable->nCol==BMS-1 );
104960   testcase( pTable->nCol==BMS-2 );
104961   for(i=0; i<mxBitCol; i++){
104962     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104963   }
104964   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104965     nColumn += pTable->nCol - BMS + 1;
104966   }
104967   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104968 
104969   /* Construct the Index object to describe this index */
104970   nByte = sizeof(Index);
104971   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104972   nByte += nColumn*sizeof(char*);   /* Index.azColl */
104973   nByte += nColumn;                 /* Index.aSortOrder */
104974   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
104975   if( pIdx==0 ) return;
104976   pLevel->plan.u.pIdx = pIdx;
104977   pIdx->azColl = (char**)&pIdx[1];
104978   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104979   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104980   pIdx->zName = "auto-index";
104981   pIdx->nColumn = nColumn;
104982   pIdx->pTable = pTable;
104983   n = 0;
104984   idxCols = 0;
104985   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104986     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104987       int iCol = pTerm->u.leftColumn;
104988       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104989       if( (idxCols & cMask)==0 ){
104990         Expr *pX = pTerm->pExpr;
104991         idxCols |= cMask;
104992         pIdx->aiColumn[n] = pTerm->u.leftColumn;
104993         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104994         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104995         n++;
104996       }
104997     }
104998   }
104999   assert( (u32)n==pLevel->plan.nEq );
105000 
105001   /* Add additional columns needed to make the automatic index into
105002   ** a covering index */
105003   for(i=0; i<mxBitCol; i++){
105004     if( extraCols & (((Bitmask)1)<<i) ){
105005       pIdx->aiColumn[n] = i;
105006       pIdx->azColl[n] = "BINARY";
105007       n++;
105008     }
105009   }
105010   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
105011     for(i=BMS-1; i<pTable->nCol; i++){
105012       pIdx->aiColumn[n] = i;
105013       pIdx->azColl[n] = "BINARY";
105014       n++;
105015     }
105016   }
105017   assert( n==nColumn );
105018 
105019   /* Create the automatic index */
105020   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
105021   assert( pLevel->iIdxCur>=0 );
105022   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
105023                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
105024   VdbeComment((v, "for %s", pTable->zName));
105025 
105026   /* Fill the automatic index with content */
105027   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
105028   regRecord = sqlite3GetTempReg(pParse);
105029   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
105030   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
105031   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
105032   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
105033   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
105034   sqlite3VdbeJumpHere(v, addrTop);
105035   sqlite3ReleaseTempReg(pParse, regRecord);
105036 
105037   /* Jump here when skipping the initialization */
105038   sqlite3VdbeJumpHere(v, addrInit);
105039 }
105040 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
105041 
105042 #ifndef SQLITE_OMIT_VIRTUALTABLE
105043 /*
105044 ** Allocate and populate an sqlite3_index_info structure. It is the
105045 ** responsibility of the caller to eventually release the structure
105046 ** by passing the pointer returned by this function to sqlite3_free().
105047 */
105048 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
105049   Parse *pParse = p->pParse;
105050   WhereClause *pWC = p->pWC;
105051   struct SrcList_item *pSrc = p->pSrc;
105052   ExprList *pOrderBy = p->pOrderBy;
105053   int i, j;
105054   int nTerm;
105055   struct sqlite3_index_constraint *pIdxCons;
105056   struct sqlite3_index_orderby *pIdxOrderBy;
105057   struct sqlite3_index_constraint_usage *pUsage;
105058   WhereTerm *pTerm;
105059   int nOrderBy;
105060   sqlite3_index_info *pIdxInfo;
105061 
105062   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
105063 
105064   /* Count the number of possible WHERE clause constraints referring
105065   ** to this virtual table */
105066   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
105067     if( pTerm->leftCursor != pSrc->iCursor ) continue;
105068     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
105069     testcase( pTerm->eOperator & WO_IN );
105070     testcase( pTerm->eOperator & WO_ISNULL );
105071     if( pTerm->eOperator & (WO_ISNULL) ) continue;
105072     if( pTerm->wtFlags & TERM_VNULL ) continue;
105073     nTerm++;
105074   }
105075 
105076   /* If the ORDER BY clause contains only columns in the current
105077   ** virtual table then allocate space for the aOrderBy part of
105078   ** the sqlite3_index_info structure.
105079   */
105080   nOrderBy = 0;
105081   if( pOrderBy ){
105082     int n = pOrderBy->nExpr;
105083     for(i=0; i<n; i++){
105084       Expr *pExpr = pOrderBy->a[i].pExpr;
105085       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
105086     }
105087     if( i==n){
105088       nOrderBy = n;
105089     }
105090   }
105091 
105092   /* Allocate the sqlite3_index_info structure
105093   */
105094   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
105095                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
105096                            + sizeof(*pIdxOrderBy)*nOrderBy );
105097   if( pIdxInfo==0 ){
105098     sqlite3ErrorMsg(pParse, "out of memory");
105099     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
105100     return 0;
105101   }
105102 
105103   /* Initialize the structure.  The sqlite3_index_info structure contains
105104   ** many fields that are declared "const" to prevent xBestIndex from
105105   ** changing them.  We have to do some funky casting in order to
105106   ** initialize those fields.
105107   */
105108   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
105109   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
105110   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
105111   *(int*)&pIdxInfo->nConstraint = nTerm;
105112   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
105113   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
105114   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
105115   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
105116                                                                    pUsage;
105117 
105118   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
105119     u8 op;
105120     if( pTerm->leftCursor != pSrc->iCursor ) continue;
105121     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
105122     testcase( pTerm->eOperator & WO_IN );
105123     testcase( pTerm->eOperator & WO_ISNULL );
105124     if( pTerm->eOperator & (WO_ISNULL) ) continue;
105125     if( pTerm->wtFlags & TERM_VNULL ) continue;
105126     pIdxCons[j].iColumn = pTerm->u.leftColumn;
105127     pIdxCons[j].iTermOffset = i;
105128     op = (u8)pTerm->eOperator & WO_ALL;
105129     if( op==WO_IN ) op = WO_EQ;
105130     pIdxCons[j].op = op;
105131     /* The direct assignment in the previous line is possible only because
105132     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
105133     ** following asserts verify this fact. */
105134     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
105135     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
105136     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
105137     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
105138     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
105139     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
105140     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
105141     j++;
105142   }
105143   for(i=0; i<nOrderBy; i++){
105144     Expr *pExpr = pOrderBy->a[i].pExpr;
105145     pIdxOrderBy[i].iColumn = pExpr->iColumn;
105146     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
105147   }
105148 
105149   return pIdxInfo;
105150 }
105151 
105152 /*
105153 ** The table object reference passed as the second argument to this function
105154 ** must represent a virtual table. This function invokes the xBestIndex()
105155 ** method of the virtual table with the sqlite3_index_info pointer passed
105156 ** as the argument.
105157 **
105158 ** If an error occurs, pParse is populated with an error message and a
105159 ** non-zero value is returned. Otherwise, 0 is returned and the output
105160 ** part of the sqlite3_index_info structure is left populated.
105161 **
105162 ** Whether or not an error is returned, it is the responsibility of the
105163 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
105164 ** that this is required.
105165 */
105166 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
105167   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
105168   int i;
105169   int rc;
105170 
105171   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
105172   TRACE_IDX_INPUTS(p);
105173   rc = pVtab->pModule->xBestIndex(pVtab, p);
105174   TRACE_IDX_OUTPUTS(p);
105175 
105176   if( rc!=SQLITE_OK ){
105177     if( rc==SQLITE_NOMEM ){
105178       pParse->db->mallocFailed = 1;
105179     }else if( !pVtab->zErrMsg ){
105180       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
105181     }else{
105182       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
105183     }
105184   }
105185   sqlite3_free(pVtab->zErrMsg);
105186   pVtab->zErrMsg = 0;
105187 
105188   for(i=0; i<p->nConstraint; i++){
105189     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
105190       sqlite3ErrorMsg(pParse,
105191           "table %s: xBestIndex returned an invalid plan", pTab->zName);
105192     }
105193   }
105194 
105195   return pParse->nErr;
105196 }
105197 
105198 
105199 /*
105200 ** Compute the best index for a virtual table.
105201 **
105202 ** The best index is computed by the xBestIndex method of the virtual
105203 ** table module.  This routine is really just a wrapper that sets up
105204 ** the sqlite3_index_info structure that is used to communicate with
105205 ** xBestIndex.
105206 **
105207 ** In a join, this routine might be called multiple times for the
105208 ** same virtual table.  The sqlite3_index_info structure is created
105209 ** and initialized on the first invocation and reused on all subsequent
105210 ** invocations.  The sqlite3_index_info structure is also used when
105211 ** code is generated to access the virtual table.  The whereInfoDelete()
105212 ** routine takes care of freeing the sqlite3_index_info structure after
105213 ** everybody has finished with it.
105214 */
105215 static void bestVirtualIndex(WhereBestIdx *p){
105216   Parse *pParse = p->pParse;      /* The parsing context */
105217   WhereClause *pWC = p->pWC;      /* The WHERE clause */
105218   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
105219   Table *pTab = pSrc->pTab;
105220   sqlite3_index_info *pIdxInfo;
105221   struct sqlite3_index_constraint *pIdxCons;
105222   struct sqlite3_index_constraint_usage *pUsage;
105223   WhereTerm *pTerm;
105224   int i, j, k;
105225   int nOrderBy;
105226   int sortOrder;                  /* Sort order for IN clauses */
105227   int bAllowIN;                   /* Allow IN optimizations */
105228   double rCost;
105229 
105230   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
105231   ** malloc in allocateIndexInfo() fails and this function returns leaving
105232   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
105233   */
105234   memset(&p->cost, 0, sizeof(p->cost));
105235   p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
105236 
105237   /* If the sqlite3_index_info structure has not been previously
105238   ** allocated and initialized, then allocate and initialize it now.
105239   */
105240   pIdxInfo = *p->ppIdxInfo;
105241   if( pIdxInfo==0 ){
105242     *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
105243   }
105244   if( pIdxInfo==0 ){
105245     return;
105246   }
105247 
105248   /* At this point, the sqlite3_index_info structure that pIdxInfo points
105249   ** to will have been initialized, either during the current invocation or
105250   ** during some prior invocation.  Now we just have to customize the
105251   ** details of pIdxInfo for the current invocation and pass it to
105252   ** xBestIndex.
105253   */
105254 
105255   /* The module name must be defined. Also, by this point there must
105256   ** be a pointer to an sqlite3_vtab structure. Otherwise
105257   ** sqlite3ViewGetColumnNames() would have picked up the error.
105258   */
105259   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
105260   assert( sqlite3GetVTable(pParse->db, pTab) );
105261 
105262   /* Try once or twice.  On the first attempt, allow IN optimizations.
105263   ** If an IN optimization is accepted by the virtual table xBestIndex
105264   ** method, but the  pInfo->aConstrainUsage.omit flag is not set, then
105265   ** the query will not work because it might allow duplicate rows in
105266   ** output.  In that case, run the xBestIndex method a second time
105267   ** without the IN constraints.  Usually this loop only runs once.
105268   ** The loop will exit using a "break" statement.
105269   */
105270   for(bAllowIN=1; 1; bAllowIN--){
105271     assert( bAllowIN==0 || bAllowIN==1 );
105272 
105273     /* Set the aConstraint[].usable fields and initialize all
105274     ** output variables to zero.
105275     **
105276     ** aConstraint[].usable is true for constraints where the right-hand
105277     ** side contains only references to tables to the left of the current
105278     ** table.  In other words, if the constraint is of the form:
105279     **
105280     **           column = expr
105281     **
105282     ** and we are evaluating a join, then the constraint on column is
105283     ** only valid if all tables referenced in expr occur to the left
105284     ** of the table containing column.
105285     **
105286     ** The aConstraints[] array contains entries for all constraints
105287     ** on the current table.  That way we only have to compute it once
105288     ** even though we might try to pick the best index multiple times.
105289     ** For each attempt at picking an index, the order of tables in the
105290     ** join might be different so we have to recompute the usable flag
105291     ** each time.
105292     */
105293     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
105294     pUsage = pIdxInfo->aConstraintUsage;
105295     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
105296       j = pIdxCons->iTermOffset;
105297       pTerm = &pWC->a[j];
105298       if( (pTerm->prereqRight&p->notReady)==0
105299        && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
105300       ){
105301         pIdxCons->usable = 1;
105302       }else{
105303         pIdxCons->usable = 0;
105304       }
105305     }
105306     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
105307     if( pIdxInfo->needToFreeIdxStr ){
105308       sqlite3_free(pIdxInfo->idxStr);
105309     }
105310     pIdxInfo->idxStr = 0;
105311     pIdxInfo->idxNum = 0;
105312     pIdxInfo->needToFreeIdxStr = 0;
105313     pIdxInfo->orderByConsumed = 0;
105314     /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
105315     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
105316     nOrderBy = pIdxInfo->nOrderBy;
105317     if( !p->pOrderBy ){
105318       pIdxInfo->nOrderBy = 0;
105319     }
105320 
105321     if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
105322       return;
105323     }
105324 
105325     sortOrder = SQLITE_SO_ASC;
105326     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
105327     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
105328       if( pUsage[i].argvIndex>0 ){
105329         j = pIdxCons->iTermOffset;
105330         pTerm = &pWC->a[j];
105331         p->cost.used |= pTerm->prereqRight;
105332         if( (pTerm->eOperator & WO_IN)!=0 ){
105333           if( pUsage[i].omit==0 ){
105334             /* Do not attempt to use an IN constraint if the virtual table
105335             ** says that the equivalent EQ constraint cannot be safely omitted.
105336             ** If we do attempt to use such a constraint, some rows might be
105337             ** repeated in the output. */
105338             break;
105339           }
105340           for(k=0; k<pIdxInfo->nOrderBy; k++){
105341             if( pIdxInfo->aOrderBy[k].iColumn==pIdxCons->iColumn ){
105342               sortOrder = pIdxInfo->aOrderBy[k].desc;
105343               break;
105344             }
105345           }
105346         }
105347       }
105348     }
105349     if( i>=pIdxInfo->nConstraint ) break;
105350   }
105351 
105352   /* If there is an ORDER BY clause, and the selected virtual table index
105353   ** does not satisfy it, increase the cost of the scan accordingly. This
105354   ** matches the processing for non-virtual tables in bestBtreeIndex().
105355   */
105356   rCost = pIdxInfo->estimatedCost;
105357   if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
105358     rCost += estLog(rCost)*rCost;
105359   }
105360 
105361   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
105362   ** inital value of lowestCost in this loop. If it is, then the
105363   ** (cost<lowestCost) test below will never be true.
105364   **
105365   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
105366   ** is defined.
105367   */
105368   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
105369     p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
105370   }else{
105371     p->cost.rCost = rCost;
105372   }
105373   p->cost.plan.u.pVtabIdx = pIdxInfo;
105374   if( pIdxInfo->orderByConsumed ){
105375     assert( sortOrder==0 || sortOrder==1 );
105376     p->cost.plan.wsFlags |= WHERE_ORDERED + sortOrder*WHERE_REVERSE;
105377     p->cost.plan.nOBSat = nOrderBy;
105378   }else{
105379     p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
105380   }
105381   p->cost.plan.nEq = 0;
105382   pIdxInfo->nOrderBy = nOrderBy;
105383 
105384   /* Try to find a more efficient access pattern by using multiple indexes
105385   ** to optimize an OR expression within the WHERE clause.
105386   */
105387   bestOrClauseIndex(p);
105388 }
105389 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105390 
105391 #ifdef SQLITE_ENABLE_STAT3
105392 /*
105393 ** Estimate the location of a particular key among all keys in an
105394 ** index.  Store the results in aStat as follows:
105395 **
105396 **    aStat[0]      Est. number of rows less than pVal
105397 **    aStat[1]      Est. number of rows equal to pVal
105398 **
105399 ** Return SQLITE_OK on success.
105400 */
105401 static int whereKeyStats(
105402   Parse *pParse,              /* Database connection */
105403   Index *pIdx,                /* Index to consider domain of */
105404   sqlite3_value *pVal,        /* Value to consider */
105405   int roundUp,                /* Round up if true.  Round down if false */
105406   tRowcnt *aStat              /* OUT: stats written here */
105407 ){
105408   tRowcnt n;
105409   IndexSample *aSample;
105410   int i, eType;
105411   int isEq = 0;
105412   i64 v;
105413   double r, rS;
105414 
105415   assert( roundUp==0 || roundUp==1 );
105416   assert( pIdx->nSample>0 );
105417   if( pVal==0 ) return SQLITE_ERROR;
105418   n = pIdx->aiRowEst[0];
105419   aSample = pIdx->aSample;
105420   eType = sqlite3_value_type(pVal);
105421 
105422   if( eType==SQLITE_INTEGER ){
105423     v = sqlite3_value_int64(pVal);
105424     r = (i64)v;
105425     for(i=0; i<pIdx->nSample; i++){
105426       if( aSample[i].eType==SQLITE_NULL ) continue;
105427       if( aSample[i].eType>=SQLITE_TEXT ) break;
105428       if( aSample[i].eType==SQLITE_INTEGER ){
105429         if( aSample[i].u.i>=v ){
105430           isEq = aSample[i].u.i==v;
105431           break;
105432         }
105433       }else{
105434         assert( aSample[i].eType==SQLITE_FLOAT );
105435         if( aSample[i].u.r>=r ){
105436           isEq = aSample[i].u.r==r;
105437           break;
105438         }
105439       }
105440     }
105441   }else if( eType==SQLITE_FLOAT ){
105442     r = sqlite3_value_double(pVal);
105443     for(i=0; i<pIdx->nSample; i++){
105444       if( aSample[i].eType==SQLITE_NULL ) continue;
105445       if( aSample[i].eType>=SQLITE_TEXT ) break;
105446       if( aSample[i].eType==SQLITE_FLOAT ){
105447         rS = aSample[i].u.r;
105448       }else{
105449         rS = aSample[i].u.i;
105450       }
105451       if( rS>=r ){
105452         isEq = rS==r;
105453         break;
105454       }
105455     }
105456   }else if( eType==SQLITE_NULL ){
105457     i = 0;
105458     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
105459   }else{
105460     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
105461     for(i=0; i<pIdx->nSample; i++){
105462       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
105463         break;
105464       }
105465     }
105466     if( i<pIdx->nSample ){
105467       sqlite3 *db = pParse->db;
105468       CollSeq *pColl;
105469       const u8 *z;
105470       if( eType==SQLITE_BLOB ){
105471         z = (const u8 *)sqlite3_value_blob(pVal);
105472         pColl = db->pDfltColl;
105473         assert( pColl->enc==SQLITE_UTF8 );
105474       }else{
105475         pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
105476         if( pColl==0 ){
105477           return SQLITE_ERROR;
105478         }
105479         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
105480         if( !z ){
105481           return SQLITE_NOMEM;
105482         }
105483         assert( z && pColl && pColl->xCmp );
105484       }
105485       n = sqlite3ValueBytes(pVal, pColl->enc);
105486 
105487       for(; i<pIdx->nSample; i++){
105488         int c;
105489         int eSampletype = aSample[i].eType;
105490         if( eSampletype<eType ) continue;
105491         if( eSampletype!=eType ) break;
105492 #ifndef SQLITE_OMIT_UTF16
105493         if( pColl->enc!=SQLITE_UTF8 ){
105494           int nSample;
105495           char *zSample = sqlite3Utf8to16(
105496               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
105497           );
105498           if( !zSample ){
105499             assert( db->mallocFailed );
105500             return SQLITE_NOMEM;
105501           }
105502           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
105503           sqlite3DbFree(db, zSample);
105504         }else
105505 #endif
105506         {
105507           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
105508         }
105509         if( c>=0 ){
105510           if( c==0 ) isEq = 1;
105511           break;
105512         }
105513       }
105514     }
105515   }
105516 
105517   /* At this point, aSample[i] is the first sample that is greater than
105518   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
105519   ** than pVal.  If aSample[i]==pVal, then isEq==1.
105520   */
105521   if( isEq ){
105522     assert( i<pIdx->nSample );
105523     aStat[0] = aSample[i].nLt;
105524     aStat[1] = aSample[i].nEq;
105525   }else{
105526     tRowcnt iLower, iUpper, iGap;
105527     if( i==0 ){
105528       iLower = 0;
105529       iUpper = aSample[0].nLt;
105530     }else{
105531       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
105532       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
105533     }
105534     aStat[1] = pIdx->avgEq;
105535     if( iLower>=iUpper ){
105536       iGap = 0;
105537     }else{
105538       iGap = iUpper - iLower;
105539     }
105540     if( roundUp ){
105541       iGap = (iGap*2)/3;
105542     }else{
105543       iGap = iGap/3;
105544     }
105545     aStat[0] = iLower + iGap;
105546   }
105547   return SQLITE_OK;
105548 }
105549 #endif /* SQLITE_ENABLE_STAT3 */
105550 
105551 /*
105552 ** If expression pExpr represents a literal value, set *pp to point to
105553 ** an sqlite3_value structure containing the same value, with affinity
105554 ** aff applied to it, before returning. It is the responsibility of the
105555 ** caller to eventually release this structure by passing it to
105556 ** sqlite3ValueFree().
105557 **
105558 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
105559 ** is an SQL variable that currently has a non-NULL value bound to it,
105560 ** create an sqlite3_value structure containing this value, again with
105561 ** affinity aff applied to it, instead.
105562 **
105563 ** If neither of the above apply, set *pp to NULL.
105564 **
105565 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
105566 */
105567 #ifdef SQLITE_ENABLE_STAT3
105568 static int valueFromExpr(
105569   Parse *pParse,
105570   Expr *pExpr,
105571   u8 aff,
105572   sqlite3_value **pp
105573 ){
105574   if( pExpr->op==TK_VARIABLE
105575    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
105576   ){
105577     int iVar = pExpr->iColumn;
105578     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
105579     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
105580     return SQLITE_OK;
105581   }
105582   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
105583 }
105584 #endif
105585 
105586 /*
105587 ** This function is used to estimate the number of rows that will be visited
105588 ** by scanning an index for a range of values. The range may have an upper
105589 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
105590 ** and lower bounds are represented by pLower and pUpper respectively. For
105591 ** example, assuming that index p is on t1(a):
105592 **
105593 **   ... FROM t1 WHERE a > ? AND a < ? ...
105594 **                    |_____|   |_____|
105595 **                       |         |
105596 **                     pLower    pUpper
105597 **
105598 ** If either of the upper or lower bound is not present, then NULL is passed in
105599 ** place of the corresponding WhereTerm.
105600 **
105601 ** The nEq parameter is passed the index of the index column subject to the
105602 ** range constraint. Or, equivalently, the number of equality constraints
105603 ** optimized by the proposed index scan. For example, assuming index p is
105604 ** on t1(a, b), and the SQL query is:
105605 **
105606 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
105607 **
105608 ** then nEq should be passed the value 1 (as the range restricted column,
105609 ** b, is the second left-most column of the index). Or, if the query is:
105610 **
105611 **   ... FROM t1 WHERE a > ? AND a < ? ...
105612 **
105613 ** then nEq should be passed 0.
105614 **
105615 ** The returned value is an integer divisor to reduce the estimated
105616 ** search space.  A return value of 1 means that range constraints are
105617 ** no help at all.  A return value of 2 means range constraints are
105618 ** expected to reduce the search space by half.  And so forth...
105619 **
105620 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
105621 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
105622 ** results in a return of 4 and a range constraint (x>? AND x<?) results
105623 ** in a return of 16.
105624 */
105625 static int whereRangeScanEst(
105626   Parse *pParse,       /* Parsing & code generating context */
105627   Index *p,            /* The index containing the range-compared column; "x" */
105628   int nEq,             /* index into p->aCol[] of the range-compared column */
105629   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
105630   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
105631   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
105632 ){
105633   int rc = SQLITE_OK;
105634 
105635 #ifdef SQLITE_ENABLE_STAT3
105636 
105637   if( nEq==0 && p->nSample ){
105638     sqlite3_value *pRangeVal;
105639     tRowcnt iLower = 0;
105640     tRowcnt iUpper = p->aiRowEst[0];
105641     tRowcnt a[2];
105642     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105643 
105644     if( pLower ){
105645       Expr *pExpr = pLower->pExpr->pRight;
105646       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105647       assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
105648       if( rc==SQLITE_OK
105649        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
105650       ){
105651         iLower = a[0];
105652         if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
105653       }
105654       sqlite3ValueFree(pRangeVal);
105655     }
105656     if( rc==SQLITE_OK && pUpper ){
105657       Expr *pExpr = pUpper->pExpr->pRight;
105658       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105659       assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
105660       if( rc==SQLITE_OK
105661        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
105662       ){
105663         iUpper = a[0];
105664         if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
105665       }
105666       sqlite3ValueFree(pRangeVal);
105667     }
105668     if( rc==SQLITE_OK ){
105669       if( iUpper<=iLower ){
105670         *pRangeDiv = (double)p->aiRowEst[0];
105671       }else{
105672         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
105673       }
105674       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
105675                   (u32)iLower, (u32)iUpper, *pRangeDiv));
105676       return SQLITE_OK;
105677     }
105678   }
105679 #else
105680   UNUSED_PARAMETER(pParse);
105681   UNUSED_PARAMETER(p);
105682   UNUSED_PARAMETER(nEq);
105683 #endif
105684   assert( pLower || pUpper );
105685   *pRangeDiv = (double)1;
105686   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
105687   if( pUpper ) *pRangeDiv *= (double)4;
105688   return rc;
105689 }
105690 
105691 #ifdef SQLITE_ENABLE_STAT3
105692 /*
105693 ** Estimate the number of rows that will be returned based on
105694 ** an equality constraint x=VALUE and where that VALUE occurs in
105695 ** the histogram data.  This only works when x is the left-most
105696 ** column of an index and sqlite_stat3 histogram data is available
105697 ** for that index.  When pExpr==NULL that means the constraint is
105698 ** "x IS NULL" instead of "x=VALUE".
105699 **
105700 ** Write the estimated row count into *pnRow and return SQLITE_OK.
105701 ** If unable to make an estimate, leave *pnRow unchanged and return
105702 ** non-zero.
105703 **
105704 ** This routine can fail if it is unable to load a collating sequence
105705 ** required for string comparison, or if unable to allocate memory
105706 ** for a UTF conversion required for comparison.  The error is stored
105707 ** in the pParse structure.
105708 */
105709 static int whereEqualScanEst(
105710   Parse *pParse,       /* Parsing & code generating context */
105711   Index *p,            /* The index whose left-most column is pTerm */
105712   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
105713   double *pnRow        /* Write the revised row estimate here */
105714 ){
105715   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
105716   u8 aff;                   /* Column affinity */
105717   int rc;                   /* Subfunction return code */
105718   tRowcnt a[2];             /* Statistics */
105719 
105720   assert( p->aSample!=0 );
105721   assert( p->nSample>0 );
105722   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105723   if( pExpr ){
105724     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
105725     if( rc ) goto whereEqualScanEst_cancel;
105726   }else{
105727     pRhs = sqlite3ValueNew(pParse->db);
105728   }
105729   if( pRhs==0 ) return SQLITE_NOTFOUND;
105730   rc = whereKeyStats(pParse, p, pRhs, 0, a);
105731   if( rc==SQLITE_OK ){
105732     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
105733     *pnRow = a[1];
105734   }
105735 whereEqualScanEst_cancel:
105736   sqlite3ValueFree(pRhs);
105737   return rc;
105738 }
105739 #endif /* defined(SQLITE_ENABLE_STAT3) */
105740 
105741 #ifdef SQLITE_ENABLE_STAT3
105742 /*
105743 ** Estimate the number of rows that will be returned based on
105744 ** an IN constraint where the right-hand side of the IN operator
105745 ** is a list of values.  Example:
105746 **
105747 **        WHERE x IN (1,2,3,4)
105748 **
105749 ** Write the estimated row count into *pnRow and return SQLITE_OK.
105750 ** If unable to make an estimate, leave *pnRow unchanged and return
105751 ** non-zero.
105752 **
105753 ** This routine can fail if it is unable to load a collating sequence
105754 ** required for string comparison, or if unable to allocate memory
105755 ** for a UTF conversion required for comparison.  The error is stored
105756 ** in the pParse structure.
105757 */
105758 static int whereInScanEst(
105759   Parse *pParse,       /* Parsing & code generating context */
105760   Index *p,            /* The index whose left-most column is pTerm */
105761   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
105762   double *pnRow        /* Write the revised row estimate here */
105763 ){
105764   int rc = SQLITE_OK;         /* Subfunction return code */
105765   double nEst;                /* Number of rows for a single term */
105766   double nRowEst = (double)0; /* New estimate of the number of rows */
105767   int i;                      /* Loop counter */
105768 
105769   assert( p->aSample!=0 );
105770   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
105771     nEst = p->aiRowEst[0];
105772     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
105773     nRowEst += nEst;
105774   }
105775   if( rc==SQLITE_OK ){
105776     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
105777     *pnRow = nRowEst;
105778     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
105779   }
105780   return rc;
105781 }
105782 #endif /* defined(SQLITE_ENABLE_STAT3) */
105783 
105784 /*
105785 ** Check to see if column iCol of the table with cursor iTab will appear
105786 ** in sorted order according to the current query plan.
105787 **
105788 ** Return values:
105789 **
105790 **    0   iCol is not ordered
105791 **    1   iCol has only a single value
105792 **    2   iCol is in ASC order
105793 **    3   iCol is in DESC order
105794 */
105795 static int isOrderedColumn(
105796   WhereBestIdx *p,
105797   int iTab,
105798   int iCol
105799 ){
105800   int i, j;
105801   WhereLevel *pLevel = &p->aLevel[p->i-1];
105802   Index *pIdx;
105803   u8 sortOrder;
105804   for(i=p->i-1; i>=0; i--, pLevel--){
105805     if( pLevel->iTabCur!=iTab ) continue;
105806     if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
105807       return 1;
105808     }
105809     assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
105810     if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
105811       if( iCol<0 ){
105812         sortOrder = 0;
105813         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105814       }else{
105815         int n = pIdx->nColumn;
105816         for(j=0; j<n; j++){
105817           if( iCol==pIdx->aiColumn[j] ) break;
105818         }
105819         if( j>=n ) return 0;
105820         sortOrder = pIdx->aSortOrder[j];
105821         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105822       }
105823     }else{
105824       if( iCol!=(-1) ) return 0;
105825       sortOrder = 0;
105826       testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
105827     }
105828     if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
105829       assert( sortOrder==0 || sortOrder==1 );
105830       testcase( sortOrder==1 );
105831       sortOrder = 1 - sortOrder;
105832     }
105833     return sortOrder+2;
105834   }
105835   return 0;
105836 }
105837 
105838 /*
105839 ** This routine decides if pIdx can be used to satisfy the ORDER BY
105840 ** clause, either in whole or in part.  The return value is the
105841 ** cumulative number of terms in the ORDER BY clause that are satisfied
105842 ** by the index pIdx and other indices in outer loops.
105843 **
105844 ** The table being queried has a cursor number of "base".  pIdx is the
105845 ** index that is postulated for use to access the table.
105846 **
105847 ** The *pbRev value is set to 0 order 1 depending on whether or not
105848 ** pIdx should be run in the forward order or in reverse order.
105849 */
105850 static int isSortingIndex(
105851   WhereBestIdx *p,    /* Best index search context */
105852   Index *pIdx,        /* The index we are testing */
105853   int base,           /* Cursor number for the table to be sorted */
105854   int *pbRev,         /* Set to 1 for reverse-order scan of pIdx */
105855   int *pbObUnique     /* ORDER BY column values will different in every row */
105856 ){
105857   int i;                        /* Number of pIdx terms used */
105858   int j;                        /* Number of ORDER BY terms satisfied */
105859   int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
105860   int nTerm;                    /* Number of ORDER BY terms */
105861   struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
105862   Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
105863   ExprList *pOrderBy;           /* The ORDER BY clause */
105864   Parse *pParse = p->pParse;    /* Parser context */
105865   sqlite3 *db = pParse->db;     /* Database connection */
105866   int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
105867   int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
105868   int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
105869   int outerObUnique;            /* Outer loops generate different values in
105870                                 ** every row for the ORDER BY columns */
105871 
105872   if( p->i==0 ){
105873     nPriorSat = 0;
105874     outerObUnique = 1;
105875   }else{
105876     u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
105877     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
105878     if( (wsFlags & WHERE_ORDERED)==0 ){
105879       /* This loop cannot be ordered unless the next outer loop is
105880       ** also ordered */
105881       return nPriorSat;
105882     }
105883     if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
105884       /* Only look at the outer-most loop if the OrderByIdxJoin
105885       ** optimization is disabled */
105886       return nPriorSat;
105887     }
105888     testcase( wsFlags & WHERE_OB_UNIQUE );
105889     testcase( wsFlags & WHERE_ALL_UNIQUE );
105890     outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
105891   }
105892   pOrderBy = p->pOrderBy;
105893   assert( pOrderBy!=0 );
105894   if( pIdx->bUnordered ){
105895     /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
105896     ** be used for sorting */
105897     return nPriorSat;
105898   }
105899   nTerm = pOrderBy->nExpr;
105900   uniqueNotNull = pIdx->onError!=OE_None;
105901   assert( nTerm>0 );
105902 
105903   /* Argument pIdx must either point to a 'real' named index structure,
105904   ** or an index structure allocated on the stack by bestBtreeIndex() to
105905   ** represent the rowid index that is part of every table.  */
105906   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
105907 
105908   /* Match terms of the ORDER BY clause against columns of
105909   ** the index.
105910   **
105911   ** Note that indices have pIdx->nColumn regular columns plus
105912   ** one additional column containing the rowid.  The rowid column
105913   ** of the index is also allowed to match against the ORDER BY
105914   ** clause.
105915   */
105916   j = nPriorSat;
105917   for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
105918     Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
105919     CollSeq *pColl;         /* The collating sequence of pOBExpr */
105920     int termSortOrder;      /* Sort order for this term */
105921     int iColumn;            /* The i-th column of the index.  -1 for rowid */
105922     int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
105923     int isEq;               /* Subject to an == or IS NULL constraint */
105924     int isMatch;            /* ORDER BY term matches the index term */
105925     const char *zColl;      /* Name of collating sequence for i-th index term */
105926     WhereTerm *pConstraint; /* A constraint in the WHERE clause */
105927 
105928     /* If the next term of the ORDER BY clause refers to anything other than
105929     ** a column in the "base" table, then this index will not be of any
105930     ** further use in handling the ORDER BY. */
105931     pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
105932     if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
105933       break;
105934     }
105935 
105936     /* Find column number and collating sequence for the next entry
105937     ** in the index */
105938     if( pIdx->zName && i<pIdx->nColumn ){
105939       iColumn = pIdx->aiColumn[i];
105940       if( iColumn==pIdx->pTable->iPKey ){
105941         iColumn = -1;
105942       }
105943       iSortOrder = pIdx->aSortOrder[i];
105944       zColl = pIdx->azColl[i];
105945       assert( zColl!=0 );
105946     }else{
105947       iColumn = -1;
105948       iSortOrder = 0;
105949       zColl = 0;
105950     }
105951 
105952     /* Check to see if the column number and collating sequence of the
105953     ** index match the column number and collating sequence of the ORDER BY
105954     ** clause entry.  Set isMatch to 1 if they both match. */
105955     if( pOBExpr->iColumn==iColumn ){
105956       if( zColl ){
105957         pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
105958         if( !pColl ) pColl = db->pDfltColl;
105959         isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
105960       }else{
105961         isMatch = 1;
105962       }
105963     }else{
105964       isMatch = 0;
105965     }
105966 
105967     /* termSortOrder is 0 or 1 for whether or not the access loop should
105968     ** run forward or backwards (respectively) in order to satisfy this
105969     ** term of the ORDER BY clause. */
105970     assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
105971     assert( iSortOrder==0 || iSortOrder==1 );
105972     termSortOrder = iSortOrder ^ pOBItem->sortOrder;
105973 
105974     /* If X is the column in the index and ORDER BY clause, check to see
105975     ** if there are any X= or X IS NULL constraints in the WHERE clause. */
105976     pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
105977                            WO_EQ|WO_ISNULL|WO_IN, pIdx);
105978     if( pConstraint==0 ){
105979       isEq = 0;
105980     }else if( (pConstraint->eOperator & WO_IN)!=0 ){
105981       isEq = 0;
105982     }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
105983       uniqueNotNull = 0;
105984       isEq = 1;  /* "X IS NULL" means X has only a single value */
105985     }else if( pConstraint->prereqRight==0 ){
105986       isEq = 1;  /* Constraint "X=constant" means X has only a single value */
105987     }else{
105988       Expr *pRight = pConstraint->pExpr->pRight;
105989       if( pRight->op==TK_COLUMN ){
105990         WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
105991                     pRight->iTable, pRight->iColumn));
105992         isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
105993         WHERETRACE((" -> isEq=%d\n", isEq));
105994 
105995         /* If the constraint is of the form X=Y where Y is an ordered value
105996         ** in an outer loop, then make sure the sort order of Y matches the
105997         ** sort order required for X. */
105998         if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
105999           testcase( isEq==2 );
106000           testcase( isEq==3 );
106001           break;
106002         }
106003       }else{
106004         isEq = 0;  /* "X=expr" places no ordering constraints on X */
106005       }
106006     }
106007     if( !isMatch ){
106008       if( isEq==0 ){
106009         break;
106010       }else{
106011         continue;
106012       }
106013     }else if( isEq!=1 ){
106014       if( sortOrder==2 ){
106015         sortOrder = termSortOrder;
106016       }else if( termSortOrder!=sortOrder ){
106017         break;
106018       }
106019     }
106020     j++;
106021     pOBItem++;
106022     if( iColumn<0 ){
106023       seenRowid = 1;
106024       break;
106025     }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
106026       testcase( isEq==0 );
106027       testcase( isEq==2 );
106028       testcase( isEq==3 );
106029       uniqueNotNull = 0;
106030     }
106031   }
106032   if( seenRowid ){
106033     uniqueNotNull = 1;
106034   }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
106035     uniqueNotNull = 0;
106036   }
106037 
106038   /* If we have not found at least one ORDER BY term that matches the
106039   ** index, then show no progress. */
106040   if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
106041 
106042   /* Either the outer queries must generate rows where there are no two
106043   ** rows with the same values in all ORDER BY columns, or else this
106044   ** loop must generate just a single row of output.  Example:  Suppose
106045   ** the outer loops generate A=1 and A=1, and this loop generates B=3
106046   ** and B=4.  Then without the following test, ORDER BY A,B would
106047   ** generate the wrong order output: 1,3 1,4 1,3 1,4
106048   */
106049   if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
106050   *pbObUnique = uniqueNotNull;
106051 
106052   /* Return the necessary scan order back to the caller */
106053   *pbRev = sortOrder & 1;
106054 
106055   /* If there was an "ORDER BY rowid" term that matched, or it is only
106056   ** possible for a single row from this table to match, then skip over
106057   ** any additional ORDER BY terms dealing with this table.
106058   */
106059   if( uniqueNotNull ){
106060     /* Advance j over additional ORDER BY terms associated with base */
106061     WhereMaskSet *pMS = p->pWC->pMaskSet;
106062     Bitmask m = ~getMask(pMS, base);
106063     while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
106064       j++;
106065     }
106066   }
106067   return j;
106068 }
106069 
106070 /*
106071 ** Find the best query plan for accessing a particular table.  Write the
106072 ** best query plan and its cost into the p->cost.
106073 **
106074 ** The lowest cost plan wins.  The cost is an estimate of the amount of
106075 ** CPU and disk I/O needed to process the requested result.
106076 ** Factors that influence cost include:
106077 **
106078 **    *  The estimated number of rows that will be retrieved.  (The
106079 **       fewer the better.)
106080 **
106081 **    *  Whether or not sorting must occur.
106082 **
106083 **    *  Whether or not there must be separate lookups in the
106084 **       index and in the main table.
106085 **
106086 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
106087 ** the SQL statement, then this function only considers plans using the
106088 ** named index. If no such plan is found, then the returned cost is
106089 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
106090 ** then the cost is calculated in the usual way.
106091 **
106092 ** If a NOT INDEXED clause was attached to the table
106093 ** in the SELECT statement, then no indexes are considered. However, the
106094 ** selected plan may still take advantage of the built-in rowid primary key
106095 ** index.
106096 */
106097 static void bestBtreeIndex(WhereBestIdx *p){
106098   Parse *pParse = p->pParse;  /* The parsing context */
106099   WhereClause *pWC = p->pWC;  /* The WHERE clause */
106100   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106101   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
106102   Index *pProbe;              /* An index we are evaluating */
106103   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
106104   int eqTermMask;             /* Current mask of valid equality operators */
106105   int idxEqTermMask;          /* Index mask of valid equality operators */
106106   Index sPk;                  /* A fake index object for the primary key */
106107   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
106108   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
106109   int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
106110   int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
106111   int nOrderBy;               /* Number of ORDER BY terms */
106112   char bSortInit;             /* Initializer for bSort in inner loop */
106113   char bDistInit;             /* Initializer for bDist in inner loop */
106114 
106115 
106116   /* Initialize the cost to a worst-case value */
106117   memset(&p->cost, 0, sizeof(p->cost));
106118   p->cost.rCost = SQLITE_BIG_DBL;
106119 
106120   /* If the pSrc table is the right table of a LEFT JOIN then we may not
106121   ** use an index to satisfy IS NULL constraints on that table.  This is
106122   ** because columns might end up being NULL if the table does not match -
106123   ** a circumstance which the index cannot help us discover.  Ticket #2177.
106124   */
106125   if( pSrc->jointype & JT_LEFT ){
106126     idxEqTermMask = WO_EQ|WO_IN;
106127   }else{
106128     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
106129   }
106130 
106131   if( pSrc->pIndex ){
106132     /* An INDEXED BY clause specifies a particular index to use */
106133     pIdx = pProbe = pSrc->pIndex;
106134     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
106135     eqTermMask = idxEqTermMask;
106136   }else{
106137     /* There is no INDEXED BY clause.  Create a fake Index object in local
106138     ** variable sPk to represent the rowid primary key index.  Make this
106139     ** fake index the first in a chain of Index objects with all of the real
106140     ** indices to follow */
106141     Index *pFirst;                  /* First of real indices on the table */
106142     memset(&sPk, 0, sizeof(Index));
106143     sPk.nColumn = 1;
106144     sPk.aiColumn = &aiColumnPk;
106145     sPk.aiRowEst = aiRowEstPk;
106146     sPk.onError = OE_Replace;
106147     sPk.pTable = pSrc->pTab;
106148     aiRowEstPk[0] = pSrc->pTab->nRowEst;
106149     aiRowEstPk[1] = 1;
106150     pFirst = pSrc->pTab->pIndex;
106151     if( pSrc->notIndexed==0 ){
106152       /* The real indices of the table are only considered if the
106153       ** NOT INDEXED qualifier is omitted from the FROM clause */
106154       sPk.pNext = pFirst;
106155     }
106156     pProbe = &sPk;
106157     wsFlagMask = ~(
106158         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
106159     );
106160     eqTermMask = WO_EQ|WO_IN;
106161     pIdx = 0;
106162   }
106163 
106164   nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
106165   if( p->i ){
106166     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
106167     bSortInit = nPriorSat<nOrderBy;
106168     bDistInit = 0;
106169   }else{
106170     nPriorSat = 0;
106171     bSortInit = nOrderBy>0;
106172     bDistInit = p->pDistinct!=0;
106173   }
106174 
106175   /* Loop over all indices looking for the best one to use
106176   */
106177   for(; pProbe; pIdx=pProbe=pProbe->pNext){
106178     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
106179     WhereCost pc;               /* Cost of using pProbe */
106180     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
106181 
106182     /* The following variables are populated based on the properties of
106183     ** index being evaluated. They are then used to determine the expected
106184     ** cost and number of rows returned.
106185     **
106186     **  pc.plan.nEq:
106187     **    Number of equality terms that can be implemented using the index.
106188     **    In other words, the number of initial fields in the index that
106189     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
106190     **
106191     **  nInMul:
106192     **    The "in-multiplier". This is an estimate of how many seek operations
106193     **    SQLite must perform on the index in question. For example, if the
106194     **    WHERE clause is:
106195     **
106196     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
106197     **
106198     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
106199     **    set to 9. Given the same schema and either of the following WHERE
106200     **    clauses:
106201     **
106202     **      WHERE a =  1
106203     **      WHERE a >= 2
106204     **
106205     **    nInMul is set to 1.
106206     **
106207     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
106208     **    the sub-select is assumed to return 25 rows for the purposes of
106209     **    determining nInMul.
106210     **
106211     **  bInEst:
106212     **    Set to true if there was at least one "x IN (SELECT ...)" term used
106213     **    in determining the value of nInMul.  Note that the RHS of the
106214     **    IN operator must be a SELECT, not a value list, for this variable
106215     **    to be true.
106216     **
106217     **  rangeDiv:
106218     **    An estimate of a divisor by which to reduce the search space due
106219     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
106220     **    data, a single inequality reduces the search space to 1/4rd its
106221     **    original size (rangeDiv==4).  Two inequalities reduce the search
106222     **    space to 1/16th of its original size (rangeDiv==16).
106223     **
106224     **  bSort:
106225     **    Boolean. True if there is an ORDER BY clause that will require an
106226     **    external sort (i.e. scanning the index being evaluated will not
106227     **    correctly order records).
106228     **
106229     **  bDist:
106230     **    Boolean. True if there is a DISTINCT clause that will require an
106231     **    external btree.
106232     **
106233     **  bLookup:
106234     **    Boolean. True if a table lookup is required for each index entry
106235     **    visited.  In other words, true if this is not a covering index.
106236     **    This is always false for the rowid primary key index of a table.
106237     **    For other indexes, it is true unless all the columns of the table
106238     **    used by the SELECT statement are present in the index (such an
106239     **    index is sometimes described as a covering index).
106240     **    For example, given the index on (a, b), the second of the following
106241     **    two queries requires table b-tree lookups in order to find the value
106242     **    of column c, but the first does not because columns a and b are
106243     **    both available in the index.
106244     **
106245     **             SELECT a, b    FROM tbl WHERE a = 1;
106246     **             SELECT a, b, c FROM tbl WHERE a = 1;
106247     */
106248     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
106249     int nInMul = 1;               /* Number of distinct equalities to lookup */
106250     double rangeDiv = (double)1;  /* Estimated reduction in search space */
106251     int nBound = 0;               /* Number of range constraints seen */
106252     char bSort = bSortInit;       /* True if external sort required */
106253     char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
106254     char bLookup = 0;             /* True if not a covering index */
106255     WhereTerm *pTerm;             /* A single term of the WHERE clause */
106256 #ifdef SQLITE_ENABLE_STAT3
106257     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
106258 #endif
106259 
106260     WHERETRACE((
106261       "   %s(%s):\n",
106262       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
106263     ));
106264     memset(&pc, 0, sizeof(pc));
106265     pc.plan.nOBSat = nPriorSat;
106266 
106267     /* Determine the values of pc.plan.nEq and nInMul */
106268     for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
106269       int j = pProbe->aiColumn[pc.plan.nEq];
106270       pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
106271       if( pTerm==0 ) break;
106272       pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
106273       testcase( pTerm->pWC!=pWC );
106274       if( pTerm->eOperator & WO_IN ){
106275         Expr *pExpr = pTerm->pExpr;
106276         pc.plan.wsFlags |= WHERE_COLUMN_IN;
106277         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
106278           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
106279           nInMul *= 25;
106280           bInEst = 1;
106281         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
106282           /* "x IN (value, value, ...)" */
106283           nInMul *= pExpr->x.pList->nExpr;
106284         }
106285       }else if( pTerm->eOperator & WO_ISNULL ){
106286         pc.plan.wsFlags |= WHERE_COLUMN_NULL;
106287       }
106288 #ifdef SQLITE_ENABLE_STAT3
106289       if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
106290 #endif
106291       pc.used |= pTerm->prereqRight;
106292     }
106293 
106294     /* If the index being considered is UNIQUE, and there is an equality
106295     ** constraint for all columns in the index, then this search will find
106296     ** at most a single row. In this case set the WHERE_UNIQUE flag to
106297     ** indicate this to the caller.
106298     **
106299     ** Otherwise, if the search may find more than one row, test to see if
106300     ** there is a range constraint on indexed column (pc.plan.nEq+1) that
106301     ** can be optimized using the index.
106302     */
106303     if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
106304       testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
106305       testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
106306       if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
106307         pc.plan.wsFlags |= WHERE_UNIQUE;
106308         if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
106309           pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
106310         }
106311       }
106312     }else if( pProbe->bUnordered==0 ){
106313       int j;
106314       j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
106315       if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
106316         WhereTerm *pTop, *pBtm;
106317         pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
106318         pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
106319         whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
106320         if( pTop ){
106321           nBound = 1;
106322           pc.plan.wsFlags |= WHERE_TOP_LIMIT;
106323           pc.used |= pTop->prereqRight;
106324           testcase( pTop->pWC!=pWC );
106325         }
106326         if( pBtm ){
106327           nBound++;
106328           pc.plan.wsFlags |= WHERE_BTM_LIMIT;
106329           pc.used |= pBtm->prereqRight;
106330           testcase( pBtm->pWC!=pWC );
106331         }
106332         pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
106333       }
106334     }
106335 
106336     /* If there is an ORDER BY clause and the index being considered will
106337     ** naturally scan rows in the required order, set the appropriate flags
106338     ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
106339     ** the index will scan rows in a different order, set the bSort
106340     ** variable.  */
106341     if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
106342       int bRev = 2;
106343       int bObUnique = 0;
106344       WHERETRACE(("      --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
106345       pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
106346       WHERETRACE(("      --> after  isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
106347                   bRev, bObUnique, pc.plan.nOBSat));
106348       if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
106349         pc.plan.wsFlags |= WHERE_ORDERED;
106350         if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
106351       }
106352       if( nOrderBy==pc.plan.nOBSat ){
106353         bSort = 0;
106354         pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
106355       }
106356       if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
106357     }
106358 
106359     /* If there is a DISTINCT qualifier and this index will scan rows in
106360     ** order of the DISTINCT expressions, clear bDist and set the appropriate
106361     ** flags in pc.plan.wsFlags. */
106362     if( bDist
106363      && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
106364      && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
106365     ){
106366       bDist = 0;
106367       pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
106368     }
106369 
106370     /* If currently calculating the cost of using an index (not the IPK
106371     ** index), determine if all required column data may be obtained without
106372     ** using the main table (i.e. if the index is a covering
106373     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
106374     ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
106375     if( pIdx ){
106376       Bitmask m = pSrc->colUsed;
106377       int j;
106378       for(j=0; j<pIdx->nColumn; j++){
106379         int x = pIdx->aiColumn[j];
106380         if( x<BMS-1 ){
106381           m &= ~(((Bitmask)1)<<x);
106382         }
106383       }
106384       if( m==0 ){
106385         pc.plan.wsFlags |= WHERE_IDX_ONLY;
106386       }else{
106387         bLookup = 1;
106388       }
106389     }
106390 
106391     /*
106392     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
106393     ** constraint, do not let the estimate exceed half the rows in the table.
106394     */
106395     pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
106396     if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
106397       pc.plan.nRow = aiRowEst[0]/2;
106398       nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
106399     }
106400 
106401 #ifdef SQLITE_ENABLE_STAT3
106402     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
106403     ** and we do not think that values of x are unique and if histogram
106404     ** data is available for column x, then it might be possible
106405     ** to get a better estimate on the number of rows based on
106406     ** VALUE and how common that value is according to the histogram.
106407     */
106408     if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
106409      && pFirstTerm!=0 && aiRowEst[1]>1 ){
106410       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
106411       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
106412         testcase( pFirstTerm->eOperator & WO_EQ );
106413         testcase( pFirstTerm->eOperator & WO_EQUIV );
106414         testcase( pFirstTerm->eOperator & WO_ISNULL );
106415         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
106416                           &pc.plan.nRow);
106417       }else if( bInEst==0 ){
106418         assert( pFirstTerm->eOperator & WO_IN );
106419         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
106420                        &pc.plan.nRow);
106421       }
106422     }
106423 #endif /* SQLITE_ENABLE_STAT3 */
106424 
106425     /* Adjust the number of output rows and downward to reflect rows
106426     ** that are excluded by range constraints.
106427     */
106428     pc.plan.nRow = pc.plan.nRow/rangeDiv;
106429     if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
106430 
106431     /* Experiments run on real SQLite databases show that the time needed
106432     ** to do a binary search to locate a row in a table or index is roughly
106433     ** log10(N) times the time to move from one row to the next row within
106434     ** a table or index.  The actual times can vary, with the size of
106435     ** records being an important factor.  Both moves and searches are
106436     ** slower with larger records, presumably because fewer records fit
106437     ** on one page and hence more pages have to be fetched.
106438     **
106439     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
106440     ** not give us data on the relative sizes of table and index records.
106441     ** So this computation assumes table records are about twice as big
106442     ** as index records
106443     */
106444     if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
106445                                                               ==WHERE_IDX_ONLY
106446      && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
106447      && sqlite3GlobalConfig.bUseCis
106448      && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
106449     ){
106450       /* This index is not useful for indexing, but it is a covering index.
106451       ** A full-scan of the index might be a little faster than a full-scan
106452       ** of the table, so give this case a cost slightly less than a table
106453       ** scan. */
106454       pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
106455       pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
106456     }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
106457       /* The cost of a full table scan is a number of move operations equal
106458       ** to the number of rows in the table.
106459       **
106460       ** We add an additional 4x penalty to full table scans.  This causes
106461       ** the cost function to err on the side of choosing an index over
106462       ** choosing a full scan.  This 4x full-scan penalty is an arguable
106463       ** decision and one which we expect to revisit in the future.  But
106464       ** it seems to be working well enough at the moment.
106465       */
106466       pc.rCost = aiRowEst[0]*4;
106467       pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
106468       if( pIdx ){
106469         pc.plan.wsFlags &= ~WHERE_ORDERED;
106470         pc.plan.nOBSat = nPriorSat;
106471       }
106472     }else{
106473       log10N = estLog(aiRowEst[0]);
106474       pc.rCost = pc.plan.nRow;
106475       if( pIdx ){
106476         if( bLookup ){
106477           /* For an index lookup followed by a table lookup:
106478           **    nInMul index searches to find the start of each index range
106479           **  + nRow steps through the index
106480           **  + nRow table searches to lookup the table entry using the rowid
106481           */
106482           pc.rCost += (nInMul + pc.plan.nRow)*log10N;
106483         }else{
106484           /* For a covering index:
106485           **     nInMul index searches to find the initial entry
106486           **   + nRow steps through the index
106487           */
106488           pc.rCost += nInMul*log10N;
106489         }
106490       }else{
106491         /* For a rowid primary key lookup:
106492         **    nInMult table searches to find the initial entry for each range
106493         **  + nRow steps through the table
106494         */
106495         pc.rCost += nInMul*log10N;
106496       }
106497     }
106498 
106499     /* Add in the estimated cost of sorting the result.  Actual experimental
106500     ** measurements of sorting performance in SQLite show that sorting time
106501     ** adds C*N*log10(N) to the cost, where N is the number of rows to be
106502     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
106503     ** difference and select C of 3.0.
106504     */
106505     if( bSort ){
106506       double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
106507       m *= (double)(pc.plan.nOBSat ? 2 : 3);
106508       pc.rCost += pc.plan.nRow*m;
106509     }
106510     if( bDist ){
106511       pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
106512     }
106513 
106514     /**** Cost of using this index has now been computed ****/
106515 
106516     /* If there are additional constraints on this table that cannot
106517     ** be used with the current index, but which might lower the number
106518     ** of output rows, adjust the nRow value accordingly.  This only
106519     ** matters if the current index is the least costly, so do not bother
106520     ** with this step if we already know this index will not be chosen.
106521     ** Also, never reduce the output row count below 2 using this step.
106522     **
106523     ** It is critical that the notValid mask be used here instead of
106524     ** the notReady mask.  When computing an "optimal" index, the notReady
106525     ** mask will only have one bit set - the bit for the current table.
106526     ** The notValid mask, on the other hand, always has all bits set for
106527     ** tables that are not in outer loops.  If notReady is used here instead
106528     ** of notValid, then a optimal index that depends on inner joins loops
106529     ** might be selected even when there exists an optimal index that has
106530     ** no such dependency.
106531     */
106532     if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
106533       int k;                       /* Loop counter */
106534       int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
106535       int nSkipRange = nBound;     /* Number of < constraints to skip */
106536       Bitmask thisTab;             /* Bitmap for pSrc */
106537 
106538       thisTab = getMask(pWC->pMaskSet, iCur);
106539       for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
106540         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
106541         if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
106542         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
106543           if( nSkipEq ){
106544             /* Ignore the first pc.plan.nEq equality matches since the index
106545             ** has already accounted for these */
106546             nSkipEq--;
106547           }else{
106548             /* Assume each additional equality match reduces the result
106549             ** set size by a factor of 10 */
106550             pc.plan.nRow /= 10;
106551           }
106552         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
106553           if( nSkipRange ){
106554             /* Ignore the first nSkipRange range constraints since the index
106555             ** has already accounted for these */
106556             nSkipRange--;
106557           }else{
106558             /* Assume each additional range constraint reduces the result
106559             ** set size by a factor of 3.  Indexed range constraints reduce
106560             ** the search space by a larger factor: 4.  We make indexed range
106561             ** more selective intentionally because of the subjective
106562             ** observation that indexed range constraints really are more
106563             ** selective in practice, on average. */
106564             pc.plan.nRow /= 3;
106565           }
106566         }else if( (pTerm->eOperator & WO_NOOP)==0 ){
106567           /* Any other expression lowers the output row count by half */
106568           pc.plan.nRow /= 2;
106569         }
106570       }
106571       if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
106572     }
106573 
106574 
106575     WHERETRACE((
106576       "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
106577       "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
106578       "      used=0x%llx nOBSat=%d\n",
106579       pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
106580       p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
106581       pc.plan.nOBSat
106582     ));
106583 
106584     /* If this index is the best we have seen so far, then record this
106585     ** index and its cost in the p->cost structure.
106586     */
106587     if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
106588       p->cost = pc;
106589       p->cost.plan.wsFlags &= wsFlagMask;
106590       p->cost.plan.u.pIdx = pIdx;
106591     }
106592 
106593     /* If there was an INDEXED BY clause, then only that one index is
106594     ** considered. */
106595     if( pSrc->pIndex ) break;
106596 
106597     /* Reset masks for the next index in the loop */
106598     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
106599     eqTermMask = idxEqTermMask;
106600   }
106601 
106602   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
106603   ** is set, then reverse the order that the index will be scanned
106604   ** in. This is used for application testing, to help find cases
106605   ** where application behavior depends on the (undefined) order that
106606   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
106607   if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
106608     p->cost.plan.wsFlags |= WHERE_REVERSE;
106609   }
106610 
106611   assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
106612   assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
106613   assert( pSrc->pIndex==0
106614        || p->cost.plan.u.pIdx==0
106615        || p->cost.plan.u.pIdx==pSrc->pIndex
106616   );
106617 
106618   WHERETRACE(("   best index is %s cost=%.1f\n",
106619          p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
106620          p->cost.rCost));
106621 
106622   bestOrClauseIndex(p);
106623   bestAutomaticIndex(p);
106624   p->cost.plan.wsFlags |= eqTermMask;
106625 }
106626 
106627 /*
106628 ** Find the query plan for accessing table pSrc->pTab. Write the
106629 ** best query plan and its cost into the WhereCost object supplied
106630 ** as the last parameter. This function may calculate the cost of
106631 ** both real and virtual table scans.
106632 **
106633 ** This function does not take ORDER BY or DISTINCT into account.  Nor
106634 ** does it remember the virtual table query plan.  All it does is compute
106635 ** the cost while determining if an OR optimization is applicable.  The
106636 ** details will be reconsidered later if the optimization is found to be
106637 ** applicable.
106638 */
106639 static void bestIndex(WhereBestIdx *p){
106640 #ifndef SQLITE_OMIT_VIRTUALTABLE
106641   if( IsVirtual(p->pSrc->pTab) ){
106642     sqlite3_index_info *pIdxInfo = 0;
106643     p->ppIdxInfo = &pIdxInfo;
106644     bestVirtualIndex(p);
106645     assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
106646     if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
106647       sqlite3_free(pIdxInfo->idxStr);
106648     }
106649     sqlite3DbFree(p->pParse->db, pIdxInfo);
106650   }else
106651 #endif
106652   {
106653     bestBtreeIndex(p);
106654   }
106655 }
106656 
106657 /*
106658 ** Disable a term in the WHERE clause.  Except, do not disable the term
106659 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
106660 ** or USING clause of that join.
106661 **
106662 ** Consider the term t2.z='ok' in the following queries:
106663 **
106664 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
106665 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
106666 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
106667 **
106668 ** The t2.z='ok' is disabled in the in (2) because it originates
106669 ** in the ON clause.  The term is disabled in (3) because it is not part
106670 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
106671 **
106672 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
106673 ** completely satisfied by indices.
106674 **
106675 ** Disabling a term causes that term to not be tested in the inner loop
106676 ** of the join.  Disabling is an optimization.  When terms are satisfied
106677 ** by indices, we disable them to prevent redundant tests in the inner
106678 ** loop.  We would get the correct results if nothing were ever disabled,
106679 ** but joins might run a little slower.  The trick is to disable as much
106680 ** as we can without disabling too much.  If we disabled in (1), we'd get
106681 ** the wrong answer.  See ticket #813.
106682 */
106683 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
106684   if( pTerm
106685       && (pTerm->wtFlags & TERM_CODED)==0
106686       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
106687   ){
106688     pTerm->wtFlags |= TERM_CODED;
106689     if( pTerm->iParent>=0 ){
106690       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
106691       if( (--pOther->nChild)==0 ){
106692         disableTerm(pLevel, pOther);
106693       }
106694     }
106695   }
106696 }
106697 
106698 /*
106699 ** Code an OP_Affinity opcode to apply the column affinity string zAff
106700 ** to the n registers starting at base.
106701 **
106702 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
106703 ** beginning and end of zAff are ignored.  If all entries in zAff are
106704 ** SQLITE_AFF_NONE, then no code gets generated.
106705 **
106706 ** This routine makes its own copy of zAff so that the caller is free
106707 ** to modify zAff after this routine returns.
106708 */
106709 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
106710   Vdbe *v = pParse->pVdbe;
106711   if( zAff==0 ){
106712     assert( pParse->db->mallocFailed );
106713     return;
106714   }
106715   assert( v!=0 );
106716 
106717   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
106718   ** and end of the affinity string.
106719   */
106720   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
106721     n--;
106722     base++;
106723     zAff++;
106724   }
106725   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
106726     n--;
106727   }
106728 
106729   /* Code the OP_Affinity opcode if there is anything left to do. */
106730   if( n>0 ){
106731     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
106732     sqlite3VdbeChangeP4(v, -1, zAff, n);
106733     sqlite3ExprCacheAffinityChange(pParse, base, n);
106734   }
106735 }
106736 
106737 
106738 /*
106739 ** Generate code for a single equality term of the WHERE clause.  An equality
106740 ** term can be either X=expr or X IN (...).   pTerm is the term to be
106741 ** coded.
106742 **
106743 ** The current value for the constraint is left in register iReg.
106744 **
106745 ** For a constraint of the form X=expr, the expression is evaluated and its
106746 ** result is left on the stack.  For constraints of the form X IN (...)
106747 ** this routine sets up a loop that will iterate over all values of X.
106748 */
106749 static int codeEqualityTerm(
106750   Parse *pParse,      /* The parsing context */
106751   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
106752   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
106753   int iEq,            /* Index of the equality term within this level */
106754   int iTarget         /* Attempt to leave results in this register */
106755 ){
106756   Expr *pX = pTerm->pExpr;
106757   Vdbe *v = pParse->pVdbe;
106758   int iReg;                  /* Register holding results */
106759 
106760   assert( iTarget>0 );
106761   if( pX->op==TK_EQ ){
106762     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
106763   }else if( pX->op==TK_ISNULL ){
106764     iReg = iTarget;
106765     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
106766 #ifndef SQLITE_OMIT_SUBQUERY
106767   }else{
106768     int eType;
106769     int iTab;
106770     struct InLoop *pIn;
106771     u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
106772 
106773     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
106774       && pLevel->plan.u.pIdx->aSortOrder[iEq]
106775     ){
106776       testcase( iEq==0 );
106777       testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
106778       testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
106779       testcase( bRev );
106780       bRev = !bRev;
106781     }
106782     assert( pX->op==TK_IN );
106783     iReg = iTarget;
106784     eType = sqlite3FindInIndex(pParse, pX, 0);
106785     if( eType==IN_INDEX_INDEX_DESC ){
106786       testcase( bRev );
106787       bRev = !bRev;
106788     }
106789     iTab = pX->iTable;
106790     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
106791     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
106792     if( pLevel->u.in.nIn==0 ){
106793       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106794     }
106795     pLevel->u.in.nIn++;
106796     pLevel->u.in.aInLoop =
106797        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
106798                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
106799     pIn = pLevel->u.in.aInLoop;
106800     if( pIn ){
106801       pIn += pLevel->u.in.nIn - 1;
106802       pIn->iCur = iTab;
106803       if( eType==IN_INDEX_ROWID ){
106804         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
106805       }else{
106806         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
106807       }
106808       pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
106809       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
106810     }else{
106811       pLevel->u.in.nIn = 0;
106812     }
106813 #endif
106814   }
106815   disableTerm(pLevel, pTerm);
106816   return iReg;
106817 }
106818 
106819 /*
106820 ** Generate code that will evaluate all == and IN constraints for an
106821 ** index.
106822 **
106823 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
106824 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
106825 ** The index has as many as three equality constraints, but in this
106826 ** example, the third "c" value is an inequality.  So only two
106827 ** constraints are coded.  This routine will generate code to evaluate
106828 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
106829 ** in consecutive registers and the index of the first register is returned.
106830 **
106831 ** In the example above nEq==2.  But this subroutine works for any value
106832 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
106833 ** The only thing it does is allocate the pLevel->iMem memory cell and
106834 ** compute the affinity string.
106835 **
106836 ** This routine always allocates at least one memory cell and returns
106837 ** the index of that memory cell. The code that
106838 ** calls this routine will use that memory cell to store the termination
106839 ** key value of the loop.  If one or more IN operators appear, then
106840 ** this routine allocates an additional nEq memory cells for internal
106841 ** use.
106842 **
106843 ** Before returning, *pzAff is set to point to a buffer containing a
106844 ** copy of the column affinity string of the index allocated using
106845 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
106846 ** with equality constraints that use NONE affinity are set to
106847 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
106848 **
106849 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
106850 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
106851 **
106852 ** In the example above, the index on t1(a) has TEXT affinity. But since
106853 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
106854 ** no conversion should be attempted before using a t2.b value as part of
106855 ** a key to search the index. Hence the first byte in the returned affinity
106856 ** string in this example would be set to SQLITE_AFF_NONE.
106857 */
106858 static int codeAllEqualityTerms(
106859   Parse *pParse,        /* Parsing context */
106860   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
106861   WhereClause *pWC,     /* The WHERE clause */
106862   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
106863   int nExtraReg,        /* Number of extra registers to allocate */
106864   char **pzAff          /* OUT: Set to point to affinity string */
106865 ){
106866   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
106867   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
106868   Index *pIdx;                  /* The index being used for this loop */
106869   int iCur = pLevel->iTabCur;   /* The cursor of the table */
106870   WhereTerm *pTerm;             /* A single constraint term */
106871   int j;                        /* Loop counter */
106872   int regBase;                  /* Base register */
106873   int nReg;                     /* Number of registers to allocate */
106874   char *zAff;                   /* Affinity string to return */
106875 
106876   /* This module is only called on query plans that use an index. */
106877   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
106878   pIdx = pLevel->plan.u.pIdx;
106879 
106880   /* Figure out how many memory cells we will need then allocate them.
106881   */
106882   regBase = pParse->nMem + 1;
106883   nReg = pLevel->plan.nEq + nExtraReg;
106884   pParse->nMem += nReg;
106885 
106886   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
106887   if( !zAff ){
106888     pParse->db->mallocFailed = 1;
106889   }
106890 
106891   /* Evaluate the equality constraints
106892   */
106893   assert( pIdx->nColumn>=nEq );
106894   for(j=0; j<nEq; j++){
106895     int r1;
106896     int k = pIdx->aiColumn[j];
106897     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
106898     if( pTerm==0 ) break;
106899     /* The following true for indices with redundant columns.
106900     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
106901     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
106902     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106903     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
106904     if( r1!=regBase+j ){
106905       if( nReg==1 ){
106906         sqlite3ReleaseTempReg(pParse, regBase);
106907         regBase = r1;
106908       }else{
106909         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
106910       }
106911     }
106912     testcase( pTerm->eOperator & WO_ISNULL );
106913     testcase( pTerm->eOperator & WO_IN );
106914     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
106915       Expr *pRight = pTerm->pExpr->pRight;
106916       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
106917       if( zAff ){
106918         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
106919           zAff[j] = SQLITE_AFF_NONE;
106920         }
106921         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
106922           zAff[j] = SQLITE_AFF_NONE;
106923         }
106924       }
106925     }
106926   }
106927   *pzAff = zAff;
106928   return regBase;
106929 }
106930 
106931 #ifndef SQLITE_OMIT_EXPLAIN
106932 /*
106933 ** This routine is a helper for explainIndexRange() below
106934 **
106935 ** pStr holds the text of an expression that we are building up one term
106936 ** at a time.  This routine adds a new term to the end of the expression.
106937 ** Terms are separated by AND so add the "AND" text for second and subsequent
106938 ** terms only.
106939 */
106940 static void explainAppendTerm(
106941   StrAccum *pStr,             /* The text expression being built */
106942   int iTerm,                  /* Index of this term.  First is zero */
106943   const char *zColumn,        /* Name of the column */
106944   const char *zOp             /* Name of the operator */
106945 ){
106946   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
106947   sqlite3StrAccumAppend(pStr, zColumn, -1);
106948   sqlite3StrAccumAppend(pStr, zOp, 1);
106949   sqlite3StrAccumAppend(pStr, "?", 1);
106950 }
106951 
106952 /*
106953 ** Argument pLevel describes a strategy for scanning table pTab. This
106954 ** function returns a pointer to a string buffer containing a description
106955 ** of the subset of table rows scanned by the strategy in the form of an
106956 ** SQL expression. Or, if all rows are scanned, NULL is returned.
106957 **
106958 ** For example, if the query:
106959 **
106960 **   SELECT * FROM t1 WHERE a=1 AND b>2;
106961 **
106962 ** is run and there is an index on (a, b), then this function returns a
106963 ** string similar to:
106964 **
106965 **   "a=? AND b>?"
106966 **
106967 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
106968 ** It is the responsibility of the caller to free the buffer when it is
106969 ** no longer required.
106970 */
106971 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
106972   WherePlan *pPlan = &pLevel->plan;
106973   Index *pIndex = pPlan->u.pIdx;
106974   int nEq = pPlan->nEq;
106975   int i, j;
106976   Column *aCol = pTab->aCol;
106977   int *aiColumn = pIndex->aiColumn;
106978   StrAccum txt;
106979 
106980   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
106981     return 0;
106982   }
106983   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
106984   txt.db = db;
106985   sqlite3StrAccumAppend(&txt, " (", 2);
106986   for(i=0; i<nEq; i++){
106987     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
106988   }
106989 
106990   j = i;
106991   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
106992     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106993     explainAppendTerm(&txt, i++, z, ">");
106994   }
106995   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
106996     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106997     explainAppendTerm(&txt, i, z, "<");
106998   }
106999   sqlite3StrAccumAppend(&txt, ")", 1);
107000   return sqlite3StrAccumFinish(&txt);
107001 }
107002 
107003 /*
107004 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
107005 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
107006 ** record is added to the output to describe the table scan strategy in
107007 ** pLevel.
107008 */
107009 static void explainOneScan(
107010   Parse *pParse,                  /* Parse context */
107011   SrcList *pTabList,              /* Table list this loop refers to */
107012   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
107013   int iLevel,                     /* Value for "level" column of output */
107014   int iFrom,                      /* Value for "from" column of output */
107015   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
107016 ){
107017   if( pParse->explain==2 ){
107018     u32 flags = pLevel->plan.wsFlags;
107019     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
107020     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
107021     sqlite3 *db = pParse->db;     /* Database handle */
107022     char *zMsg;                   /* Text to add to EQP output */
107023     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
107024     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
107025     int isSearch;                 /* True for a SEARCH. False for SCAN. */
107026 
107027     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
107028 
107029     isSearch = (pLevel->plan.nEq>0)
107030              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107031              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107032 
107033     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
107034     if( pItem->pSelect ){
107035       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
107036     }else{
107037       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
107038     }
107039 
107040     if( pItem->zAlias ){
107041       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
107042     }
107043     if( (flags & WHERE_INDEXED)!=0 ){
107044       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
107045       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
107046           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
107047           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
107048           ((flags & WHERE_TEMP_INDEX)?"":" "),
107049           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
107050           zWhere
107051       );
107052       sqlite3DbFree(db, zWhere);
107053     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107054       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
107055 
107056       if( flags&WHERE_ROWID_EQ ){
107057         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
107058       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
107059         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
107060       }else if( flags&WHERE_BTM_LIMIT ){
107061         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
107062       }else if( flags&WHERE_TOP_LIMIT ){
107063         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
107064       }
107065     }
107066 #ifndef SQLITE_OMIT_VIRTUALTABLE
107067     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
107068       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
107069       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
107070                   pVtabIdx->idxNum, pVtabIdx->idxStr);
107071     }
107072 #endif
107073     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
107074       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
107075       nRow = 1;
107076     }else{
107077       nRow = (sqlite3_int64)pLevel->plan.nRow;
107078     }
107079     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
107080     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
107081   }
107082 }
107083 #else
107084 # define explainOneScan(u,v,w,x,y,z)
107085 #endif /* SQLITE_OMIT_EXPLAIN */
107086 
107087 
107088 /*
107089 ** Generate code for the start of the iLevel-th loop in the WHERE clause
107090 ** implementation described by pWInfo.
107091 */
107092 static Bitmask codeOneLoopStart(
107093   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
107094   int iLevel,          /* Which level of pWInfo->a[] should be coded */
107095   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
107096   Bitmask notReady     /* Which tables are currently available */
107097 ){
107098   int j, k;            /* Loop counters */
107099   int iCur;            /* The VDBE cursor for the table */
107100   int addrNxt;         /* Where to jump to continue with the next IN case */
107101   int omitTable;       /* True if we use the index only */
107102   int bRev;            /* True if we need to scan in reverse order */
107103   WhereLevel *pLevel;  /* The where level to be coded */
107104   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
107105   WhereTerm *pTerm;               /* A WHERE clause term */
107106   Parse *pParse;                  /* Parsing context */
107107   Vdbe *v;                        /* The prepared stmt under constructions */
107108   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
107109   int addrBrk;                    /* Jump here to break out of the loop */
107110   int addrCont;                   /* Jump here to continue with next cycle */
107111   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
107112   int iReleaseReg = 0;      /* Temp register to free before returning */
107113 
107114   pParse = pWInfo->pParse;
107115   v = pParse->pVdbe;
107116   pWC = pWInfo->pWC;
107117   pLevel = &pWInfo->a[iLevel];
107118   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
107119   iCur = pTabItem->iCursor;
107120   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
107121   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
107122            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
107123 
107124   /* Create labels for the "break" and "continue" instructions
107125   ** for the current loop.  Jump to addrBrk to break out of a loop.
107126   ** Jump to cont to go immediately to the next iteration of the
107127   ** loop.
107128   **
107129   ** When there is an IN operator, we also have a "addrNxt" label that
107130   ** means to continue with the next IN value combination.  When
107131   ** there are no IN operators in the constraints, the "addrNxt" label
107132   ** is the same as "addrBrk".
107133   */
107134   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107135   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
107136 
107137   /* If this is the right table of a LEFT OUTER JOIN, allocate and
107138   ** initialize a memory cell that records if this table matches any
107139   ** row of the left table of the join.
107140   */
107141   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
107142     pLevel->iLeftJoin = ++pParse->nMem;
107143     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
107144     VdbeComment((v, "init LEFT JOIN no-match flag"));
107145   }
107146 
107147   /* Special case of a FROM clause subquery implemented as a co-routine */
107148   if( pTabItem->viaCoroutine ){
107149     int regYield = pTabItem->regReturn;
107150     sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
107151     pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
107152     VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
107153     sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
107154     pLevel->op = OP_Goto;
107155   }else
107156 
107157 #ifndef SQLITE_OMIT_VIRTUALTABLE
107158   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107159     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
107160     **          to access the data.
107161     */
107162     int iReg;   /* P3 Value for OP_VFilter */
107163     int addrNotFound;
107164     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
107165     int nConstraint = pVtabIdx->nConstraint;
107166     struct sqlite3_index_constraint_usage *aUsage =
107167                                                 pVtabIdx->aConstraintUsage;
107168     const struct sqlite3_index_constraint *aConstraint =
107169                                                 pVtabIdx->aConstraint;
107170 
107171     sqlite3ExprCachePush(pParse);
107172     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
107173     addrNotFound = pLevel->addrBrk;
107174     for(j=1; j<=nConstraint; j++){
107175       for(k=0; k<nConstraint; k++){
107176         if( aUsage[k].argvIndex==j ){
107177           int iTarget = iReg+j+1;
107178           pTerm = &pWC->a[aConstraint[k].iTermOffset];
107179           if( pTerm->eOperator & WO_IN ){
107180             codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
107181             addrNotFound = pLevel->addrNxt;
107182           }else{
107183             sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
107184           }
107185           break;
107186         }
107187       }
107188       if( k==nConstraint ) break;
107189     }
107190     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
107191     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
107192     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
107193                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
107194     pVtabIdx->needToFreeIdxStr = 0;
107195     for(j=0; j<nConstraint; j++){
107196       if( aUsage[j].omit ){
107197         int iTerm = aConstraint[j].iTermOffset;
107198         disableTerm(pLevel, &pWC->a[iTerm]);
107199       }
107200     }
107201     pLevel->op = OP_VNext;
107202     pLevel->p1 = iCur;
107203     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
107204     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
107205     sqlite3ExprCachePop(pParse, 1);
107206   }else
107207 #endif /* SQLITE_OMIT_VIRTUALTABLE */
107208 
107209   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
107210     /* Case 1:  We can directly reference a single row using an
107211     **          equality comparison against the ROWID field.  Or
107212     **          we reference multiple rows using a "rowid IN (...)"
107213     **          construct.
107214     */
107215     iReleaseReg = sqlite3GetTempReg(pParse);
107216     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
107217     assert( pTerm!=0 );
107218     assert( pTerm->pExpr!=0 );
107219     assert( omitTable==0 );
107220     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107221     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
107222     addrNxt = pLevel->addrNxt;
107223     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
107224     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
107225     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
107226     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107227     VdbeComment((v, "pk"));
107228     pLevel->op = OP_Noop;
107229   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
107230     /* Case 2:  We have an inequality comparison against the ROWID field.
107231     */
107232     int testOp = OP_Noop;
107233     int start;
107234     int memEndValue = 0;
107235     WhereTerm *pStart, *pEnd;
107236 
107237     assert( omitTable==0 );
107238     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
107239     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
107240     if( bRev ){
107241       pTerm = pStart;
107242       pStart = pEnd;
107243       pEnd = pTerm;
107244     }
107245     if( pStart ){
107246       Expr *pX;             /* The expression that defines the start bound */
107247       int r1, rTemp;        /* Registers for holding the start boundary */
107248 
107249       /* The following constant maps TK_xx codes into corresponding
107250       ** seek opcodes.  It depends on a particular ordering of TK_xx
107251       */
107252       const u8 aMoveOp[] = {
107253            /* TK_GT */  OP_SeekGt,
107254            /* TK_LE */  OP_SeekLe,
107255            /* TK_LT */  OP_SeekLt,
107256            /* TK_GE */  OP_SeekGe
107257       };
107258       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
107259       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
107260       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
107261 
107262       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107263       pX = pStart->pExpr;
107264       assert( pX!=0 );
107265       assert( pStart->leftCursor==iCur );
107266       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
107267       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
107268       VdbeComment((v, "pk"));
107269       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
107270       sqlite3ReleaseTempReg(pParse, rTemp);
107271       disableTerm(pLevel, pStart);
107272     }else{
107273       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
107274     }
107275     if( pEnd ){
107276       Expr *pX;
107277       pX = pEnd->pExpr;
107278       assert( pX!=0 );
107279       assert( pEnd->leftCursor==iCur );
107280       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107281       memEndValue = ++pParse->nMem;
107282       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
107283       if( pX->op==TK_LT || pX->op==TK_GT ){
107284         testOp = bRev ? OP_Le : OP_Ge;
107285       }else{
107286         testOp = bRev ? OP_Lt : OP_Gt;
107287       }
107288       disableTerm(pLevel, pEnd);
107289     }
107290     start = sqlite3VdbeCurrentAddr(v);
107291     pLevel->op = bRev ? OP_Prev : OP_Next;
107292     pLevel->p1 = iCur;
107293     pLevel->p2 = start;
107294     if( pStart==0 && pEnd==0 ){
107295       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107296     }else{
107297       assert( pLevel->p5==0 );
107298     }
107299     if( testOp!=OP_Noop ){
107300       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107301       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
107302       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107303       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
107304       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
107305     }
107306   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
107307     /* Case 3: A scan using an index.
107308     **
107309     **         The WHERE clause may contain zero or more equality
107310     **         terms ("==" or "IN" operators) that refer to the N
107311     **         left-most columns of the index. It may also contain
107312     **         inequality constraints (>, <, >= or <=) on the indexed
107313     **         column that immediately follows the N equalities. Only
107314     **         the right-most column can be an inequality - the rest must
107315     **         use the "==" and "IN" operators. For example, if the
107316     **         index is on (x,y,z), then the following clauses are all
107317     **         optimized:
107318     **
107319     **            x=5
107320     **            x=5 AND y=10
107321     **            x=5 AND y<10
107322     **            x=5 AND y>5 AND y<10
107323     **            x=5 AND y=5 AND z<=10
107324     **
107325     **         The z<10 term of the following cannot be used, only
107326     **         the x=5 term:
107327     **
107328     **            x=5 AND z<10
107329     **
107330     **         N may be zero if there are inequality constraints.
107331     **         If there are no inequality constraints, then N is at
107332     **         least one.
107333     **
107334     **         This case is also used when there are no WHERE clause
107335     **         constraints but an index is selected anyway, in order
107336     **         to force the output order to conform to an ORDER BY.
107337     */
107338     static const u8 aStartOp[] = {
107339       0,
107340       0,
107341       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
107342       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
107343       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
107344       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
107345       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
107346       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
107347     };
107348     static const u8 aEndOp[] = {
107349       OP_Noop,             /* 0: (!end_constraints) */
107350       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
107351       OP_IdxLT             /* 2: (end_constraints && bRev) */
107352     };
107353     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
107354     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
107355     int regBase;                 /* Base register holding constraint values */
107356     int r1;                      /* Temp register */
107357     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
107358     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
107359     int startEq;                 /* True if range start uses ==, >= or <= */
107360     int endEq;                   /* True if range end uses ==, >= or <= */
107361     int start_constraints;       /* Start of range is constrained */
107362     int nConstraint;             /* Number of constraint terms */
107363     Index *pIdx;                 /* The index we will be using */
107364     int iIdxCur;                 /* The VDBE cursor for the index */
107365     int nExtraReg = 0;           /* Number of extra registers needed */
107366     int op;                      /* Instruction opcode */
107367     char *zStartAff;             /* Affinity for start of range constraint */
107368     char *zEndAff;               /* Affinity for end of range constraint */
107369 
107370     pIdx = pLevel->plan.u.pIdx;
107371     iIdxCur = pLevel->iIdxCur;
107372     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
107373 
107374     /* If this loop satisfies a sort order (pOrderBy) request that
107375     ** was passed to this function to implement a "SELECT min(x) ..."
107376     ** query, then the caller will only allow the loop to run for
107377     ** a single iteration. This means that the first row returned
107378     ** should not have a NULL value stored in 'x'. If column 'x' is
107379     ** the first one after the nEq equality constraints in the index,
107380     ** this requires some special handling.
107381     */
107382     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
107383      && (pLevel->plan.wsFlags&WHERE_ORDERED)
107384      && (pIdx->nColumn>nEq)
107385     ){
107386       /* assert( pOrderBy->nExpr==1 ); */
107387       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
107388       isMinQuery = 1;
107389       nExtraReg = 1;
107390     }
107391 
107392     /* Find any inequality constraint terms for the start and end
107393     ** of the range.
107394     */
107395     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
107396       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
107397       nExtraReg = 1;
107398     }
107399     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
107400       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
107401       nExtraReg = 1;
107402     }
107403 
107404     /* Generate code to evaluate all constraint terms using == or IN
107405     ** and store the values of those terms in an array of registers
107406     ** starting at regBase.
107407     */
107408     regBase = codeAllEqualityTerms(
107409         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
107410     );
107411     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
107412     addrNxt = pLevel->addrNxt;
107413 
107414     /* If we are doing a reverse order scan on an ascending index, or
107415     ** a forward order scan on a descending index, interchange the
107416     ** start and end terms (pRangeStart and pRangeEnd).
107417     */
107418     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
107419      || (bRev && pIdx->nColumn==nEq)
107420     ){
107421       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
107422     }
107423 
107424     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
107425     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
107426     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
107427     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
107428     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
107429     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
107430     start_constraints = pRangeStart || nEq>0;
107431 
107432     /* Seek the index cursor to the start of the range. */
107433     nConstraint = nEq;
107434     if( pRangeStart ){
107435       Expr *pRight = pRangeStart->pExpr->pRight;
107436       sqlite3ExprCode(pParse, pRight, regBase+nEq);
107437       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
107438         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
107439       }
107440       if( zStartAff ){
107441         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
107442           /* Since the comparison is to be performed with no conversions
107443           ** applied to the operands, set the affinity to apply to pRight to
107444           ** SQLITE_AFF_NONE.  */
107445           zStartAff[nEq] = SQLITE_AFF_NONE;
107446         }
107447         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
107448           zStartAff[nEq] = SQLITE_AFF_NONE;
107449         }
107450       }
107451       nConstraint++;
107452       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107453     }else if( isMinQuery ){
107454       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
107455       nConstraint++;
107456       startEq = 0;
107457       start_constraints = 1;
107458     }
107459     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
107460     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
107461     assert( op!=0 );
107462     testcase( op==OP_Rewind );
107463     testcase( op==OP_Last );
107464     testcase( op==OP_SeekGt );
107465     testcase( op==OP_SeekGe );
107466     testcase( op==OP_SeekLe );
107467     testcase( op==OP_SeekLt );
107468     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
107469 
107470     /* Load the value for the inequality constraint at the end of the
107471     ** range (if any).
107472     */
107473     nConstraint = nEq;
107474     if( pRangeEnd ){
107475       Expr *pRight = pRangeEnd->pExpr->pRight;
107476       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
107477       sqlite3ExprCode(pParse, pRight, regBase+nEq);
107478       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
107479         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
107480       }
107481       if( zEndAff ){
107482         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
107483           /* Since the comparison is to be performed with no conversions
107484           ** applied to the operands, set the affinity to apply to pRight to
107485           ** SQLITE_AFF_NONE.  */
107486           zEndAff[nEq] = SQLITE_AFF_NONE;
107487         }
107488         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
107489           zEndAff[nEq] = SQLITE_AFF_NONE;
107490         }
107491       }
107492       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
107493       nConstraint++;
107494       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107495     }
107496     sqlite3DbFree(pParse->db, zStartAff);
107497     sqlite3DbFree(pParse->db, zEndAff);
107498 
107499     /* Top of the loop body */
107500     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
107501 
107502     /* Check if the index cursor is past the end of the range. */
107503     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
107504     testcase( op==OP_Noop );
107505     testcase( op==OP_IdxGE );
107506     testcase( op==OP_IdxLT );
107507     if( op!=OP_Noop ){
107508       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
107509       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
107510     }
107511 
107512     /* If there are inequality constraints, check that the value
107513     ** of the table column that the inequality contrains is not NULL.
107514     ** If it is, jump to the next iteration of the loop.
107515     */
107516     r1 = sqlite3GetTempReg(pParse);
107517     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
107518     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
107519     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
107520       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
107521       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
107522     }
107523     sqlite3ReleaseTempReg(pParse, r1);
107524 
107525     /* Seek the table cursor, if required */
107526     disableTerm(pLevel, pRangeStart);
107527     disableTerm(pLevel, pRangeEnd);
107528     if( !omitTable ){
107529       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107530       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
107531       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107532       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
107533     }
107534 
107535     /* Record the instruction used to terminate the loop. Disable
107536     ** WHERE clause terms made redundant by the index range scan.
107537     */
107538     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
107539       pLevel->op = OP_Noop;
107540     }else if( bRev ){
107541       pLevel->op = OP_Prev;
107542     }else{
107543       pLevel->op = OP_Next;
107544     }
107545     pLevel->p1 = iIdxCur;
107546     if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
107547       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107548     }else{
107549       assert( pLevel->p5==0 );
107550     }
107551   }else
107552 
107553 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
107554   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
107555     /* Case 4:  Two or more separately indexed terms connected by OR
107556     **
107557     ** Example:
107558     **
107559     **   CREATE TABLE t1(a,b,c,d);
107560     **   CREATE INDEX i1 ON t1(a);
107561     **   CREATE INDEX i2 ON t1(b);
107562     **   CREATE INDEX i3 ON t1(c);
107563     **
107564     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
107565     **
107566     ** In the example, there are three indexed terms connected by OR.
107567     ** The top of the loop looks like this:
107568     **
107569     **          Null       1                # Zero the rowset in reg 1
107570     **
107571     ** Then, for each indexed term, the following. The arguments to
107572     ** RowSetTest are such that the rowid of the current row is inserted
107573     ** into the RowSet. If it is already present, control skips the
107574     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
107575     **
107576     **        sqlite3WhereBegin(<term>)
107577     **          RowSetTest                  # Insert rowid into rowset
107578     **          Gosub      2 A
107579     **        sqlite3WhereEnd()
107580     **
107581     ** Following the above, code to terminate the loop. Label A, the target
107582     ** of the Gosub above, jumps to the instruction right after the Goto.
107583     **
107584     **          Null       1                # Zero the rowset in reg 1
107585     **          Goto       B                # The loop is finished.
107586     **
107587     **       A: <loop body>                 # Return data, whatever.
107588     **
107589     **          Return     2                # Jump back to the Gosub
107590     **
107591     **       B: <after the loop>
107592     **
107593     */
107594     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
107595     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
107596     Index *pCov = 0;             /* Potential covering index (or NULL) */
107597     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
107598 
107599     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
107600     int regRowset = 0;                        /* Register for RowSet object */
107601     int regRowid = 0;                         /* Register holding rowid */
107602     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
107603     int iRetInit;                             /* Address of regReturn init */
107604     int untestedTerms = 0;             /* Some terms not completely tested */
107605     int ii;                            /* Loop counter */
107606     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
107607 
107608     pTerm = pLevel->plan.u.pTerm;
107609     assert( pTerm!=0 );
107610     assert( pTerm->eOperator & WO_OR );
107611     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
107612     pOrWc = &pTerm->u.pOrInfo->wc;
107613     pLevel->op = OP_Return;
107614     pLevel->p1 = regReturn;
107615 
107616     /* Set up a new SrcList in pOrTab containing the table being scanned
107617     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
107618     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
107619     */
107620     if( pWInfo->nLevel>1 ){
107621       int nNotReady;                 /* The number of notReady tables */
107622       struct SrcList_item *origSrc;     /* Original list of tables */
107623       nNotReady = pWInfo->nLevel - iLevel - 1;
107624       pOrTab = sqlite3StackAllocRaw(pParse->db,
107625                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
107626       if( pOrTab==0 ) return notReady;
107627       pOrTab->nAlloc = (i16)(nNotReady + 1);
107628       pOrTab->nSrc = pOrTab->nAlloc;
107629       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
107630       origSrc = pWInfo->pTabList->a;
107631       for(k=1; k<=nNotReady; k++){
107632         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
107633       }
107634     }else{
107635       pOrTab = pWInfo->pTabList;
107636     }
107637 
107638     /* Initialize the rowset register to contain NULL. An SQL NULL is
107639     ** equivalent to an empty rowset.
107640     **
107641     ** Also initialize regReturn to contain the address of the instruction
107642     ** immediately following the OP_Return at the bottom of the loop. This
107643     ** is required in a few obscure LEFT JOIN cases where control jumps
107644     ** over the top of the loop into the body of it. In this case the
107645     ** correct response for the end-of-loop code (the OP_Return) is to
107646     ** fall through to the next instruction, just as an OP_Next does if
107647     ** called on an uninitialized cursor.
107648     */
107649     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107650       regRowset = ++pParse->nMem;
107651       regRowid = ++pParse->nMem;
107652       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
107653     }
107654     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
107655 
107656     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
107657     ** Then for every term xN, evaluate as the subexpression: xN AND z
107658     ** That way, terms in y that are factored into the disjunction will
107659     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
107660     **
107661     ** Actually, each subexpression is converted to "xN AND w" where w is
107662     ** the "interesting" terms of z - terms that did not originate in the
107663     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
107664     ** indices.
107665     */
107666     if( pWC->nTerm>1 ){
107667       int iTerm;
107668       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
107669         Expr *pExpr = pWC->a[iTerm].pExpr;
107670         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
107671         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
107672         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
107673         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
107674         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
107675       }
107676       if( pAndExpr ){
107677         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
107678       }
107679     }
107680 
107681     for(ii=0; ii<pOrWc->nTerm; ii++){
107682       WhereTerm *pOrTerm = &pOrWc->a[ii];
107683       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
107684         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
107685         Expr *pOrExpr = pOrTerm->pExpr;
107686         if( pAndExpr ){
107687           pAndExpr->pLeft = pOrExpr;
107688           pOrExpr = pAndExpr;
107689         }
107690         /* Loop through table entries that match term pOrTerm. */
107691         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
107692                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
107693                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
107694         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
107695         if( pSubWInfo ){
107696           WhereLevel *pLvl;
107697           explainOneScan(
107698               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
107699           );
107700           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
107701             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
107702             int r;
107703             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
107704                                          regRowid, 0);
107705             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
107706                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
107707           }
107708           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
107709 
107710           /* The pSubWInfo->untestedTerms flag means that this OR term
107711           ** contained one or more AND term from a notReady table.  The
107712           ** terms from the notReady table could not be tested and will
107713           ** need to be tested later.
107714           */
107715           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
107716 
107717           /* If all of the OR-connected terms are optimized using the same
107718           ** index, and the index is opened using the same cursor number
107719           ** by each call to sqlite3WhereBegin() made by this loop, it may
107720           ** be possible to use that index as a covering index.
107721           **
107722           ** If the call to sqlite3WhereBegin() above resulted in a scan that
107723           ** uses an index, and this is either the first OR-connected term
107724           ** processed or the index is the same as that used by all previous
107725           ** terms, set pCov to the candidate covering index. Otherwise, set
107726           ** pCov to NULL to indicate that no candidate covering index will
107727           ** be available.
107728           */
107729           pLvl = &pSubWInfo->a[0];
107730           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
107731            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
107732            && (ii==0 || pLvl->plan.u.pIdx==pCov)
107733           ){
107734             assert( pLvl->iIdxCur==iCovCur );
107735             pCov = pLvl->plan.u.pIdx;
107736           }else{
107737             pCov = 0;
107738           }
107739 
107740           /* Finish the loop through table entries that match term pOrTerm. */
107741           sqlite3WhereEnd(pSubWInfo);
107742         }
107743       }
107744     }
107745     pLevel->u.pCovidx = pCov;
107746     if( pCov ) pLevel->iIdxCur = iCovCur;
107747     if( pAndExpr ){
107748       pAndExpr->pLeft = 0;
107749       sqlite3ExprDelete(pParse->db, pAndExpr);
107750     }
107751     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
107752     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
107753     sqlite3VdbeResolveLabel(v, iLoopBody);
107754 
107755     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
107756     if( !untestedTerms ) disableTerm(pLevel, pTerm);
107757   }else
107758 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
107759 
107760   {
107761     /* Case 5:  There is no usable index.  We must do a complete
107762     **          scan of the entire table.
107763     */
107764     static const u8 aStep[] = { OP_Next, OP_Prev };
107765     static const u8 aStart[] = { OP_Rewind, OP_Last };
107766     assert( bRev==0 || bRev==1 );
107767     assert( omitTable==0 );
107768     pLevel->op = aStep[bRev];
107769     pLevel->p1 = iCur;
107770     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
107771     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107772   }
107773   notReady &= ~getMask(pWC->pMaskSet, iCur);
107774 
107775   /* Insert code to test every subexpression that can be completely
107776   ** computed using the current set of tables.
107777   **
107778   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
107779   ** the use of indices become tests that are evaluated against each row of
107780   ** the relevant input tables.
107781   */
107782   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
107783     Expr *pE;
107784     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
107785     testcase( pTerm->wtFlags & TERM_CODED );
107786     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107787     if( (pTerm->prereqAll & notReady)!=0 ){
107788       testcase( pWInfo->untestedTerms==0
107789                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
107790       pWInfo->untestedTerms = 1;
107791       continue;
107792     }
107793     pE = pTerm->pExpr;
107794     assert( pE!=0 );
107795     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
107796       continue;
107797     }
107798     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
107799     pTerm->wtFlags |= TERM_CODED;
107800   }
107801 
107802   /* For a LEFT OUTER JOIN, generate code that will record the fact that
107803   ** at least one row of the right table has matched the left table.
107804   */
107805   if( pLevel->iLeftJoin ){
107806     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
107807     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
107808     VdbeComment((v, "record LEFT JOIN hit"));
107809     sqlite3ExprCacheClear(pParse);
107810     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
107811       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
107812       testcase( pTerm->wtFlags & TERM_CODED );
107813       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107814       if( (pTerm->prereqAll & notReady)!=0 ){
107815         assert( pWInfo->untestedTerms );
107816         continue;
107817       }
107818       assert( pTerm->pExpr );
107819       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
107820       pTerm->wtFlags |= TERM_CODED;
107821     }
107822   }
107823   sqlite3ReleaseTempReg(pParse, iReleaseReg);
107824 
107825   return notReady;
107826 }
107827 
107828 #if defined(SQLITE_TEST)
107829 /*
107830 ** The following variable holds a text description of query plan generated
107831 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
107832 ** overwrites the previous.  This information is used for testing and
107833 ** analysis only.
107834 */
107835 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
107836 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
107837 
107838 #endif /* SQLITE_TEST */
107839 
107840 
107841 /*
107842 ** Free a WhereInfo structure
107843 */
107844 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
107845   if( ALWAYS(pWInfo) ){
107846     int i;
107847     for(i=0; i<pWInfo->nLevel; i++){
107848       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
107849       if( pInfo ){
107850         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
107851         if( pInfo->needToFreeIdxStr ){
107852           sqlite3_free(pInfo->idxStr);
107853         }
107854         sqlite3DbFree(db, pInfo);
107855       }
107856       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
107857         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
107858         if( pIdx ){
107859           sqlite3DbFree(db, pIdx->zColAff);
107860           sqlite3DbFree(db, pIdx);
107861         }
107862       }
107863     }
107864     whereClauseClear(pWInfo->pWC);
107865     sqlite3DbFree(db, pWInfo);
107866   }
107867 }
107868 
107869 
107870 /*
107871 ** Generate the beginning of the loop used for WHERE clause processing.
107872 ** The return value is a pointer to an opaque structure that contains
107873 ** information needed to terminate the loop.  Later, the calling routine
107874 ** should invoke sqlite3WhereEnd() with the return value of this function
107875 ** in order to complete the WHERE clause processing.
107876 **
107877 ** If an error occurs, this routine returns NULL.
107878 **
107879 ** The basic idea is to do a nested loop, one loop for each table in
107880 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
107881 ** same as a SELECT with only a single table in the FROM clause.)  For
107882 ** example, if the SQL is this:
107883 **
107884 **       SELECT * FROM t1, t2, t3 WHERE ...;
107885 **
107886 ** Then the code generated is conceptually like the following:
107887 **
107888 **      foreach row1 in t1 do       \    Code generated
107889 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
107890 **          foreach row3 in t3 do   /
107891 **            ...
107892 **          end                     \    Code generated
107893 **        end                        |-- by sqlite3WhereEnd()
107894 **      end                         /
107895 **
107896 ** Note that the loops might not be nested in the order in which they
107897 ** appear in the FROM clause if a different order is better able to make
107898 ** use of indices.  Note also that when the IN operator appears in
107899 ** the WHERE clause, it might result in additional nested loops for
107900 ** scanning through all values on the right-hand side of the IN.
107901 **
107902 ** There are Btree cursors associated with each table.  t1 uses cursor
107903 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
107904 ** And so forth.  This routine generates code to open those VDBE cursors
107905 ** and sqlite3WhereEnd() generates the code to close them.
107906 **
107907 ** The code that sqlite3WhereBegin() generates leaves the cursors named
107908 ** in pTabList pointing at their appropriate entries.  The [...] code
107909 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
107910 ** data from the various tables of the loop.
107911 **
107912 ** If the WHERE clause is empty, the foreach loops must each scan their
107913 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
107914 ** the tables have indices and there are terms in the WHERE clause that
107915 ** refer to those indices, a complete table scan can be avoided and the
107916 ** code will run much faster.  Most of the work of this routine is checking
107917 ** to see if there are indices that can be used to speed up the loop.
107918 **
107919 ** Terms of the WHERE clause are also used to limit which rows actually
107920 ** make it to the "..." in the middle of the loop.  After each "foreach",
107921 ** terms of the WHERE clause that use only terms in that loop and outer
107922 ** loops are evaluated and if false a jump is made around all subsequent
107923 ** inner loops (or around the "..." if the test occurs within the inner-
107924 ** most loop)
107925 **
107926 ** OUTER JOINS
107927 **
107928 ** An outer join of tables t1 and t2 is conceptally coded as follows:
107929 **
107930 **    foreach row1 in t1 do
107931 **      flag = 0
107932 **      foreach row2 in t2 do
107933 **        start:
107934 **          ...
107935 **          flag = 1
107936 **      end
107937 **      if flag==0 then
107938 **        move the row2 cursor to a null row
107939 **        goto start
107940 **      fi
107941 **    end
107942 **
107943 ** ORDER BY CLAUSE PROCESSING
107944 **
107945 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
107946 ** if there is one.  If there is no ORDER BY clause or if this routine
107947 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
107948 **
107949 ** If an index can be used so that the natural output order of the table
107950 ** scan is correct for the ORDER BY clause, then that index is used and
107951 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
107952 ** is an optimization that prevents an unnecessary sort of the result set
107953 ** if an index appropriate for the ORDER BY clause already exists.
107954 **
107955 ** If the where clause loops cannot be arranged to provide the correct
107956 ** output order, then WhereInfo.nOBSat is 0.
107957 */
107958 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
107959   Parse *pParse,        /* The parser context */
107960   SrcList *pTabList,    /* A list of all tables to be scanned */
107961   Expr *pWhere,         /* The WHERE clause */
107962   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
107963   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
107964   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
107965   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
107966 ){
107967   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
107968   int nTabList;              /* Number of elements in pTabList */
107969   WhereInfo *pWInfo;         /* Will become the return value of this function */
107970   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
107971   Bitmask notReady;          /* Cursors that are not yet positioned */
107972   WhereBestIdx sWBI;         /* Best index search context */
107973   WhereMaskSet *pMaskSet;    /* The expression mask set */
107974   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
107975   int iFrom;                 /* First unused FROM clause element */
107976   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
107977   int ii;                    /* Loop counter */
107978   sqlite3 *db;               /* Database connection */
107979 
107980 
107981   /* Variable initialization */
107982   memset(&sWBI, 0, sizeof(sWBI));
107983   sWBI.pParse = pParse;
107984 
107985   /* The number of tables in the FROM clause is limited by the number of
107986   ** bits in a Bitmask
107987   */
107988   testcase( pTabList->nSrc==BMS );
107989   if( pTabList->nSrc>BMS ){
107990     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
107991     return 0;
107992   }
107993 
107994   /* This function normally generates a nested loop for all tables in
107995   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
107996   ** only generate code for the first table in pTabList and assume that
107997   ** any cursors associated with subsequent tables are uninitialized.
107998   */
107999   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
108000 
108001   /* Allocate and initialize the WhereInfo structure that will become the
108002   ** return value. A single allocation is used to store the WhereInfo
108003   ** struct, the contents of WhereInfo.a[], the WhereClause structure
108004   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
108005   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
108006   ** some architectures. Hence the ROUND8() below.
108007   */
108008   db = pParse->db;
108009   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
108010   pWInfo = sqlite3DbMallocZero(db,
108011       nByteWInfo +
108012       sizeof(WhereClause) +
108013       sizeof(WhereMaskSet)
108014   );
108015   if( db->mallocFailed ){
108016     sqlite3DbFree(db, pWInfo);
108017     pWInfo = 0;
108018     goto whereBeginError;
108019   }
108020   pWInfo->nLevel = nTabList;
108021   pWInfo->pParse = pParse;
108022   pWInfo->pTabList = pTabList;
108023   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
108024   pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
108025   pWInfo->wctrlFlags = wctrlFlags;
108026   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
108027   pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
108028   sWBI.aLevel = pWInfo->a;
108029 
108030   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
108031   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
108032   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
108033 
108034   /* Split the WHERE clause into separate subexpressions where each
108035   ** subexpression is separated by an AND operator.
108036   */
108037   initMaskSet(pMaskSet);
108038   whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
108039   sqlite3ExprCodeConstants(pParse, pWhere);
108040   whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
108041 
108042   /* Special case: a WHERE clause that is constant.  Evaluate the
108043   ** expression and either jump over all of the code or fall thru.
108044   */
108045   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
108046     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
108047     pWhere = 0;
108048   }
108049 
108050   /* Assign a bit from the bitmask to every term in the FROM clause.
108051   **
108052   ** When assigning bitmask values to FROM clause cursors, it must be
108053   ** the case that if X is the bitmask for the N-th FROM clause term then
108054   ** the bitmask for all FROM clause terms to the left of the N-th term
108055   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
108056   ** its Expr.iRightJoinTable value to find the bitmask of the right table
108057   ** of the join.  Subtracting one from the right table bitmask gives a
108058   ** bitmask for all tables to the left of the join.  Knowing the bitmask
108059   ** for all tables to the left of a left join is important.  Ticket #3015.
108060   **
108061   ** Note that bitmasks are created for all pTabList->nSrc tables in
108062   ** pTabList, not just the first nTabList tables.  nTabList is normally
108063   ** equal to pTabList->nSrc but might be shortened to 1 if the
108064   ** WHERE_ONETABLE_ONLY flag is set.
108065   */
108066   for(ii=0; ii<pTabList->nSrc; ii++){
108067     createMask(pMaskSet, pTabList->a[ii].iCursor);
108068   }
108069 #ifndef NDEBUG
108070   {
108071     Bitmask toTheLeft = 0;
108072     for(ii=0; ii<pTabList->nSrc; ii++){
108073       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
108074       assert( (m-1)==toTheLeft );
108075       toTheLeft |= m;
108076     }
108077   }
108078 #endif
108079 
108080   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
108081   ** add new virtual terms onto the end of the WHERE clause.  We do not
108082   ** want to analyze these virtual terms, so start analyzing at the end
108083   ** and work forward so that the added virtual terms are never processed.
108084   */
108085   exprAnalyzeAll(pTabList, sWBI.pWC);
108086   if( db->mallocFailed ){
108087     goto whereBeginError;
108088   }
108089 
108090   /* Check if the DISTINCT qualifier, if there is one, is redundant.
108091   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
108092   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
108093   */
108094   if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
108095     pDistinct = 0;
108096     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
108097   }
108098 
108099   /* Chose the best index to use for each table in the FROM clause.
108100   **
108101   ** This loop fills in the following fields:
108102   **
108103   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
108104   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
108105   **   pWInfo->a[].nEq       The number of == and IN constraints
108106   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
108107   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
108108   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
108109   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
108110   **
108111   ** This loop also figures out the nesting order of tables in the FROM
108112   ** clause.
108113   */
108114   sWBI.notValid = ~(Bitmask)0;
108115   sWBI.pOrderBy = pOrderBy;
108116   sWBI.n = nTabList;
108117   sWBI.pDistinct = pDistinct;
108118   andFlags = ~0;
108119   WHERETRACE(("*** Optimizer Start ***\n"));
108120   for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
108121     WhereCost bestPlan;         /* Most efficient plan seen so far */
108122     Index *pIdx;                /* Index for FROM table at pTabItem */
108123     int j;                      /* For looping over FROM tables */
108124     int bestJ = -1;             /* The value of j */
108125     Bitmask m;                  /* Bitmask value for j or bestJ */
108126     int isOptimal;              /* Iterator for optimal/non-optimal search */
108127     int ckOptimal;              /* Do the optimal scan check */
108128     int nUnconstrained;         /* Number tables without INDEXED BY */
108129     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
108130 
108131     memset(&bestPlan, 0, sizeof(bestPlan));
108132     bestPlan.rCost = SQLITE_BIG_DBL;
108133     WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
108134 
108135     /* Loop through the remaining entries in the FROM clause to find the
108136     ** next nested loop. The loop tests all FROM clause entries
108137     ** either once or twice.
108138     **
108139     ** The first test is always performed if there are two or more entries
108140     ** remaining and never performed if there is only one FROM clause entry
108141     ** to choose from.  The first test looks for an "optimal" scan.  In
108142     ** this context an optimal scan is one that uses the same strategy
108143     ** for the given FROM clause entry as would be selected if the entry
108144     ** were used as the innermost nested loop.  In other words, a table
108145     ** is chosen such that the cost of running that table cannot be reduced
108146     ** by waiting for other tables to run first.  This "optimal" test works
108147     ** by first assuming that the FROM clause is on the inner loop and finding
108148     ** its query plan, then checking to see if that query plan uses any
108149     ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
108150     ** are used then the "optimal" query plan works.
108151     **
108152     ** Note that the WhereCost.nRow parameter for an optimal scan might
108153     ** not be as small as it would be if the table really were the innermost
108154     ** join.  The nRow value can be reduced by WHERE clause constraints
108155     ** that do not use indices.  But this nRow reduction only happens if the
108156     ** table really is the innermost join.
108157     **
108158     ** The second loop iteration is only performed if no optimal scan
108159     ** strategies were found by the first iteration. This second iteration
108160     ** is used to search for the lowest cost scan overall.
108161     **
108162     ** Without the optimal scan step (the first iteration) a suboptimal
108163     ** plan might be chosen for queries like this:
108164     **
108165     **   CREATE TABLE t1(a, b);
108166     **   CREATE TABLE t2(c, d);
108167     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
108168     **
108169     ** The best strategy is to iterate through table t1 first. However it
108170     ** is not possible to determine this with a simple greedy algorithm.
108171     ** Since the cost of a linear scan through table t2 is the same
108172     ** as the cost of a linear scan through table t1, a simple greedy
108173     ** algorithm may choose to use t2 for the outer loop, which is a much
108174     ** costlier approach.
108175     */
108176     nUnconstrained = 0;
108177     notIndexed = 0;
108178 
108179     /* The optimal scan check only occurs if there are two or more tables
108180     ** available to be reordered */
108181     if( iFrom==nTabList-1 ){
108182       ckOptimal = 0;  /* Common case of just one table in the FROM clause */
108183     }else{
108184       ckOptimal = -1;
108185       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
108186         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
108187         if( (m & sWBI.notValid)==0 ){
108188           if( j==iFrom ) iFrom++;
108189           continue;
108190         }
108191         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
108192         if( ++ckOptimal ) break;
108193         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
108194       }
108195     }
108196     assert( ckOptimal==0 || ckOptimal==1 );
108197 
108198     for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
108199       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
108200         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
108201           /* This break and one like it in the ckOptimal computation loop
108202           ** above prevent table reordering across LEFT and CROSS JOINs.
108203           ** The LEFT JOIN case is necessary for correctness.  The prohibition
108204           ** against reordering across a CROSS JOIN is an SQLite feature that
108205           ** allows the developer to control table reordering */
108206           break;
108207         }
108208         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
108209         if( (m & sWBI.notValid)==0 ){
108210           assert( j>iFrom );
108211           continue;
108212         }
108213         sWBI.notReady = (isOptimal ? m : sWBI.notValid);
108214         if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
108215 
108216         WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
108217                     j, sWBI.pSrc->pTab->zName, isOptimal));
108218         assert( sWBI.pSrc->pTab );
108219 #ifndef SQLITE_OMIT_VIRTUALTABLE
108220         if( IsVirtual(sWBI.pSrc->pTab) ){
108221           sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
108222           bestVirtualIndex(&sWBI);
108223         }else
108224 #endif
108225         {
108226           bestBtreeIndex(&sWBI);
108227         }
108228         assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
108229 
108230         /* If an INDEXED BY clause is present, then the plan must use that
108231         ** index if it uses any index at all */
108232         assert( sWBI.pSrc->pIndex==0
108233                   || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
108234                   || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
108235 
108236         if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
108237           notIndexed |= m;
108238         }
108239         if( isOptimal ){
108240           pWInfo->a[j].rOptCost = sWBI.cost.rCost;
108241         }else if( ckOptimal ){
108242           /* If two or more tables have nearly the same outer loop cost, but
108243           ** very different inner loop (optimal) cost, we want to choose
108244           ** for the outer loop that table which benefits the least from
108245           ** being in the inner loop.  The following code scales the
108246           ** outer loop cost estimate to accomplish that. */
108247           WHERETRACE(("   scaling cost from %.1f to %.1f\n",
108248                       sWBI.cost.rCost,
108249                       sWBI.cost.rCost/pWInfo->a[j].rOptCost));
108250           sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
108251         }
108252 
108253         /* Conditions under which this table becomes the best so far:
108254         **
108255         **   (1) The table must not depend on other tables that have not
108256         **       yet run.  (In other words, it must not depend on tables
108257         **       in inner loops.)
108258         **
108259         **   (2) (This rule was removed on 2012-11-09.  The scaling of the
108260         **       cost using the optimal scan cost made this rule obsolete.)
108261         **
108262         **   (3) All tables have an INDEXED BY clause or this table lacks an
108263         **       INDEXED BY clause or this table uses the specific
108264         **       index specified by its INDEXED BY clause.  This rule ensures
108265         **       that a best-so-far is always selected even if an impossible
108266         **       combination of INDEXED BY clauses are given.  The error
108267         **       will be detected and relayed back to the application later.
108268         **       The NEVER() comes about because rule (2) above prevents
108269         **       An indexable full-table-scan from reaching rule (3).
108270         **
108271         **   (4) The plan cost must be lower than prior plans, where "cost"
108272         **       is defined by the compareCost() function above.
108273         */
108274         if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
108275             && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
108276                 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
108277             && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
108278         ){
108279           WHERETRACE(("   === table %d (%s) is best so far\n"
108280                       "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
108281                       j, sWBI.pSrc->pTab->zName,
108282                       sWBI.cost.rCost, sWBI.cost.plan.nRow,
108283                       sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
108284           bestPlan = sWBI.cost;
108285           bestJ = j;
108286         }
108287 
108288         /* In a join like "w JOIN x LEFT JOIN y JOIN z"  make sure that
108289         ** table y (and not table z) is always the next inner loop inside
108290         ** of table x. */
108291         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
108292       }
108293     }
108294     assert( bestJ>=0 );
108295     assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
108296     assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
108297     testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
108298     testcase( bestJ>iFrom && bestJ<nTabList-1
108299                           && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
108300     WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
108301                 "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
108302                 bestJ, pTabList->a[bestJ].pTab->zName,
108303                 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
108304                 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
108305     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
108306       assert( pWInfo->eDistinct==0 );
108307       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
108308     }
108309     andFlags &= bestPlan.plan.wsFlags;
108310     pLevel->plan = bestPlan.plan;
108311     pLevel->iTabCur = pTabList->a[bestJ].iCursor;
108312     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
108313     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
108314     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
108315       if( (wctrlFlags & WHERE_ONETABLE_ONLY)
108316        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
108317       ){
108318         pLevel->iIdxCur = iIdxCur;
108319       }else{
108320         pLevel->iIdxCur = pParse->nTab++;
108321       }
108322     }else{
108323       pLevel->iIdxCur = -1;
108324     }
108325     sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
108326     pLevel->iFrom = (u8)bestJ;
108327     if( bestPlan.plan.nRow>=(double)1 ){
108328       pParse->nQueryLoop *= bestPlan.plan.nRow;
108329     }
108330 
108331     /* Check that if the table scanned by this loop iteration had an
108332     ** INDEXED BY clause attached to it, that the named index is being
108333     ** used for the scan. If not, then query compilation has failed.
108334     ** Return an error.
108335     */
108336     pIdx = pTabList->a[bestJ].pIndex;
108337     if( pIdx ){
108338       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
108339         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
108340         goto whereBeginError;
108341       }else{
108342         /* If an INDEXED BY clause is used, the bestIndex() function is
108343         ** guaranteed to find the index specified in the INDEXED BY clause
108344         ** if it find an index at all. */
108345         assert( bestPlan.plan.u.pIdx==pIdx );
108346       }
108347     }
108348   }
108349   WHERETRACE(("*** Optimizer Finished ***\n"));
108350   if( pParse->nErr || db->mallocFailed ){
108351     goto whereBeginError;
108352   }
108353   if( nTabList ){
108354     pLevel--;
108355     pWInfo->nOBSat = pLevel->plan.nOBSat;
108356   }else{
108357     pWInfo->nOBSat = 0;
108358   }
108359 
108360   /* If the total query only selects a single row, then the ORDER BY
108361   ** clause is irrelevant.
108362   */
108363   if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
108364     assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
108365     pWInfo->nOBSat = pOrderBy->nExpr;
108366   }
108367 
108368   /* If the caller is an UPDATE or DELETE statement that is requesting
108369   ** to use a one-pass algorithm, determine if this is appropriate.
108370   ** The one-pass algorithm only works if the WHERE clause constraints
108371   ** the statement to update a single row.
108372   */
108373   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
108374   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
108375     pWInfo->okOnePass = 1;
108376     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
108377   }
108378 
108379   /* Open all tables in the pTabList and any indices selected for
108380   ** searching those tables.
108381   */
108382   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
108383   notReady = ~(Bitmask)0;
108384   pWInfo->nRowOut = (double)1;
108385   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
108386     Table *pTab;     /* Table to open */
108387     int iDb;         /* Index of database containing table/index */
108388     struct SrcList_item *pTabItem;
108389 
108390     pTabItem = &pTabList->a[pLevel->iFrom];
108391     pTab = pTabItem->pTab;
108392     pWInfo->nRowOut *= pLevel->plan.nRow;
108393     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108394     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
108395       /* Do nothing */
108396     }else
108397 #ifndef SQLITE_OMIT_VIRTUALTABLE
108398     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108399       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
108400       int iCur = pTabItem->iCursor;
108401       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
108402     }else if( IsVirtual(pTab) ){
108403       /* noop */
108404     }else
108405 #endif
108406     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108407          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
108408       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
108409       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
108410       testcase( pTab->nCol==BMS-1 );
108411       testcase( pTab->nCol==BMS );
108412       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
108413         Bitmask b = pTabItem->colUsed;
108414         int n = 0;
108415         for(; b; b=b>>1, n++){}
108416         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
108417                             SQLITE_INT_TO_PTR(n), P4_INT32);
108418         assert( n<=pTab->nCol );
108419       }
108420     }else{
108421       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
108422     }
108423 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
108424     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
108425       constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
108426     }else
108427 #endif
108428     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
108429       Index *pIx = pLevel->plan.u.pIdx;
108430       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
108431       int iIndexCur = pLevel->iIdxCur;
108432       assert( pIx->pSchema==pTab->pSchema );
108433       assert( iIndexCur>=0 );
108434       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
108435                         (char*)pKey, P4_KEYINFO_HANDOFF);
108436       VdbeComment((v, "%s", pIx->zName));
108437     }
108438     sqlite3CodeVerifySchema(pParse, iDb);
108439     notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
108440   }
108441   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
108442   if( db->mallocFailed ) goto whereBeginError;
108443 
108444   /* Generate the code to do the search.  Each iteration of the for
108445   ** loop below generates code for a single nested loop of the VM
108446   ** program.
108447   */
108448   notReady = ~(Bitmask)0;
108449   for(ii=0; ii<nTabList; ii++){
108450     pLevel = &pWInfo->a[ii];
108451     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
108452     notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
108453     pWInfo->iContinue = pLevel->addrCont;
108454   }
108455 
108456 #ifdef SQLITE_TEST  /* For testing and debugging use only */
108457   /* Record in the query plan information about the current table
108458   ** and the index used to access it (if any).  If the table itself
108459   ** is not used, its name is just '{}'.  If no index is used
108460   ** the index is listed as "{}".  If the primary key is used the
108461   ** index name is '*'.
108462   */
108463   for(ii=0; ii<nTabList; ii++){
108464     char *z;
108465     int n;
108466     int w;
108467     struct SrcList_item *pTabItem;
108468 
108469     pLevel = &pWInfo->a[ii];
108470     w = pLevel->plan.wsFlags;
108471     pTabItem = &pTabList->a[pLevel->iFrom];
108472     z = pTabItem->zAlias;
108473     if( z==0 ) z = pTabItem->pTab->zName;
108474     n = sqlite3Strlen30(z);
108475     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
108476       if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
108477         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
108478         nQPlan += 2;
108479       }else{
108480         memcpy(&sqlite3_query_plan[nQPlan], z, n);
108481         nQPlan += n;
108482       }
108483       sqlite3_query_plan[nQPlan++] = ' ';
108484     }
108485     testcase( w & WHERE_ROWID_EQ );
108486     testcase( w & WHERE_ROWID_RANGE );
108487     if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108488       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
108489       nQPlan += 2;
108490     }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
108491       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
108492       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
108493         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
108494         nQPlan += n;
108495         sqlite3_query_plan[nQPlan++] = ' ';
108496       }
108497     }else{
108498       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
108499       nQPlan += 3;
108500     }
108501   }
108502   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
108503     sqlite3_query_plan[--nQPlan] = 0;
108504   }
108505   sqlite3_query_plan[nQPlan] = 0;
108506   nQPlan = 0;
108507 #endif /* SQLITE_TEST // Testing and debugging use only */
108508 
108509   /* Record the continuation address in the WhereInfo structure.  Then
108510   ** clean up and return.
108511   */
108512   return pWInfo;
108513 
108514   /* Jump here if malloc fails */
108515 whereBeginError:
108516   if( pWInfo ){
108517     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
108518     whereInfoFree(db, pWInfo);
108519   }
108520   return 0;
108521 }
108522 
108523 /*
108524 ** Generate the end of the WHERE loop.  See comments on
108525 ** sqlite3WhereBegin() for additional information.
108526 */
108527 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
108528   Parse *pParse = pWInfo->pParse;
108529   Vdbe *v = pParse->pVdbe;
108530   int i;
108531   WhereLevel *pLevel;
108532   SrcList *pTabList = pWInfo->pTabList;
108533   sqlite3 *db = pParse->db;
108534 
108535   /* Generate loop termination code.
108536   */
108537   sqlite3ExprCacheClear(pParse);
108538   for(i=pWInfo->nLevel-1; i>=0; i--){
108539     pLevel = &pWInfo->a[i];
108540     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
108541     if( pLevel->op!=OP_Noop ){
108542       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
108543       sqlite3VdbeChangeP5(v, pLevel->p5);
108544     }
108545     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
108546       struct InLoop *pIn;
108547       int j;
108548       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
108549       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
108550         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
108551         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
108552         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
108553       }
108554       sqlite3DbFree(db, pLevel->u.in.aInLoop);
108555     }
108556     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
108557     if( pLevel->iLeftJoin ){
108558       int addr;
108559       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
108560       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108561            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
108562       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
108563         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
108564       }
108565       if( pLevel->iIdxCur>=0 ){
108566         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
108567       }
108568       if( pLevel->op==OP_Return ){
108569         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
108570       }else{
108571         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
108572       }
108573       sqlite3VdbeJumpHere(v, addr);
108574     }
108575   }
108576 
108577   /* The "break" point is here, just past the end of the outer loop.
108578   ** Set it.
108579   */
108580   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
108581 
108582   /* Close all of the cursors that were opened by sqlite3WhereBegin.
108583   */
108584   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
108585   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
108586     Index *pIdx = 0;
108587     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
108588     Table *pTab = pTabItem->pTab;
108589     assert( pTab!=0 );
108590     if( (pTab->tabFlags & TF_Ephemeral)==0
108591      && pTab->pSelect==0
108592      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
108593     ){
108594       int ws = pLevel->plan.wsFlags;
108595       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
108596         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
108597       }
108598       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
108599         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
108600       }
108601     }
108602 
108603     /* If this scan uses an index, make code substitutions to read data
108604     ** from the index in preference to the table. Sometimes, this means
108605     ** the table need never be read from. This is a performance boost,
108606     ** as the vdbe level waits until the table is read before actually
108607     ** seeking the table cursor to the record corresponding to the current
108608     ** position in the index.
108609     **
108610     ** Calls to the code generator in between sqlite3WhereBegin and
108611     ** sqlite3WhereEnd will have created code that references the table
108612     ** directly.  This loop scans all that code looking for opcodes
108613     ** that reference the table and converts them into opcodes that
108614     ** reference the index.
108615     */
108616     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
108617       pIdx = pLevel->plan.u.pIdx;
108618     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108619       pIdx = pLevel->u.pCovidx;
108620     }
108621     if( pIdx && !db->mallocFailed){
108622       int k, j, last;
108623       VdbeOp *pOp;
108624 
108625       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
108626       last = sqlite3VdbeCurrentAddr(v);
108627       for(k=pWInfo->iTop; k<last; k++, pOp++){
108628         if( pOp->p1!=pLevel->iTabCur ) continue;
108629         if( pOp->opcode==OP_Column ){
108630           for(j=0; j<pIdx->nColumn; j++){
108631             if( pOp->p2==pIdx->aiColumn[j] ){
108632               pOp->p2 = j;
108633               pOp->p1 = pLevel->iIdxCur;
108634               break;
108635             }
108636           }
108637           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
108638                || j<pIdx->nColumn );
108639         }else if( pOp->opcode==OP_Rowid ){
108640           pOp->p1 = pLevel->iIdxCur;
108641           pOp->opcode = OP_IdxRowid;
108642         }
108643       }
108644     }
108645   }
108646 
108647   /* Final cleanup
108648   */
108649   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
108650   whereInfoFree(db, pWInfo);
108651   return;
108652 }
108653 
108654 /************** End of where.c ***********************************************/
108655 /************** Begin file parse.c *******************************************/
108656 /* Driver template for the LEMON parser generator.
108657 ** The author disclaims copyright to this source code.
108658 **
108659 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
108660 ** The only modifications are the addition of a couple of NEVER()
108661 ** macros to disable tests that are needed in the case of a general
108662 ** LALR(1) grammar but which are always false in the
108663 ** specific grammar used by SQLite.
108664 */
108665 /* First off, code is included that follows the "include" declaration
108666 ** in the input grammar file. */
108667 /* #include <stdio.h> */
108668 
108669 
108670 /*
108671 ** Disable all error recovery processing in the parser push-down
108672 ** automaton.
108673 */
108674 #define YYNOERRORRECOVERY 1
108675 
108676 /*
108677 ** Make yytestcase() the same as testcase()
108678 */
108679 #define yytestcase(X) testcase(X)
108680 
108681 /*
108682 ** An instance of this structure holds information about the
108683 ** LIMIT clause of a SELECT statement.
108684 */
108685 struct LimitVal {
108686   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
108687   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
108688 };
108689 
108690 /*
108691 ** An instance of this structure is used to store the LIKE,
108692 ** GLOB, NOT LIKE, and NOT GLOB operators.
108693 */
108694 struct LikeOp {
108695   Token eOperator;  /* "like" or "glob" or "regexp" */
108696   int bNot;         /* True if the NOT keyword is present */
108697 };
108698 
108699 /*
108700 ** An instance of the following structure describes the event of a
108701 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
108702 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
108703 **
108704 **      UPDATE ON (a,b,c)
108705 **
108706 ** Then the "b" IdList records the list "a,b,c".
108707 */
108708 struct TrigEvent { int a; IdList * b; };
108709 
108710 /*
108711 ** An instance of this structure holds the ATTACH key and the key type.
108712 */
108713 struct AttachKey { int type;  Token key; };
108714 
108715 /*
108716 ** One or more VALUES claues
108717 */
108718 struct ValueList {
108719   ExprList *pList;
108720   Select *pSelect;
108721 };
108722 
108723 
108724   /* This is a utility routine used to set the ExprSpan.zStart and
108725   ** ExprSpan.zEnd values of pOut so that the span covers the complete
108726   ** range of text beginning with pStart and going to the end of pEnd.
108727   */
108728   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
108729     pOut->zStart = pStart->z;
108730     pOut->zEnd = &pEnd->z[pEnd->n];
108731   }
108732 
108733   /* Construct a new Expr object from a single identifier.  Use the
108734   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
108735   ** that created the expression.
108736   */
108737   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
108738     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
108739     pOut->zStart = pValue->z;
108740     pOut->zEnd = &pValue->z[pValue->n];
108741   }
108742 
108743   /* This routine constructs a binary expression node out of two ExprSpan
108744   ** objects and uses the result to populate a new ExprSpan object.
108745   */
108746   static void spanBinaryExpr(
108747     ExprSpan *pOut,     /* Write the result here */
108748     Parse *pParse,      /* The parsing context.  Errors accumulate here */
108749     int op,             /* The binary operation */
108750     ExprSpan *pLeft,    /* The left operand */
108751     ExprSpan *pRight    /* The right operand */
108752   ){
108753     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
108754     pOut->zStart = pLeft->zStart;
108755     pOut->zEnd = pRight->zEnd;
108756   }
108757 
108758   /* Construct an expression node for a unary postfix operator
108759   */
108760   static void spanUnaryPostfix(
108761     ExprSpan *pOut,        /* Write the new expression node here */
108762     Parse *pParse,         /* Parsing context to record errors */
108763     int op,                /* The operator */
108764     ExprSpan *pOperand,    /* The operand */
108765     Token *pPostOp         /* The operand token for setting the span */
108766   ){
108767     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
108768     pOut->zStart = pOperand->zStart;
108769     pOut->zEnd = &pPostOp->z[pPostOp->n];
108770   }
108771 
108772   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
108773   ** unary TK_ISNULL or TK_NOTNULL expression. */
108774   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
108775     sqlite3 *db = pParse->db;
108776     if( db->mallocFailed==0 && pY->op==TK_NULL ){
108777       pA->op = (u8)op;
108778       sqlite3ExprDelete(db, pA->pRight);
108779       pA->pRight = 0;
108780     }
108781   }
108782 
108783   /* Construct an expression node for a unary prefix operator
108784   */
108785   static void spanUnaryPrefix(
108786     ExprSpan *pOut,        /* Write the new expression node here */
108787     Parse *pParse,         /* Parsing context to record errors */
108788     int op,                /* The operator */
108789     ExprSpan *pOperand,    /* The operand */
108790     Token *pPreOp         /* The operand token for setting the span */
108791   ){
108792     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
108793     pOut->zStart = pPreOp->z;
108794     pOut->zEnd = pOperand->zEnd;
108795   }
108796 /* Next is all token values, in a form suitable for use by makeheaders.
108797 ** This section will be null unless lemon is run with the -m switch.
108798 */
108799 /*
108800 ** These constants (all generated automatically by the parser generator)
108801 ** specify the various kinds of tokens (terminals) that the parser
108802 ** understands.
108803 **
108804 ** Each symbol here is a terminal symbol in the grammar.
108805 */
108806 /* Make sure the INTERFACE macro is defined.
108807 */
108808 #ifndef INTERFACE
108809 # define INTERFACE 1
108810 #endif
108811 /* The next thing included is series of defines which control
108812 ** various aspects of the generated parser.
108813 **    YYCODETYPE         is the data type used for storing terminal
108814 **                       and nonterminal numbers.  "unsigned char" is
108815 **                       used if there are fewer than 250 terminals
108816 **                       and nonterminals.  "int" is used otherwise.
108817 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
108818 **                       to no legal terminal or nonterminal number.  This
108819 **                       number is used to fill in empty slots of the hash
108820 **                       table.
108821 **    YYFALLBACK         If defined, this indicates that one or more tokens
108822 **                       have fall-back values which should be used if the
108823 **                       original value of the token will not parse.
108824 **    YYACTIONTYPE       is the data type used for storing terminal
108825 **                       and nonterminal numbers.  "unsigned char" is
108826 **                       used if there are fewer than 250 rules and
108827 **                       states combined.  "int" is used otherwise.
108828 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
108829 **                       directly to the parser from the tokenizer.
108830 **    YYMINORTYPE        is the data type used for all minor tokens.
108831 **                       This is typically a union of many types, one of
108832 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
108833 **                       for base tokens is called "yy0".
108834 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
108835 **                       zero the stack is dynamically sized using realloc()
108836 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
108837 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
108838 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
108839 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
108840 **    YYNSTATE           the combined number of states.
108841 **    YYNRULE            the number of rules in the grammar
108842 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
108843 **                       defined, then do no error processing.
108844 */
108845 #define YYCODETYPE unsigned char
108846 #define YYNOCODE 251
108847 #define YYACTIONTYPE unsigned short int
108848 #define YYWILDCARD 67
108849 #define sqlite3ParserTOKENTYPE Token
108850 typedef union {
108851   int yyinit;
108852   sqlite3ParserTOKENTYPE yy0;
108853   struct LimitVal yy64;
108854   Expr* yy122;
108855   Select* yy159;
108856   IdList* yy180;
108857   struct {int value; int mask;} yy207;
108858   u8 yy258;
108859   u16 yy305;
108860   struct LikeOp yy318;
108861   TriggerStep* yy327;
108862   ExprSpan yy342;
108863   SrcList* yy347;
108864   int yy392;
108865   struct TrigEvent yy410;
108866   ExprList* yy442;
108867   struct ValueList yy487;
108868 } YYMINORTYPE;
108869 #ifndef YYSTACKDEPTH
108870 #define YYSTACKDEPTH 100
108871 #endif
108872 #define sqlite3ParserARG_SDECL Parse *pParse;
108873 #define sqlite3ParserARG_PDECL ,Parse *pParse
108874 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
108875 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
108876 #define YYNSTATE 627
108877 #define YYNRULE 327
108878 #define YYFALLBACK 1
108879 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
108880 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
108881 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
108882 
108883 /* The yyzerominor constant is used to initialize instances of
108884 ** YYMINORTYPE objects to zero. */
108885 static const YYMINORTYPE yyzerominor = { 0 };
108886 
108887 /* Define the yytestcase() macro to be a no-op if is not already defined
108888 ** otherwise.
108889 **
108890 ** Applications can choose to define yytestcase() in the %include section
108891 ** to a macro that can assist in verifying code coverage.  For production
108892 ** code the yytestcase() macro should be turned off.  But it is useful
108893 ** for testing.
108894 */
108895 #ifndef yytestcase
108896 # define yytestcase(X)
108897 #endif
108898 
108899 
108900 /* Next are the tables used to determine what action to take based on the
108901 ** current state and lookahead token.  These tables are used to implement
108902 ** functions that take a state number and lookahead value and return an
108903 ** action integer.
108904 **
108905 ** Suppose the action integer is N.  Then the action is determined as
108906 ** follows
108907 **
108908 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
108909 **                                      token onto the stack and goto state N.
108910 **
108911 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
108912 **
108913 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
108914 **
108915 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
108916 **
108917 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
108918 **                                      slots in the yy_action[] table.
108919 **
108920 ** The action table is constructed as a single large table named yy_action[].
108921 ** Given state S and lookahead X, the action is computed as
108922 **
108923 **      yy_action[ yy_shift_ofst[S] + X ]
108924 **
108925 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
108926 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
108927 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
108928 ** and that yy_default[S] should be used instead.
108929 **
108930 ** The formula above is for computing the action when the lookahead is
108931 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
108932 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
108933 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
108934 ** YY_SHIFT_USE_DFLT.
108935 **
108936 ** The following are the tables generated in this section:
108937 **
108938 **  yy_action[]        A single table containing all actions.
108939 **  yy_lookahead[]     A table containing the lookahead for each entry in
108940 **                     yy_action.  Used to detect hash collisions.
108941 **  yy_shift_ofst[]    For each state, the offset into yy_action for
108942 **                     shifting terminals.
108943 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
108944 **                     shifting non-terminals after a reduce.
108945 **  yy_default[]       Default action for each state.
108946 */
108947 #define YY_ACTTAB_COUNT (1564)
108948 static const YYACTIONTYPE yy_action[] = {
108949  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
108950  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
108951  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
108952  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
108953  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
108954  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108955  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
108956  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
108957  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108958  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
108959  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
108960  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
108961  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
108962  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
108963  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
108964  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
108965  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
108966  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
108967  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
108968  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
108969  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
108970  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108971  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
108972  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
108973  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
108974  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
108975  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
108976  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
108977  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
108978  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
108979  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
108980  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
108981  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
108982  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
108983  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
108984  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
108985  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
108986  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
108987  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
108988  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
108989  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
108990  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
108991  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
108992  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
108993  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
108994  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
108995  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
108996  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
108997  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
108998  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
108999  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
109000  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
109001  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
109002  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
109003  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
109004  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
109005  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
109006  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109007  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109008  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
109009  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
109010  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
109011  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
109012  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
109013  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
109014  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
109015  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
109016  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
109017  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
109018  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
109019  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
109020  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
109021  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
109022  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109023  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
109024  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
109025  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
109026  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
109027  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
109028  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109029  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
109030  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
109031  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
109032  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
109033  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
109034  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
109035  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
109036  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
109037  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
109038  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
109039  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
109040  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
109041  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
109042  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
109043  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109044  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109045  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
109046  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
109047  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
109048  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
109049  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
109050  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
109051  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
109052  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
109053  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
109054  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
109055  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
109056  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
109057  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
109058  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
109059  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
109060  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
109061  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
109062  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
109063  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
109064  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
109065  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109066  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
109067  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
109068  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
109069  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
109070  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
109071  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
109072  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
109073  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
109074  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
109075  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
109076  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
109077  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
109078  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
109079  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
109080  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
109081  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
109082  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
109083  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
109084  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
109085  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
109086  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
109087  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
109088  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
109089  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
109090  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
109091  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
109092  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
109093  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
109094  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
109095  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
109096  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
109097  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
109098  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
109099  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
109100  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
109101  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
109102  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
109103  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
109104  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
109105  /*  1560 */   295,  498,  956,  488,
109106 };
109107 static const YYCODETYPE yy_lookahead[] = {
109108  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
109109  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
109110  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
109111  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
109112  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
109113  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109114  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
109115  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
109116  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109117  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
109118  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
109119  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
109120  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
109121  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
109122  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
109123  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
109124  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
109125  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
109126  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
109127  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
109128  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109129  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109130  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
109131  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
109132  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
109133  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
109134  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
109135  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109136  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
109137  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
109138  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
109139  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
109140  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
109141  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
109142  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
109143  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
109144  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109145  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
109146  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
109147  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
109148  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
109149  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
109150  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109151  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
109152  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
109153  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
109154  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
109155  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
109156  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
109157  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
109158  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
109159  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
109160  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
109161  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
109162  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
109163  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
109164  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
109165  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109166  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109167  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
109168  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
109169  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
109170  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
109171  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
109172  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109173  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
109174  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
109175  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
109176  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
109177  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
109178  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
109179  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
109180  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
109181  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109182  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
109183  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
109184  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
109185  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
109186  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
109187  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109188  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
109189  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
109190  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
109191  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
109192  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
109193  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
109194  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
109195  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
109196  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
109197  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
109198  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
109199  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
109200  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
109201  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
109202  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
109203  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
109204  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
109205  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
109206  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
109207  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
109208  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
109209  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
109210  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
109211  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
109212  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
109213  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
109214  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
109215  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
109216  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
109217  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
109218  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
109219  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
109220  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
109221  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
109222  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
109223  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
109224  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
109225  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
109226  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
109227  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
109228  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
109229  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
109230  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
109231  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
109232  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
109233  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
109234  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
109235  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
109236  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
109237  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
109238  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
109239  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
109240  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
109241  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
109242  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
109243  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
109244  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
109245  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
109246  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
109247  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
109248  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
109249  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
109250  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
109251  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
109252  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
109253  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
109254  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
109255  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
109256  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
109257  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
109258  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
109259  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
109260  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
109261  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
109262  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
109263  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
109264  /*  1560 */   195,  182,  250,  186,
109265 };
109266 #define YY_SHIFT_USE_DFLT (-70)
109267 #define YY_SHIFT_COUNT (416)
109268 #define YY_SHIFT_MIN   (-69)
109269 #define YY_SHIFT_MAX   (1487)
109270 static const short yy_shift_ofst[] = {
109271  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
109272  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
109273  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109274  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109275  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
109276  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
109277  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
109278  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
109279  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
109280  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
109281  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
109282  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109283  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
109284  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
109285  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
109286  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109287  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109288  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
109289  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
109290  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
109291  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
109292  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
109293  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
109294  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
109295  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
109296  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
109297  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
109298  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
109299  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
109300  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
109301  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
109302  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
109303  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
109304  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
109305  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
109306  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
109307  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
109308  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
109309  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
109310  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
109311  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
109312  /*   410 */    92,   75,   45,  114,   25,   11,    5,
109313 };
109314 #define YY_REDUCE_USE_DFLT (-169)
109315 #define YY_REDUCE_COUNT (308)
109316 #define YY_REDUCE_MIN   (-168)
109317 #define YY_REDUCE_MAX   (1391)
109318 static const short yy_reduce_ofst[] = {
109319  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
109320  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
109321  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
109322  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
109323  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
109324  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
109325  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
109326  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109327  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109328  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
109329  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
109330  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
109331  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
109332  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
109333  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
109334  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
109335  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
109336  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
109337  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
109338  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
109339  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
109340  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
109341  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
109342  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
109343  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
109344  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
109345  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
109346  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
109347  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
109348  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
109349  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
109350 };
109351 static const YYACTIONTYPE yy_default[] = {
109352  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
109353  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
109354  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109355  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109356  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109357  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109358  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
109359  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
109360  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
109361  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
109362  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
109363  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109364  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
109365  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
109366  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109367  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
109368  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109369  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109370  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
109371  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109372  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
109373  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
109374  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
109375  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
109376  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
109377  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
109378  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
109379  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
109380  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
109381  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
109382  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
109383  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
109384  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
109385  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
109386  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
109387  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
109388  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
109389  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109390  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
109391  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
109392  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
109393  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
109394  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
109395  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
109396  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
109397  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
109398  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
109399  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
109400  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
109401  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
109402  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
109403  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
109404  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
109405  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
109406  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
109407  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
109408  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
109409  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
109410  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
109411  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
109412  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
109413  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
109414  /*   620 */   665,  639,  636,  635,  631,  630,  628,
109415 };
109416 
109417 /* The next table maps tokens into fallback tokens.  If a construct
109418 ** like the following:
109419 **
109420 **      %fallback ID X Y Z.
109421 **
109422 ** appears in the grammar, then ID becomes a fallback token for X, Y,
109423 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
109424 ** but it does not parse, the type of the token is changed to ID and
109425 ** the parse is retried before an error is thrown.
109426 */
109427 #ifdef YYFALLBACK
109428 static const YYCODETYPE yyFallback[] = {
109429     0,  /*          $ => nothing */
109430     0,  /*       SEMI => nothing */
109431    26,  /*    EXPLAIN => ID */
109432    26,  /*      QUERY => ID */
109433    26,  /*       PLAN => ID */
109434    26,  /*      BEGIN => ID */
109435     0,  /* TRANSACTION => nothing */
109436    26,  /*   DEFERRED => ID */
109437    26,  /*  IMMEDIATE => ID */
109438    26,  /*  EXCLUSIVE => ID */
109439     0,  /*     COMMIT => nothing */
109440    26,  /*        END => ID */
109441    26,  /*   ROLLBACK => ID */
109442    26,  /*  SAVEPOINT => ID */
109443    26,  /*    RELEASE => ID */
109444     0,  /*         TO => nothing */
109445     0,  /*      TABLE => nothing */
109446     0,  /*     CREATE => nothing */
109447    26,  /*         IF => ID */
109448     0,  /*        NOT => nothing */
109449     0,  /*     EXISTS => nothing */
109450    26,  /*       TEMP => ID */
109451     0,  /*         LP => nothing */
109452     0,  /*         RP => nothing */
109453     0,  /*         AS => nothing */
109454     0,  /*      COMMA => nothing */
109455     0,  /*         ID => nothing */
109456     0,  /*    INDEXED => nothing */
109457    26,  /*      ABORT => ID */
109458    26,  /*     ACTION => ID */
109459    26,  /*      AFTER => ID */
109460    26,  /*    ANALYZE => ID */
109461    26,  /*        ASC => ID */
109462    26,  /*     ATTACH => ID */
109463    26,  /*     BEFORE => ID */
109464    26,  /*         BY => ID */
109465    26,  /*    CASCADE => ID */
109466    26,  /*       CAST => ID */
109467    26,  /*   COLUMNKW => ID */
109468    26,  /*   CONFLICT => ID */
109469    26,  /*   DATABASE => ID */
109470    26,  /*       DESC => ID */
109471    26,  /*     DETACH => ID */
109472    26,  /*       EACH => ID */
109473    26,  /*       FAIL => ID */
109474    26,  /*        FOR => ID */
109475    26,  /*     IGNORE => ID */
109476    26,  /*  INITIALLY => ID */
109477    26,  /*    INSTEAD => ID */
109478    26,  /*    LIKE_KW => ID */
109479    26,  /*      MATCH => ID */
109480    26,  /*         NO => ID */
109481    26,  /*        KEY => ID */
109482    26,  /*         OF => ID */
109483    26,  /*     OFFSET => ID */
109484    26,  /*     PRAGMA => ID */
109485    26,  /*      RAISE => ID */
109486    26,  /*    REPLACE => ID */
109487    26,  /*   RESTRICT => ID */
109488    26,  /*        ROW => ID */
109489    26,  /*    TRIGGER => ID */
109490    26,  /*     VACUUM => ID */
109491    26,  /*       VIEW => ID */
109492    26,  /*    VIRTUAL => ID */
109493    26,  /*    REINDEX => ID */
109494    26,  /*     RENAME => ID */
109495    26,  /*   CTIME_KW => ID */
109496 };
109497 #endif /* YYFALLBACK */
109498 
109499 /* The following structure represents a single element of the
109500 ** parser's stack.  Information stored includes:
109501 **
109502 **   +  The state number for the parser at this level of the stack.
109503 **
109504 **   +  The value of the token stored at this level of the stack.
109505 **      (In other words, the "major" token.)
109506 **
109507 **   +  The semantic value stored at this level of the stack.  This is
109508 **      the information used by the action routines in the grammar.
109509 **      It is sometimes called the "minor" token.
109510 */
109511 struct yyStackEntry {
109512   YYACTIONTYPE stateno;  /* The state-number */
109513   YYCODETYPE major;      /* The major token value.  This is the code
109514                          ** number for the token at this stack level */
109515   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
109516                          ** is the value of the token  */
109517 };
109518 typedef struct yyStackEntry yyStackEntry;
109519 
109520 /* The state of the parser is completely contained in an instance of
109521 ** the following structure */
109522 struct yyParser {
109523   int yyidx;                    /* Index of top element in stack */
109524 #ifdef YYTRACKMAXSTACKDEPTH
109525   int yyidxMax;                 /* Maximum value of yyidx */
109526 #endif
109527   int yyerrcnt;                 /* Shifts left before out of the error */
109528   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
109529 #if YYSTACKDEPTH<=0
109530   int yystksz;                  /* Current side of the stack */
109531   yyStackEntry *yystack;        /* The parser's stack */
109532 #else
109533   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
109534 #endif
109535 };
109536 typedef struct yyParser yyParser;
109537 
109538 #ifndef NDEBUG
109539 /* #include <stdio.h> */
109540 static FILE *yyTraceFILE = 0;
109541 static char *yyTracePrompt = 0;
109542 #endif /* NDEBUG */
109543 
109544 #ifndef NDEBUG
109545 /*
109546 ** Turn parser tracing on by giving a stream to which to write the trace
109547 ** and a prompt to preface each trace message.  Tracing is turned off
109548 ** by making either argument NULL
109549 **
109550 ** Inputs:
109551 ** <ul>
109552 ** <li> A FILE* to which trace output should be written.
109553 **      If NULL, then tracing is turned off.
109554 ** <li> A prefix string written at the beginning of every
109555 **      line of trace output.  If NULL, then tracing is
109556 **      turned off.
109557 ** </ul>
109558 **
109559 ** Outputs:
109560 ** None.
109561 */
109562 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
109563   yyTraceFILE = TraceFILE;
109564   yyTracePrompt = zTracePrompt;
109565   if( yyTraceFILE==0 ) yyTracePrompt = 0;
109566   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
109567 }
109568 #endif /* NDEBUG */
109569 
109570 #ifndef NDEBUG
109571 /* For tracing shifts, the names of all terminals and nonterminals
109572 ** are required.  The following table supplies these names */
109573 static const char *const yyTokenName[] = {
109574   "$",             "SEMI",          "EXPLAIN",       "QUERY",
109575   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
109576   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
109577   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
109578   "TABLE",         "CREATE",        "IF",            "NOT",
109579   "EXISTS",        "TEMP",          "LP",            "RP",
109580   "AS",            "COMMA",         "ID",            "INDEXED",
109581   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
109582   "ASC",           "ATTACH",        "BEFORE",        "BY",
109583   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
109584   "DATABASE",      "DESC",          "DETACH",        "EACH",
109585   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
109586   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
109587   "KEY",           "OF",            "OFFSET",        "PRAGMA",
109588   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
109589   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
109590   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
109591   "OR",            "AND",           "IS",            "BETWEEN",
109592   "IN",            "ISNULL",        "NOTNULL",       "NE",
109593   "EQ",            "GT",            "LE",            "LT",
109594   "GE",            "ESCAPE",        "BITAND",        "BITOR",
109595   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
109596   "STAR",          "SLASH",         "REM",           "CONCAT",
109597   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
109598   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
109599   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
109600   "ON",            "INSERT",        "DELETE",        "UPDATE",
109601   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
109602   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
109603   "SELECT",        "DISTINCT",      "DOT",           "FROM",
109604   "JOIN",          "USING",         "ORDER",         "GROUP",
109605   "HAVING",        "LIMIT",         "WHERE",         "INTO",
109606   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
109607   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
109608   "THEN",          "ELSE",          "INDEX",         "ALTER",
109609   "ADD",           "error",         "input",         "cmdlist",
109610   "ecmd",          "explain",       "cmdx",          "cmd",
109611   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
109612   "create_table",  "create_table_args",  "createkw",      "temp",
109613   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
109614   "select",        "column",        "columnid",      "type",
109615   "carglist",      "id",            "ids",           "typetoken",
109616   "typename",      "signed",        "plus_num",      "minus_num",
109617   "ccons",         "term",          "expr",          "onconf",
109618   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",
109619   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
109620   "conslist",      "tconscomma",    "tcons",         "idxlist",
109621   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
109622   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
109623   "distinct",      "selcollist",    "from",          "where_opt",
109624   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
109625   "sclp",          "as",            "seltablist",    "stl_prefix",
109626   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
109627   "joinop2",       "inscollist",    "sortlist",      "nexprlist",
109628   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
109629   "exprlist",      "likeop",        "between_op",    "in_op",
109630   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
109631   "collate",       "nmnum",         "number",        "trigger_decl",
109632   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
109633   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
109634   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
109635   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
109636   "lp",            "anylist",
109637 };
109638 #endif /* NDEBUG */
109639 
109640 #ifndef NDEBUG
109641 /* For tracing reduce actions, the names of all rules are required.
109642 */
109643 static const char *const yyRuleName[] = {
109644  /*   0 */ "input ::= cmdlist",
109645  /*   1 */ "cmdlist ::= cmdlist ecmd",
109646  /*   2 */ "cmdlist ::= ecmd",
109647  /*   3 */ "ecmd ::= SEMI",
109648  /*   4 */ "ecmd ::= explain cmdx SEMI",
109649  /*   5 */ "explain ::=",
109650  /*   6 */ "explain ::= EXPLAIN",
109651  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
109652  /*   8 */ "cmdx ::= cmd",
109653  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
109654  /*  10 */ "trans_opt ::=",
109655  /*  11 */ "trans_opt ::= TRANSACTION",
109656  /*  12 */ "trans_opt ::= TRANSACTION nm",
109657  /*  13 */ "transtype ::=",
109658  /*  14 */ "transtype ::= DEFERRED",
109659  /*  15 */ "transtype ::= IMMEDIATE",
109660  /*  16 */ "transtype ::= EXCLUSIVE",
109661  /*  17 */ "cmd ::= COMMIT trans_opt",
109662  /*  18 */ "cmd ::= END trans_opt",
109663  /*  19 */ "cmd ::= ROLLBACK trans_opt",
109664  /*  20 */ "savepoint_opt ::= SAVEPOINT",
109665  /*  21 */ "savepoint_opt ::=",
109666  /*  22 */ "cmd ::= SAVEPOINT nm",
109667  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
109668  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
109669  /*  25 */ "cmd ::= create_table create_table_args",
109670  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
109671  /*  27 */ "createkw ::= CREATE",
109672  /*  28 */ "ifnotexists ::=",
109673  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
109674  /*  30 */ "temp ::= TEMP",
109675  /*  31 */ "temp ::=",
109676  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
109677  /*  33 */ "create_table_args ::= AS select",
109678  /*  34 */ "columnlist ::= columnlist COMMA column",
109679  /*  35 */ "columnlist ::= column",
109680  /*  36 */ "column ::= columnid type carglist",
109681  /*  37 */ "columnid ::= nm",
109682  /*  38 */ "id ::= ID",
109683  /*  39 */ "id ::= INDEXED",
109684  /*  40 */ "ids ::= ID|STRING",
109685  /*  41 */ "nm ::= id",
109686  /*  42 */ "nm ::= STRING",
109687  /*  43 */ "nm ::= JOIN_KW",
109688  /*  44 */ "type ::=",
109689  /*  45 */ "type ::= typetoken",
109690  /*  46 */ "typetoken ::= typename",
109691  /*  47 */ "typetoken ::= typename LP signed RP",
109692  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
109693  /*  49 */ "typename ::= ids",
109694  /*  50 */ "typename ::= typename ids",
109695  /*  51 */ "signed ::= plus_num",
109696  /*  52 */ "signed ::= minus_num",
109697  /*  53 */ "carglist ::= carglist ccons",
109698  /*  54 */ "carglist ::=",
109699  /*  55 */ "ccons ::= CONSTRAINT nm",
109700  /*  56 */ "ccons ::= DEFAULT term",
109701  /*  57 */ "ccons ::= DEFAULT LP expr RP",
109702  /*  58 */ "ccons ::= DEFAULT PLUS term",
109703  /*  59 */ "ccons ::= DEFAULT MINUS term",
109704  /*  60 */ "ccons ::= DEFAULT id",
109705  /*  61 */ "ccons ::= NULL onconf",
109706  /*  62 */ "ccons ::= NOT NULL onconf",
109707  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
109708  /*  64 */ "ccons ::= UNIQUE onconf",
109709  /*  65 */ "ccons ::= CHECK LP expr RP",
109710  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
109711  /*  67 */ "ccons ::= defer_subclause",
109712  /*  68 */ "ccons ::= COLLATE ids",
109713  /*  69 */ "autoinc ::=",
109714  /*  70 */ "autoinc ::= AUTOINCR",
109715  /*  71 */ "refargs ::=",
109716  /*  72 */ "refargs ::= refargs refarg",
109717  /*  73 */ "refarg ::= MATCH nm",
109718  /*  74 */ "refarg ::= ON INSERT refact",
109719  /*  75 */ "refarg ::= ON DELETE refact",
109720  /*  76 */ "refarg ::= ON UPDATE refact",
109721  /*  77 */ "refact ::= SET NULL",
109722  /*  78 */ "refact ::= SET DEFAULT",
109723  /*  79 */ "refact ::= CASCADE",
109724  /*  80 */ "refact ::= RESTRICT",
109725  /*  81 */ "refact ::= NO ACTION",
109726  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
109727  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
109728  /*  84 */ "init_deferred_pred_opt ::=",
109729  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
109730  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
109731  /*  87 */ "conslist_opt ::=",
109732  /*  88 */ "conslist_opt ::= COMMA conslist",
109733  /*  89 */ "conslist ::= conslist tconscomma tcons",
109734  /*  90 */ "conslist ::= tcons",
109735  /*  91 */ "tconscomma ::= COMMA",
109736  /*  92 */ "tconscomma ::=",
109737  /*  93 */ "tcons ::= CONSTRAINT nm",
109738  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
109739  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
109740  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
109741  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
109742  /*  98 */ "defer_subclause_opt ::=",
109743  /*  99 */ "defer_subclause_opt ::= defer_subclause",
109744  /* 100 */ "onconf ::=",
109745  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
109746  /* 102 */ "orconf ::=",
109747  /* 103 */ "orconf ::= OR resolvetype",
109748  /* 104 */ "resolvetype ::= raisetype",
109749  /* 105 */ "resolvetype ::= IGNORE",
109750  /* 106 */ "resolvetype ::= REPLACE",
109751  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
109752  /* 108 */ "ifexists ::= IF EXISTS",
109753  /* 109 */ "ifexists ::=",
109754  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
109755  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
109756  /* 112 */ "cmd ::= select",
109757  /* 113 */ "select ::= oneselect",
109758  /* 114 */ "select ::= select multiselect_op oneselect",
109759  /* 115 */ "multiselect_op ::= UNION",
109760  /* 116 */ "multiselect_op ::= UNION ALL",
109761  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
109762  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
109763  /* 119 */ "distinct ::= DISTINCT",
109764  /* 120 */ "distinct ::= ALL",
109765  /* 121 */ "distinct ::=",
109766  /* 122 */ "sclp ::= selcollist COMMA",
109767  /* 123 */ "sclp ::=",
109768  /* 124 */ "selcollist ::= sclp expr as",
109769  /* 125 */ "selcollist ::= sclp STAR",
109770  /* 126 */ "selcollist ::= sclp nm DOT STAR",
109771  /* 127 */ "as ::= AS nm",
109772  /* 128 */ "as ::= ids",
109773  /* 129 */ "as ::=",
109774  /* 130 */ "from ::=",
109775  /* 131 */ "from ::= FROM seltablist",
109776  /* 132 */ "stl_prefix ::= seltablist joinop",
109777  /* 133 */ "stl_prefix ::=",
109778  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
109779  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
109780  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
109781  /* 137 */ "dbnm ::=",
109782  /* 138 */ "dbnm ::= DOT nm",
109783  /* 139 */ "fullname ::= nm dbnm",
109784  /* 140 */ "joinop ::= COMMA|JOIN",
109785  /* 141 */ "joinop ::= JOIN_KW JOIN",
109786  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
109787  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
109788  /* 144 */ "on_opt ::= ON expr",
109789  /* 145 */ "on_opt ::=",
109790  /* 146 */ "indexed_opt ::=",
109791  /* 147 */ "indexed_opt ::= INDEXED BY nm",
109792  /* 148 */ "indexed_opt ::= NOT INDEXED",
109793  /* 149 */ "using_opt ::= USING LP inscollist RP",
109794  /* 150 */ "using_opt ::=",
109795  /* 151 */ "orderby_opt ::=",
109796  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
109797  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
109798  /* 154 */ "sortlist ::= expr sortorder",
109799  /* 155 */ "sortorder ::= ASC",
109800  /* 156 */ "sortorder ::= DESC",
109801  /* 157 */ "sortorder ::=",
109802  /* 158 */ "groupby_opt ::=",
109803  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
109804  /* 160 */ "having_opt ::=",
109805  /* 161 */ "having_opt ::= HAVING expr",
109806  /* 162 */ "limit_opt ::=",
109807  /* 163 */ "limit_opt ::= LIMIT expr",
109808  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
109809  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
109810  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
109811  /* 167 */ "where_opt ::=",
109812  /* 168 */ "where_opt ::= WHERE expr",
109813  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
109814  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
109815  /* 171 */ "setlist ::= nm EQ expr",
109816  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
109817  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
109818  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
109819  /* 175 */ "insert_cmd ::= INSERT orconf",
109820  /* 176 */ "insert_cmd ::= REPLACE",
109821  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
109822  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
109823  /* 179 */ "inscollist_opt ::=",
109824  /* 180 */ "inscollist_opt ::= LP inscollist RP",
109825  /* 181 */ "inscollist ::= inscollist COMMA nm",
109826  /* 182 */ "inscollist ::= nm",
109827  /* 183 */ "expr ::= term",
109828  /* 184 */ "expr ::= LP expr RP",
109829  /* 185 */ "term ::= NULL",
109830  /* 186 */ "expr ::= id",
109831  /* 187 */ "expr ::= JOIN_KW",
109832  /* 188 */ "expr ::= nm DOT nm",
109833  /* 189 */ "expr ::= nm DOT nm DOT nm",
109834  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
109835  /* 191 */ "term ::= STRING",
109836  /* 192 */ "expr ::= REGISTER",
109837  /* 193 */ "expr ::= VARIABLE",
109838  /* 194 */ "expr ::= expr COLLATE ids",
109839  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
109840  /* 196 */ "expr ::= ID LP distinct exprlist RP",
109841  /* 197 */ "expr ::= ID LP STAR RP",
109842  /* 198 */ "term ::= CTIME_KW",
109843  /* 199 */ "expr ::= expr AND expr",
109844  /* 200 */ "expr ::= expr OR expr",
109845  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
109846  /* 202 */ "expr ::= expr EQ|NE expr",
109847  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
109848  /* 204 */ "expr ::= expr PLUS|MINUS expr",
109849  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
109850  /* 206 */ "expr ::= expr CONCAT expr",
109851  /* 207 */ "likeop ::= LIKE_KW",
109852  /* 208 */ "likeop ::= NOT LIKE_KW",
109853  /* 209 */ "likeop ::= MATCH",
109854  /* 210 */ "likeop ::= NOT MATCH",
109855  /* 211 */ "expr ::= expr likeop expr",
109856  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
109857  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
109858  /* 214 */ "expr ::= expr NOT NULL",
109859  /* 215 */ "expr ::= expr IS expr",
109860  /* 216 */ "expr ::= expr IS NOT expr",
109861  /* 217 */ "expr ::= NOT expr",
109862  /* 218 */ "expr ::= BITNOT expr",
109863  /* 219 */ "expr ::= MINUS expr",
109864  /* 220 */ "expr ::= PLUS expr",
109865  /* 221 */ "between_op ::= BETWEEN",
109866  /* 222 */ "between_op ::= NOT BETWEEN",
109867  /* 223 */ "expr ::= expr between_op expr AND expr",
109868  /* 224 */ "in_op ::= IN",
109869  /* 225 */ "in_op ::= NOT IN",
109870  /* 226 */ "expr ::= expr in_op LP exprlist RP",
109871  /* 227 */ "expr ::= LP select RP",
109872  /* 228 */ "expr ::= expr in_op LP select RP",
109873  /* 229 */ "expr ::= expr in_op nm dbnm",
109874  /* 230 */ "expr ::= EXISTS LP select RP",
109875  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
109876  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
109877  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
109878  /* 234 */ "case_else ::= ELSE expr",
109879  /* 235 */ "case_else ::=",
109880  /* 236 */ "case_operand ::= expr",
109881  /* 237 */ "case_operand ::=",
109882  /* 238 */ "exprlist ::= nexprlist",
109883  /* 239 */ "exprlist ::=",
109884  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
109885  /* 241 */ "nexprlist ::= expr",
109886  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
109887  /* 243 */ "uniqueflag ::= UNIQUE",
109888  /* 244 */ "uniqueflag ::=",
109889  /* 245 */ "idxlist_opt ::=",
109890  /* 246 */ "idxlist_opt ::= LP idxlist RP",
109891  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
109892  /* 248 */ "idxlist ::= nm collate sortorder",
109893  /* 249 */ "collate ::=",
109894  /* 250 */ "collate ::= COLLATE ids",
109895  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
109896  /* 252 */ "cmd ::= VACUUM",
109897  /* 253 */ "cmd ::= VACUUM nm",
109898  /* 254 */ "cmd ::= PRAGMA nm dbnm",
109899  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
109900  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
109901  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
109902  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
109903  /* 259 */ "nmnum ::= plus_num",
109904  /* 260 */ "nmnum ::= nm",
109905  /* 261 */ "nmnum ::= ON",
109906  /* 262 */ "nmnum ::= DELETE",
109907  /* 263 */ "nmnum ::= DEFAULT",
109908  /* 264 */ "plus_num ::= PLUS number",
109909  /* 265 */ "plus_num ::= number",
109910  /* 266 */ "minus_num ::= MINUS number",
109911  /* 267 */ "number ::= INTEGER|FLOAT",
109912  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
109913  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
109914  /* 270 */ "trigger_time ::= BEFORE",
109915  /* 271 */ "trigger_time ::= AFTER",
109916  /* 272 */ "trigger_time ::= INSTEAD OF",
109917  /* 273 */ "trigger_time ::=",
109918  /* 274 */ "trigger_event ::= DELETE|INSERT",
109919  /* 275 */ "trigger_event ::= UPDATE",
109920  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
109921  /* 277 */ "foreach_clause ::=",
109922  /* 278 */ "foreach_clause ::= FOR EACH ROW",
109923  /* 279 */ "when_clause ::=",
109924  /* 280 */ "when_clause ::= WHEN expr",
109925  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
109926  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
109927  /* 283 */ "trnm ::= nm",
109928  /* 284 */ "trnm ::= nm DOT nm",
109929  /* 285 */ "tridxby ::=",
109930  /* 286 */ "tridxby ::= INDEXED BY nm",
109931  /* 287 */ "tridxby ::= NOT INDEXED",
109932  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
109933  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
109934  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
109935  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
109936  /* 292 */ "trigger_cmd ::= select",
109937  /* 293 */ "expr ::= RAISE LP IGNORE RP",
109938  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
109939  /* 295 */ "raisetype ::= ROLLBACK",
109940  /* 296 */ "raisetype ::= ABORT",
109941  /* 297 */ "raisetype ::= FAIL",
109942  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
109943  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
109944  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
109945  /* 301 */ "key_opt ::=",
109946  /* 302 */ "key_opt ::= KEY expr",
109947  /* 303 */ "database_kw_opt ::= DATABASE",
109948  /* 304 */ "database_kw_opt ::=",
109949  /* 305 */ "cmd ::= REINDEX",
109950  /* 306 */ "cmd ::= REINDEX nm dbnm",
109951  /* 307 */ "cmd ::= ANALYZE",
109952  /* 308 */ "cmd ::= ANALYZE nm dbnm",
109953  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
109954  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
109955  /* 311 */ "add_column_fullname ::= fullname",
109956  /* 312 */ "kwcolumn_opt ::=",
109957  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
109958  /* 314 */ "cmd ::= create_vtab",
109959  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
109960  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
109961  /* 317 */ "vtabarglist ::= vtabarg",
109962  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
109963  /* 319 */ "vtabarg ::=",
109964  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
109965  /* 321 */ "vtabargtoken ::= ANY",
109966  /* 322 */ "vtabargtoken ::= lp anylist RP",
109967  /* 323 */ "lp ::= LP",
109968  /* 324 */ "anylist ::=",
109969  /* 325 */ "anylist ::= anylist LP anylist RP",
109970  /* 326 */ "anylist ::= anylist ANY",
109971 };
109972 #endif /* NDEBUG */
109973 
109974 
109975 #if YYSTACKDEPTH<=0
109976 /*
109977 ** Try to increase the size of the parser stack.
109978 */
109979 static void yyGrowStack(yyParser *p){
109980   int newSize;
109981   yyStackEntry *pNew;
109982 
109983   newSize = p->yystksz*2 + 100;
109984   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
109985   if( pNew ){
109986     p->yystack = pNew;
109987     p->yystksz = newSize;
109988 #ifndef NDEBUG
109989     if( yyTraceFILE ){
109990       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
109991               yyTracePrompt, p->yystksz);
109992     }
109993 #endif
109994   }
109995 }
109996 #endif
109997 
109998 /*
109999 ** This function allocates a new parser.
110000 ** The only argument is a pointer to a function which works like
110001 ** malloc.
110002 **
110003 ** Inputs:
110004 ** A pointer to the function used to allocate memory.
110005 **
110006 ** Outputs:
110007 ** A pointer to a parser.  This pointer is used in subsequent calls
110008 ** to sqlite3Parser and sqlite3ParserFree.
110009 */
110010 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
110011   yyParser *pParser;
110012   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
110013   if( pParser ){
110014     pParser->yyidx = -1;
110015 #ifdef YYTRACKMAXSTACKDEPTH
110016     pParser->yyidxMax = 0;
110017 #endif
110018 #if YYSTACKDEPTH<=0
110019     pParser->yystack = NULL;
110020     pParser->yystksz = 0;
110021     yyGrowStack(pParser);
110022 #endif
110023   }
110024   return pParser;
110025 }
110026 
110027 /* The following function deletes the value associated with a
110028 ** symbol.  The symbol can be either a terminal or nonterminal.
110029 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
110030 ** the value.
110031 */
110032 static void yy_destructor(
110033   yyParser *yypParser,    /* The parser */
110034   YYCODETYPE yymajor,     /* Type code for object to destroy */
110035   YYMINORTYPE *yypminor   /* The object to be destroyed */
110036 ){
110037   sqlite3ParserARG_FETCH;
110038   switch( yymajor ){
110039     /* Here is inserted the actions which take place when a
110040     ** terminal or non-terminal is destroyed.  This can happen
110041     ** when the symbol is popped from the stack during a
110042     ** reduce or during error processing or when a parser is
110043     ** being destroyed before it is finished parsing.
110044     **
110045     ** Note: during a reduce, the only symbols destroyed are those
110046     ** which appear on the RHS of the rule, but which are not used
110047     ** inside the C code.
110048     */
110049     case 160: /* select */
110050     case 194: /* oneselect */
110051 {
110052 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
110053 }
110054       break;
110055     case 173: /* term */
110056     case 174: /* expr */
110057 {
110058 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
110059 }
110060       break;
110061     case 178: /* idxlist_opt */
110062     case 187: /* idxlist */
110063     case 197: /* selcollist */
110064     case 200: /* groupby_opt */
110065     case 202: /* orderby_opt */
110066     case 204: /* sclp */
110067     case 214: /* sortlist */
110068     case 215: /* nexprlist */
110069     case 216: /* setlist */
110070     case 220: /* exprlist */
110071     case 225: /* case_exprlist */
110072 {
110073 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
110074 }
110075       break;
110076     case 193: /* fullname */
110077     case 198: /* from */
110078     case 206: /* seltablist */
110079     case 207: /* stl_prefix */
110080 {
110081 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
110082 }
110083       break;
110084     case 199: /* where_opt */
110085     case 201: /* having_opt */
110086     case 210: /* on_opt */
110087     case 224: /* case_operand */
110088     case 226: /* case_else */
110089     case 236: /* when_clause */
110090     case 241: /* key_opt */
110091 {
110092 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
110093 }
110094       break;
110095     case 211: /* using_opt */
110096     case 213: /* inscollist */
110097     case 218: /* inscollist_opt */
110098 {
110099 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
110100 }
110101       break;
110102     case 219: /* valuelist */
110103 {
110104 
110105   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
110106   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
110107 
110108 }
110109       break;
110110     case 232: /* trigger_cmd_list */
110111     case 237: /* trigger_cmd */
110112 {
110113 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
110114 }
110115       break;
110116     case 234: /* trigger_event */
110117 {
110118 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
110119 }
110120       break;
110121     default:  break;   /* If no destructor action specified: do nothing */
110122   }
110123 }
110124 
110125 /*
110126 ** Pop the parser's stack once.
110127 **
110128 ** If there is a destructor routine associated with the token which
110129 ** is popped from the stack, then call it.
110130 **
110131 ** Return the major token number for the symbol popped.
110132 */
110133 static int yy_pop_parser_stack(yyParser *pParser){
110134   YYCODETYPE yymajor;
110135   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
110136 
110137   /* There is no mechanism by which the parser stack can be popped below
110138   ** empty in SQLite.  */
110139   if( NEVER(pParser->yyidx<0) ) return 0;
110140 #ifndef NDEBUG
110141   if( yyTraceFILE && pParser->yyidx>=0 ){
110142     fprintf(yyTraceFILE,"%sPopping %s\n",
110143       yyTracePrompt,
110144       yyTokenName[yytos->major]);
110145   }
110146 #endif
110147   yymajor = yytos->major;
110148   yy_destructor(pParser, yymajor, &yytos->minor);
110149   pParser->yyidx--;
110150   return yymajor;
110151 }
110152 
110153 /*
110154 ** Deallocate and destroy a parser.  Destructors are all called for
110155 ** all stack elements before shutting the parser down.
110156 **
110157 ** Inputs:
110158 ** <ul>
110159 ** <li>  A pointer to the parser.  This should be a pointer
110160 **       obtained from sqlite3ParserAlloc.
110161 ** <li>  A pointer to a function used to reclaim memory obtained
110162 **       from malloc.
110163 ** </ul>
110164 */
110165 SQLITE_PRIVATE void sqlite3ParserFree(
110166   void *p,                    /* The parser to be deleted */
110167   void (*freeProc)(void*)     /* Function used to reclaim memory */
110168 ){
110169   yyParser *pParser = (yyParser*)p;
110170   /* In SQLite, we never try to destroy a parser that was not successfully
110171   ** created in the first place. */
110172   if( NEVER(pParser==0) ) return;
110173   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
110174 #if YYSTACKDEPTH<=0
110175   free(pParser->yystack);
110176 #endif
110177   (*freeProc)((void*)pParser);
110178 }
110179 
110180 /*
110181 ** Return the peak depth of the stack for a parser.
110182 */
110183 #ifdef YYTRACKMAXSTACKDEPTH
110184 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
110185   yyParser *pParser = (yyParser*)p;
110186   return pParser->yyidxMax;
110187 }
110188 #endif
110189 
110190 /*
110191 ** Find the appropriate action for a parser given the terminal
110192 ** look-ahead token iLookAhead.
110193 **
110194 ** If the look-ahead token is YYNOCODE, then check to see if the action is
110195 ** independent of the look-ahead.  If it is, return the action, otherwise
110196 ** return YY_NO_ACTION.
110197 */
110198 static int yy_find_shift_action(
110199   yyParser *pParser,        /* The parser */
110200   YYCODETYPE iLookAhead     /* The look-ahead token */
110201 ){
110202   int i;
110203   int stateno = pParser->yystack[pParser->yyidx].stateno;
110204 
110205   if( stateno>YY_SHIFT_COUNT
110206    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
110207     return yy_default[stateno];
110208   }
110209   assert( iLookAhead!=YYNOCODE );
110210   i += iLookAhead;
110211   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
110212     if( iLookAhead>0 ){
110213 #ifdef YYFALLBACK
110214       YYCODETYPE iFallback;            /* Fallback token */
110215       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
110216              && (iFallback = yyFallback[iLookAhead])!=0 ){
110217 #ifndef NDEBUG
110218         if( yyTraceFILE ){
110219           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
110220              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
110221         }
110222 #endif
110223         return yy_find_shift_action(pParser, iFallback);
110224       }
110225 #endif
110226 #ifdef YYWILDCARD
110227       {
110228         int j = i - iLookAhead + YYWILDCARD;
110229         if(
110230 #if YY_SHIFT_MIN+YYWILDCARD<0
110231           j>=0 &&
110232 #endif
110233 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
110234           j<YY_ACTTAB_COUNT &&
110235 #endif
110236           yy_lookahead[j]==YYWILDCARD
110237         ){
110238 #ifndef NDEBUG
110239           if( yyTraceFILE ){
110240             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
110241                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
110242           }
110243 #endif /* NDEBUG */
110244           return yy_action[j];
110245         }
110246       }
110247 #endif /* YYWILDCARD */
110248     }
110249     return yy_default[stateno];
110250   }else{
110251     return yy_action[i];
110252   }
110253 }
110254 
110255 /*
110256 ** Find the appropriate action for a parser given the non-terminal
110257 ** look-ahead token iLookAhead.
110258 **
110259 ** If the look-ahead token is YYNOCODE, then check to see if the action is
110260 ** independent of the look-ahead.  If it is, return the action, otherwise
110261 ** return YY_NO_ACTION.
110262 */
110263 static int yy_find_reduce_action(
110264   int stateno,              /* Current state number */
110265   YYCODETYPE iLookAhead     /* The look-ahead token */
110266 ){
110267   int i;
110268 #ifdef YYERRORSYMBOL
110269   if( stateno>YY_REDUCE_COUNT ){
110270     return yy_default[stateno];
110271   }
110272 #else
110273   assert( stateno<=YY_REDUCE_COUNT );
110274 #endif
110275   i = yy_reduce_ofst[stateno];
110276   assert( i!=YY_REDUCE_USE_DFLT );
110277   assert( iLookAhead!=YYNOCODE );
110278   i += iLookAhead;
110279 #ifdef YYERRORSYMBOL
110280   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
110281     return yy_default[stateno];
110282   }
110283 #else
110284   assert( i>=0 && i<YY_ACTTAB_COUNT );
110285   assert( yy_lookahead[i]==iLookAhead );
110286 #endif
110287   return yy_action[i];
110288 }
110289 
110290 /*
110291 ** The following routine is called if the stack overflows.
110292 */
110293 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
110294    sqlite3ParserARG_FETCH;
110295    yypParser->yyidx--;
110296 #ifndef NDEBUG
110297    if( yyTraceFILE ){
110298      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
110299    }
110300 #endif
110301    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
110302    /* Here code is inserted which will execute if the parser
110303    ** stack every overflows */
110304 
110305   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
110306   sqlite3ErrorMsg(pParse, "parser stack overflow");
110307    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
110308 }
110309 
110310 /*
110311 ** Perform a shift action.
110312 */
110313 static void yy_shift(
110314   yyParser *yypParser,          /* The parser to be shifted */
110315   int yyNewState,               /* The new state to shift in */
110316   int yyMajor,                  /* The major token to shift in */
110317   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
110318 ){
110319   yyStackEntry *yytos;
110320   yypParser->yyidx++;
110321 #ifdef YYTRACKMAXSTACKDEPTH
110322   if( yypParser->yyidx>yypParser->yyidxMax ){
110323     yypParser->yyidxMax = yypParser->yyidx;
110324   }
110325 #endif
110326 #if YYSTACKDEPTH>0
110327   if( yypParser->yyidx>=YYSTACKDEPTH ){
110328     yyStackOverflow(yypParser, yypMinor);
110329     return;
110330   }
110331 #else
110332   if( yypParser->yyidx>=yypParser->yystksz ){
110333     yyGrowStack(yypParser);
110334     if( yypParser->yyidx>=yypParser->yystksz ){
110335       yyStackOverflow(yypParser, yypMinor);
110336       return;
110337     }
110338   }
110339 #endif
110340   yytos = &yypParser->yystack[yypParser->yyidx];
110341   yytos->stateno = (YYACTIONTYPE)yyNewState;
110342   yytos->major = (YYCODETYPE)yyMajor;
110343   yytos->minor = *yypMinor;
110344 #ifndef NDEBUG
110345   if( yyTraceFILE && yypParser->yyidx>0 ){
110346     int i;
110347     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
110348     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
110349     for(i=1; i<=yypParser->yyidx; i++)
110350       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
110351     fprintf(yyTraceFILE,"\n");
110352   }
110353 #endif
110354 }
110355 
110356 /* The following table contains information about every rule that
110357 ** is used during the reduce.
110358 */
110359 static const struct {
110360   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
110361   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
110362 } yyRuleInfo[] = {
110363   { 142, 1 },
110364   { 143, 2 },
110365   { 143, 1 },
110366   { 144, 1 },
110367   { 144, 3 },
110368   { 145, 0 },
110369   { 145, 1 },
110370   { 145, 3 },
110371   { 146, 1 },
110372   { 147, 3 },
110373   { 149, 0 },
110374   { 149, 1 },
110375   { 149, 2 },
110376   { 148, 0 },
110377   { 148, 1 },
110378   { 148, 1 },
110379   { 148, 1 },
110380   { 147, 2 },
110381   { 147, 2 },
110382   { 147, 2 },
110383   { 151, 1 },
110384   { 151, 0 },
110385   { 147, 2 },
110386   { 147, 3 },
110387   { 147, 5 },
110388   { 147, 2 },
110389   { 152, 6 },
110390   { 154, 1 },
110391   { 156, 0 },
110392   { 156, 3 },
110393   { 155, 1 },
110394   { 155, 0 },
110395   { 153, 4 },
110396   { 153, 2 },
110397   { 158, 3 },
110398   { 158, 1 },
110399   { 161, 3 },
110400   { 162, 1 },
110401   { 165, 1 },
110402   { 165, 1 },
110403   { 166, 1 },
110404   { 150, 1 },
110405   { 150, 1 },
110406   { 150, 1 },
110407   { 163, 0 },
110408   { 163, 1 },
110409   { 167, 1 },
110410   { 167, 4 },
110411   { 167, 6 },
110412   { 168, 1 },
110413   { 168, 2 },
110414   { 169, 1 },
110415   { 169, 1 },
110416   { 164, 2 },
110417   { 164, 0 },
110418   { 172, 2 },
110419   { 172, 2 },
110420   { 172, 4 },
110421   { 172, 3 },
110422   { 172, 3 },
110423   { 172, 2 },
110424   { 172, 2 },
110425   { 172, 3 },
110426   { 172, 5 },
110427   { 172, 2 },
110428   { 172, 4 },
110429   { 172, 4 },
110430   { 172, 1 },
110431   { 172, 2 },
110432   { 177, 0 },
110433   { 177, 1 },
110434   { 179, 0 },
110435   { 179, 2 },
110436   { 181, 2 },
110437   { 181, 3 },
110438   { 181, 3 },
110439   { 181, 3 },
110440   { 182, 2 },
110441   { 182, 2 },
110442   { 182, 1 },
110443   { 182, 1 },
110444   { 182, 2 },
110445   { 180, 3 },
110446   { 180, 2 },
110447   { 183, 0 },
110448   { 183, 2 },
110449   { 183, 2 },
110450   { 159, 0 },
110451   { 159, 2 },
110452   { 184, 3 },
110453   { 184, 1 },
110454   { 185, 1 },
110455   { 185, 0 },
110456   { 186, 2 },
110457   { 186, 7 },
110458   { 186, 5 },
110459   { 186, 5 },
110460   { 186, 10 },
110461   { 188, 0 },
110462   { 188, 1 },
110463   { 175, 0 },
110464   { 175, 3 },
110465   { 189, 0 },
110466   { 189, 2 },
110467   { 190, 1 },
110468   { 190, 1 },
110469   { 190, 1 },
110470   { 147, 4 },
110471   { 192, 2 },
110472   { 192, 0 },
110473   { 147, 8 },
110474   { 147, 4 },
110475   { 147, 1 },
110476   { 160, 1 },
110477   { 160, 3 },
110478   { 195, 1 },
110479   { 195, 2 },
110480   { 195, 1 },
110481   { 194, 9 },
110482   { 196, 1 },
110483   { 196, 1 },
110484   { 196, 0 },
110485   { 204, 2 },
110486   { 204, 0 },
110487   { 197, 3 },
110488   { 197, 2 },
110489   { 197, 4 },
110490   { 205, 2 },
110491   { 205, 1 },
110492   { 205, 0 },
110493   { 198, 0 },
110494   { 198, 2 },
110495   { 207, 2 },
110496   { 207, 0 },
110497   { 206, 7 },
110498   { 206, 7 },
110499   { 206, 7 },
110500   { 157, 0 },
110501   { 157, 2 },
110502   { 193, 2 },
110503   { 208, 1 },
110504   { 208, 2 },
110505   { 208, 3 },
110506   { 208, 4 },
110507   { 210, 2 },
110508   { 210, 0 },
110509   { 209, 0 },
110510   { 209, 3 },
110511   { 209, 2 },
110512   { 211, 4 },
110513   { 211, 0 },
110514   { 202, 0 },
110515   { 202, 3 },
110516   { 214, 4 },
110517   { 214, 2 },
110518   { 176, 1 },
110519   { 176, 1 },
110520   { 176, 0 },
110521   { 200, 0 },
110522   { 200, 3 },
110523   { 201, 0 },
110524   { 201, 2 },
110525   { 203, 0 },
110526   { 203, 2 },
110527   { 203, 4 },
110528   { 203, 4 },
110529   { 147, 5 },
110530   { 199, 0 },
110531   { 199, 2 },
110532   { 147, 7 },
110533   { 216, 5 },
110534   { 216, 3 },
110535   { 147, 5 },
110536   { 147, 5 },
110537   { 147, 6 },
110538   { 217, 2 },
110539   { 217, 1 },
110540   { 219, 4 },
110541   { 219, 5 },
110542   { 218, 0 },
110543   { 218, 3 },
110544   { 213, 3 },
110545   { 213, 1 },
110546   { 174, 1 },
110547   { 174, 3 },
110548   { 173, 1 },
110549   { 174, 1 },
110550   { 174, 1 },
110551   { 174, 3 },
110552   { 174, 5 },
110553   { 173, 1 },
110554   { 173, 1 },
110555   { 174, 1 },
110556   { 174, 1 },
110557   { 174, 3 },
110558   { 174, 6 },
110559   { 174, 5 },
110560   { 174, 4 },
110561   { 173, 1 },
110562   { 174, 3 },
110563   { 174, 3 },
110564   { 174, 3 },
110565   { 174, 3 },
110566   { 174, 3 },
110567   { 174, 3 },
110568   { 174, 3 },
110569   { 174, 3 },
110570   { 221, 1 },
110571   { 221, 2 },
110572   { 221, 1 },
110573   { 221, 2 },
110574   { 174, 3 },
110575   { 174, 5 },
110576   { 174, 2 },
110577   { 174, 3 },
110578   { 174, 3 },
110579   { 174, 4 },
110580   { 174, 2 },
110581   { 174, 2 },
110582   { 174, 2 },
110583   { 174, 2 },
110584   { 222, 1 },
110585   { 222, 2 },
110586   { 174, 5 },
110587   { 223, 1 },
110588   { 223, 2 },
110589   { 174, 5 },
110590   { 174, 3 },
110591   { 174, 5 },
110592   { 174, 4 },
110593   { 174, 4 },
110594   { 174, 5 },
110595   { 225, 5 },
110596   { 225, 4 },
110597   { 226, 2 },
110598   { 226, 0 },
110599   { 224, 1 },
110600   { 224, 0 },
110601   { 220, 1 },
110602   { 220, 0 },
110603   { 215, 3 },
110604   { 215, 1 },
110605   { 147, 11 },
110606   { 227, 1 },
110607   { 227, 0 },
110608   { 178, 0 },
110609   { 178, 3 },
110610   { 187, 5 },
110611   { 187, 3 },
110612   { 228, 0 },
110613   { 228, 2 },
110614   { 147, 4 },
110615   { 147, 1 },
110616   { 147, 2 },
110617   { 147, 3 },
110618   { 147, 5 },
110619   { 147, 6 },
110620   { 147, 5 },
110621   { 147, 6 },
110622   { 229, 1 },
110623   { 229, 1 },
110624   { 229, 1 },
110625   { 229, 1 },
110626   { 229, 1 },
110627   { 170, 2 },
110628   { 170, 1 },
110629   { 171, 2 },
110630   { 230, 1 },
110631   { 147, 5 },
110632   { 231, 11 },
110633   { 233, 1 },
110634   { 233, 1 },
110635   { 233, 2 },
110636   { 233, 0 },
110637   { 234, 1 },
110638   { 234, 1 },
110639   { 234, 3 },
110640   { 235, 0 },
110641   { 235, 3 },
110642   { 236, 0 },
110643   { 236, 2 },
110644   { 232, 3 },
110645   { 232, 2 },
110646   { 238, 1 },
110647   { 238, 3 },
110648   { 239, 0 },
110649   { 239, 3 },
110650   { 239, 2 },
110651   { 237, 7 },
110652   { 237, 5 },
110653   { 237, 5 },
110654   { 237, 5 },
110655   { 237, 1 },
110656   { 174, 4 },
110657   { 174, 6 },
110658   { 191, 1 },
110659   { 191, 1 },
110660   { 191, 1 },
110661   { 147, 4 },
110662   { 147, 6 },
110663   { 147, 3 },
110664   { 241, 0 },
110665   { 241, 2 },
110666   { 240, 1 },
110667   { 240, 0 },
110668   { 147, 1 },
110669   { 147, 3 },
110670   { 147, 1 },
110671   { 147, 3 },
110672   { 147, 6 },
110673   { 147, 6 },
110674   { 242, 1 },
110675   { 243, 0 },
110676   { 243, 1 },
110677   { 147, 1 },
110678   { 147, 4 },
110679   { 244, 8 },
110680   { 245, 1 },
110681   { 245, 3 },
110682   { 246, 0 },
110683   { 246, 2 },
110684   { 247, 1 },
110685   { 247, 3 },
110686   { 248, 1 },
110687   { 249, 0 },
110688   { 249, 4 },
110689   { 249, 2 },
110690 };
110691 
110692 static void yy_accept(yyParser*);  /* Forward Declaration */
110693 
110694 /*
110695 ** Perform a reduce action and the shift that must immediately
110696 ** follow the reduce.
110697 */
110698 static void yy_reduce(
110699   yyParser *yypParser,         /* The parser */
110700   int yyruleno                 /* Number of the rule by which to reduce */
110701 ){
110702   int yygoto;                     /* The next state */
110703   int yyact;                      /* The next action */
110704   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
110705   yyStackEntry *yymsp;            /* The top of the parser's stack */
110706   int yysize;                     /* Amount to pop the stack */
110707   sqlite3ParserARG_FETCH;
110708   yymsp = &yypParser->yystack[yypParser->yyidx];
110709 #ifndef NDEBUG
110710   if( yyTraceFILE && yyruleno>=0
110711         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
110712     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
110713       yyRuleName[yyruleno]);
110714   }
110715 #endif /* NDEBUG */
110716 
110717   /* Silence complaints from purify about yygotominor being uninitialized
110718   ** in some cases when it is copied into the stack after the following
110719   ** switch.  yygotominor is uninitialized when a rule reduces that does
110720   ** not set the value of its left-hand side nonterminal.  Leaving the
110721   ** value of the nonterminal uninitialized is utterly harmless as long
110722   ** as the value is never used.  So really the only thing this code
110723   ** accomplishes is to quieten purify.
110724   **
110725   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
110726   ** without this code, their parser segfaults.  I'm not sure what there
110727   ** parser is doing to make this happen.  This is the second bug report
110728   ** from wireshark this week.  Clearly they are stressing Lemon in ways
110729   ** that it has not been previously stressed...  (SQLite ticket #2172)
110730   */
110731   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
110732   yygotominor = yyzerominor;
110733 
110734 
110735   switch( yyruleno ){
110736   /* Beginning here are the reduction cases.  A typical example
110737   ** follows:
110738   **   case 0:
110739   **  #line <lineno> <grammarfile>
110740   **     { ... }           // User supplied code
110741   **  #line <lineno> <thisfile>
110742   **     break;
110743   */
110744       case 5: /* explain ::= */
110745 { sqlite3BeginParse(pParse, 0); }
110746         break;
110747       case 6: /* explain ::= EXPLAIN */
110748 { sqlite3BeginParse(pParse, 1); }
110749         break;
110750       case 7: /* explain ::= EXPLAIN QUERY PLAN */
110751 { sqlite3BeginParse(pParse, 2); }
110752         break;
110753       case 8: /* cmdx ::= cmd */
110754 { sqlite3FinishCoding(pParse); }
110755         break;
110756       case 9: /* cmd ::= BEGIN transtype trans_opt */
110757 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
110758         break;
110759       case 13: /* transtype ::= */
110760 {yygotominor.yy392 = TK_DEFERRED;}
110761         break;
110762       case 14: /* transtype ::= DEFERRED */
110763       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
110764       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
110765       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
110766       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
110767 {yygotominor.yy392 = yymsp[0].major;}
110768         break;
110769       case 17: /* cmd ::= COMMIT trans_opt */
110770       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
110771 {sqlite3CommitTransaction(pParse);}
110772         break;
110773       case 19: /* cmd ::= ROLLBACK trans_opt */
110774 {sqlite3RollbackTransaction(pParse);}
110775         break;
110776       case 22: /* cmd ::= SAVEPOINT nm */
110777 {
110778   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
110779 }
110780         break;
110781       case 23: /* cmd ::= RELEASE savepoint_opt nm */
110782 {
110783   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
110784 }
110785         break;
110786       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
110787 {
110788   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
110789 }
110790         break;
110791       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
110792 {
110793    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
110794 }
110795         break;
110796       case 27: /* createkw ::= CREATE */
110797 {
110798   pParse->db->lookaside.bEnabled = 0;
110799   yygotominor.yy0 = yymsp[0].minor.yy0;
110800 }
110801         break;
110802       case 28: /* ifnotexists ::= */
110803       case 31: /* temp ::= */ yytestcase(yyruleno==31);
110804       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
110805       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
110806       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
110807       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
110808       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
110809       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
110810       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
110811       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
110812 {yygotominor.yy392 = 0;}
110813         break;
110814       case 29: /* ifnotexists ::= IF NOT EXISTS */
110815       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
110816       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
110817       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
110818       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
110819       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
110820       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
110821 {yygotominor.yy392 = 1;}
110822         break;
110823       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
110824 {
110825   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
110826 }
110827         break;
110828       case 33: /* create_table_args ::= AS select */
110829 {
110830   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
110831   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
110832 }
110833         break;
110834       case 36: /* column ::= columnid type carglist */
110835 {
110836   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
110837   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
110838 }
110839         break;
110840       case 37: /* columnid ::= nm */
110841 {
110842   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
110843   yygotominor.yy0 = yymsp[0].minor.yy0;
110844   pParse->constraintName.n = 0;
110845 }
110846         break;
110847       case 38: /* id ::= ID */
110848       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
110849       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
110850       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
110851       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
110852       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
110853       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
110854       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
110855       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
110856       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
110857       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
110858       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
110859       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
110860       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
110861       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
110862       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
110863       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
110864       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
110865       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
110866       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
110867       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
110868       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
110869       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
110870 {yygotominor.yy0 = yymsp[0].minor.yy0;}
110871         break;
110872       case 45: /* type ::= typetoken */
110873 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
110874         break;
110875       case 47: /* typetoken ::= typename LP signed RP */
110876 {
110877   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
110878   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
110879 }
110880         break;
110881       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
110882 {
110883   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
110884   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
110885 }
110886         break;
110887       case 50: /* typename ::= typename ids */
110888 {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
110889         break;
110890       case 55: /* ccons ::= CONSTRAINT nm */
110891       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
110892 {pParse->constraintName = yymsp[0].minor.yy0;}
110893         break;
110894       case 56: /* ccons ::= DEFAULT term */
110895       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
110896 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
110897         break;
110898       case 57: /* ccons ::= DEFAULT LP expr RP */
110899 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
110900         break;
110901       case 59: /* ccons ::= DEFAULT MINUS term */
110902 {
110903   ExprSpan v;
110904   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
110905   v.zStart = yymsp[-1].minor.yy0.z;
110906   v.zEnd = yymsp[0].minor.yy342.zEnd;
110907   sqlite3AddDefaultValue(pParse,&v);
110908 }
110909         break;
110910       case 60: /* ccons ::= DEFAULT id */
110911 {
110912   ExprSpan v;
110913   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
110914   sqlite3AddDefaultValue(pParse,&v);
110915 }
110916         break;
110917       case 62: /* ccons ::= NOT NULL onconf */
110918 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
110919         break;
110920       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
110921 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
110922         break;
110923       case 64: /* ccons ::= UNIQUE onconf */
110924 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
110925         break;
110926       case 65: /* ccons ::= CHECK LP expr RP */
110927 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
110928         break;
110929       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
110930 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
110931         break;
110932       case 67: /* ccons ::= defer_subclause */
110933 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
110934         break;
110935       case 68: /* ccons ::= COLLATE ids */
110936 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
110937         break;
110938       case 71: /* refargs ::= */
110939 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
110940         break;
110941       case 72: /* refargs ::= refargs refarg */
110942 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
110943         break;
110944       case 73: /* refarg ::= MATCH nm */
110945       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
110946 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
110947         break;
110948       case 75: /* refarg ::= ON DELETE refact */
110949 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
110950         break;
110951       case 76: /* refarg ::= ON UPDATE refact */
110952 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
110953         break;
110954       case 77: /* refact ::= SET NULL */
110955 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
110956         break;
110957       case 78: /* refact ::= SET DEFAULT */
110958 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
110959         break;
110960       case 79: /* refact ::= CASCADE */
110961 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
110962         break;
110963       case 80: /* refact ::= RESTRICT */
110964 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
110965         break;
110966       case 81: /* refact ::= NO ACTION */
110967 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
110968         break;
110969       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
110970       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
110971       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
110972       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
110973 {yygotominor.yy392 = yymsp[0].minor.yy392;}
110974         break;
110975       case 87: /* conslist_opt ::= */
110976 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
110977         break;
110978       case 88: /* conslist_opt ::= COMMA conslist */
110979 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
110980         break;
110981       case 91: /* tconscomma ::= COMMA */
110982 {pParse->constraintName.n = 0;}
110983         break;
110984       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
110985 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
110986         break;
110987       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
110988 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
110989         break;
110990       case 96: /* tcons ::= CHECK LP expr RP onconf */
110991 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
110992         break;
110993       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
110994 {
110995     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
110996     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
110997 }
110998         break;
110999       case 100: /* onconf ::= */
111000 {yygotominor.yy392 = OE_Default;}
111001         break;
111002       case 102: /* orconf ::= */
111003 {yygotominor.yy258 = OE_Default;}
111004         break;
111005       case 103: /* orconf ::= OR resolvetype */
111006 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
111007         break;
111008       case 105: /* resolvetype ::= IGNORE */
111009 {yygotominor.yy392 = OE_Ignore;}
111010         break;
111011       case 106: /* resolvetype ::= REPLACE */
111012 {yygotominor.yy392 = OE_Replace;}
111013         break;
111014       case 107: /* cmd ::= DROP TABLE ifexists fullname */
111015 {
111016   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
111017 }
111018         break;
111019       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
111020 {
111021   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
111022 }
111023         break;
111024       case 111: /* cmd ::= DROP VIEW ifexists fullname */
111025 {
111026   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
111027 }
111028         break;
111029       case 112: /* cmd ::= select */
111030 {
111031   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
111032   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
111033   sqlite3ExplainBegin(pParse->pVdbe);
111034   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
111035   sqlite3ExplainFinish(pParse->pVdbe);
111036   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
111037 }
111038         break;
111039       case 113: /* select ::= oneselect */
111040 {yygotominor.yy159 = yymsp[0].minor.yy159;}
111041         break;
111042       case 114: /* select ::= select multiselect_op oneselect */
111043 {
111044   if( yymsp[0].minor.yy159 ){
111045     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
111046     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
111047   }else{
111048     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
111049   }
111050   yygotominor.yy159 = yymsp[0].minor.yy159;
111051 }
111052         break;
111053       case 116: /* multiselect_op ::= UNION ALL */
111054 {yygotominor.yy392 = TK_ALL;}
111055         break;
111056       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
111057 {
111058   yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
111059 }
111060         break;
111061       case 119: /* distinct ::= DISTINCT */
111062 {yygotominor.yy305 = SF_Distinct;}
111063         break;
111064       case 120: /* distinct ::= ALL */
111065       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
111066 {yygotominor.yy305 = 0;}
111067         break;
111068       case 122: /* sclp ::= selcollist COMMA */
111069       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
111070 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
111071         break;
111072       case 123: /* sclp ::= */
111073       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
111074       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
111075       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
111076       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
111077 {yygotominor.yy442 = 0;}
111078         break;
111079       case 124: /* selcollist ::= sclp expr as */
111080 {
111081    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
111082    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
111083    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
111084 }
111085         break;
111086       case 125: /* selcollist ::= sclp STAR */
111087 {
111088   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
111089   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
111090 }
111091         break;
111092       case 126: /* selcollist ::= sclp nm DOT STAR */
111093 {
111094   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
111095   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111096   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
111097   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
111098 }
111099         break;
111100       case 129: /* as ::= */
111101 {yygotominor.yy0.n = 0;}
111102         break;
111103       case 130: /* from ::= */
111104 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
111105         break;
111106       case 131: /* from ::= FROM seltablist */
111107 {
111108   yygotominor.yy347 = yymsp[0].minor.yy347;
111109   sqlite3SrcListShiftJoinType(yygotominor.yy347);
111110 }
111111         break;
111112       case 132: /* stl_prefix ::= seltablist joinop */
111113 {
111114    yygotominor.yy347 = yymsp[-1].minor.yy347;
111115    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
111116 }
111117         break;
111118       case 133: /* stl_prefix ::= */
111119 {yygotominor.yy347 = 0;}
111120         break;
111121       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
111122 {
111123   yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111124   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
111125 }
111126         break;
111127       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
111128 {
111129     yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111130   }
111131         break;
111132       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
111133 {
111134     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
111135       yygotominor.yy347 = yymsp[-4].minor.yy347;
111136     }else if( yymsp[-4].minor.yy347->nSrc==1 ){
111137       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111138       if( yygotominor.yy347 ){
111139         struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
111140         struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
111141         pNew->zName = pOld->zName;
111142         pNew->zDatabase = pOld->zDatabase;
111143         pOld->zName = pOld->zDatabase = 0;
111144       }
111145       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
111146     }else{
111147       Select *pSubquery;
111148       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
111149       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
111150       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
111151     }
111152   }
111153         break;
111154       case 137: /* dbnm ::= */
111155       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
111156 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
111157         break;
111158       case 139: /* fullname ::= nm dbnm */
111159 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
111160         break;
111161       case 140: /* joinop ::= COMMA|JOIN */
111162 { yygotominor.yy392 = JT_INNER; }
111163         break;
111164       case 141: /* joinop ::= JOIN_KW JOIN */
111165 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
111166         break;
111167       case 142: /* joinop ::= JOIN_KW nm JOIN */
111168 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
111169         break;
111170       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
111171 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
111172         break;
111173       case 144: /* on_opt ::= ON expr */
111174       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
111175       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
111176       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
111177       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
111178 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
111179         break;
111180       case 145: /* on_opt ::= */
111181       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
111182       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
111183       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
111184       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
111185 {yygotominor.yy122 = 0;}
111186         break;
111187       case 148: /* indexed_opt ::= NOT INDEXED */
111188 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
111189         break;
111190       case 149: /* using_opt ::= USING LP inscollist RP */
111191       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
111192 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
111193         break;
111194       case 150: /* using_opt ::= */
111195       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
111196 {yygotominor.yy180 = 0;}
111197         break;
111198       case 152: /* orderby_opt ::= ORDER BY sortlist */
111199       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
111200       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
111201 {yygotominor.yy442 = yymsp[0].minor.yy442;}
111202         break;
111203       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
111204 {
111205   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
111206   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111207 }
111208         break;
111209       case 154: /* sortlist ::= expr sortorder */
111210 {
111211   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
111212   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
111213 }
111214         break;
111215       case 155: /* sortorder ::= ASC */
111216       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
111217 {yygotominor.yy392 = SQLITE_SO_ASC;}
111218         break;
111219       case 156: /* sortorder ::= DESC */
111220 {yygotominor.yy392 = SQLITE_SO_DESC;}
111221         break;
111222       case 162: /* limit_opt ::= */
111223 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
111224         break;
111225       case 163: /* limit_opt ::= LIMIT expr */
111226 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
111227         break;
111228       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
111229 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
111230         break;
111231       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
111232 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
111233         break;
111234       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
111235 {
111236   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
111237   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
111238 }
111239         break;
111240       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
111241 {
111242   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
111243   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
111244   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
111245 }
111246         break;
111247       case 170: /* setlist ::= setlist COMMA nm EQ expr */
111248 {
111249   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
111250   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111251 }
111252         break;
111253       case 171: /* setlist ::= nm EQ expr */
111254 {
111255   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
111256   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111257 }
111258         break;
111259       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
111260 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
111261         break;
111262       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
111263 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
111264         break;
111265       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
111266 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
111267         break;
111268       case 175: /* insert_cmd ::= INSERT orconf */
111269 {yygotominor.yy258 = yymsp[0].minor.yy258;}
111270         break;
111271       case 176: /* insert_cmd ::= REPLACE */
111272 {yygotominor.yy258 = OE_Replace;}
111273         break;
111274       case 177: /* valuelist ::= VALUES LP nexprlist RP */
111275 {
111276   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
111277   yygotominor.yy487.pSelect = 0;
111278 }
111279         break;
111280       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
111281 {
111282   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
111283   if( yymsp[-4].minor.yy487.pList ){
111284     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
111285     yymsp[-4].minor.yy487.pList = 0;
111286   }
111287   yygotominor.yy487.pList = 0;
111288   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
111289     sqlite3SelectDelete(pParse->db, pRight);
111290     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
111291     yygotominor.yy487.pSelect = 0;
111292   }else{
111293     pRight->op = TK_ALL;
111294     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
111295     pRight->selFlags |= SF_Values;
111296     pRight->pPrior->selFlags |= SF_Values;
111297     yygotominor.yy487.pSelect = pRight;
111298   }
111299 }
111300         break;
111301       case 181: /* inscollist ::= inscollist COMMA nm */
111302 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
111303         break;
111304       case 182: /* inscollist ::= nm */
111305 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
111306         break;
111307       case 183: /* expr ::= term */
111308 {yygotominor.yy342 = yymsp[0].minor.yy342;}
111309         break;
111310       case 184: /* expr ::= LP expr RP */
111311 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
111312         break;
111313       case 185: /* term ::= NULL */
111314       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
111315       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
111316 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
111317         break;
111318       case 186: /* expr ::= id */
111319       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
111320 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
111321         break;
111322       case 188: /* expr ::= nm DOT nm */
111323 {
111324   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111325   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
111326   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
111327   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
111328 }
111329         break;
111330       case 189: /* expr ::= nm DOT nm DOT nm */
111331 {
111332   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
111333   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
111334   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
111335   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
111336   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
111337   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
111338 }
111339         break;
111340       case 192: /* expr ::= REGISTER */
111341 {
111342   /* When doing a nested parse, one can include terms in an expression
111343   ** that look like this:   #1 #2 ...  These terms refer to registers
111344   ** in the virtual machine.  #N is the N-th register. */
111345   if( pParse->nested==0 ){
111346     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
111347     yygotominor.yy342.pExpr = 0;
111348   }else{
111349     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
111350     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
111351   }
111352   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111353 }
111354         break;
111355       case 193: /* expr ::= VARIABLE */
111356 {
111357   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
111358   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
111359   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111360 }
111361         break;
111362       case 194: /* expr ::= expr COLLATE ids */
111363 {
111364   yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
111365   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
111366   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111367 }
111368         break;
111369       case 195: /* expr ::= CAST LP expr AS typetoken RP */
111370 {
111371   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
111372   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
111373 }
111374         break;
111375       case 196: /* expr ::= ID LP distinct exprlist RP */
111376 {
111377   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
111378     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
111379   }
111380   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
111381   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
111382   if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
111383     yygotominor.yy342.pExpr->flags |= EP_Distinct;
111384   }
111385 }
111386         break;
111387       case 197: /* expr ::= ID LP STAR RP */
111388 {
111389   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
111390   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
111391 }
111392         break;
111393       case 198: /* term ::= CTIME_KW */
111394 {
111395   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
111396   ** treated as functions that return constants */
111397   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
111398   if( yygotominor.yy342.pExpr ){
111399     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
111400   }
111401   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
111402 }
111403         break;
111404       case 199: /* expr ::= expr AND expr */
111405       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
111406       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
111407       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
111408       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
111409       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
111410       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
111411       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
111412 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
111413         break;
111414       case 207: /* likeop ::= LIKE_KW */
111415       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
111416 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
111417         break;
111418       case 208: /* likeop ::= NOT LIKE_KW */
111419       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
111420 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
111421         break;
111422       case 211: /* expr ::= expr likeop expr */
111423 {
111424   ExprList *pList;
111425   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
111426   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
111427   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
111428   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111429   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
111430   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111431   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
111432 }
111433         break;
111434       case 212: /* expr ::= expr likeop expr ESCAPE expr */
111435 {
111436   ExprList *pList;
111437   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111438   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
111439   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
111440   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
111441   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111442   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111443   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111444   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
111445 }
111446         break;
111447       case 213: /* expr ::= expr ISNULL|NOTNULL */
111448 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
111449         break;
111450       case 214: /* expr ::= expr NOT NULL */
111451 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
111452         break;
111453       case 215: /* expr ::= expr IS expr */
111454 {
111455   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
111456   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
111457 }
111458         break;
111459       case 216: /* expr ::= expr IS NOT expr */
111460 {
111461   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
111462   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
111463 }
111464         break;
111465       case 217: /* expr ::= NOT expr */
111466       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
111467 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111468         break;
111469       case 219: /* expr ::= MINUS expr */
111470 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111471         break;
111472       case 220: /* expr ::= PLUS expr */
111473 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
111474         break;
111475       case 223: /* expr ::= expr between_op expr AND expr */
111476 {
111477   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111478   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
111479   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111480   if( yygotominor.yy342.pExpr ){
111481     yygotominor.yy342.pExpr->x.pList = pList;
111482   }else{
111483     sqlite3ExprListDelete(pParse->db, pList);
111484   }
111485   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111486   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111487   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
111488 }
111489         break;
111490       case 226: /* expr ::= expr in_op LP exprlist RP */
111491 {
111492     if( yymsp[-1].minor.yy442==0 ){
111493       /* Expressions of the form
111494       **
111495       **      expr1 IN ()
111496       **      expr1 NOT IN ()
111497       **
111498       ** simplify to constants 0 (false) and 1 (true), respectively,
111499       ** regardless of the value of expr1.
111500       */
111501       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
111502       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
111503     }else{
111504       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111505       if( yygotominor.yy342.pExpr ){
111506         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
111507         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111508       }else{
111509         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
111510       }
111511       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111512     }
111513     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111514     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111515   }
111516         break;
111517       case 227: /* expr ::= LP select RP */
111518 {
111519     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
111520     if( yygotominor.yy342.pExpr ){
111521       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
111522       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111523       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111524     }else{
111525       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111526     }
111527     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
111528     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111529   }
111530         break;
111531       case 228: /* expr ::= expr in_op LP select RP */
111532 {
111533     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
111534     if( yygotominor.yy342.pExpr ){
111535       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
111536       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111537       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111538     }else{
111539       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111540     }
111541     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111542     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
111543     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111544   }
111545         break;
111546       case 229: /* expr ::= expr in_op nm dbnm */
111547 {
111548     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
111549     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
111550     if( yygotominor.yy342.pExpr ){
111551       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
111552       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
111553       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111554     }else{
111555       sqlite3SrcListDelete(pParse->db, pSrc);
111556     }
111557     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
111558     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
111559     yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
111560   }
111561         break;
111562       case 230: /* expr ::= EXISTS LP select RP */
111563 {
111564     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
111565     if( p ){
111566       p->x.pSelect = yymsp[-1].minor.yy159;
111567       ExprSetProperty(p, EP_xIsSelect);
111568       sqlite3ExprSetHeight(pParse, p);
111569     }else{
111570       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
111571     }
111572     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
111573     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111574   }
111575         break;
111576       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
111577 {
111578   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
111579   if( yygotominor.yy342.pExpr ){
111580     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
111581     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
111582   }else{
111583     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
111584   }
111585   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
111586   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111587 }
111588         break;
111589       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
111590 {
111591   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
111592   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
111593 }
111594         break;
111595       case 233: /* case_exprlist ::= WHEN expr THEN expr */
111596 {
111597   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
111598   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
111599 }
111600         break;
111601       case 240: /* nexprlist ::= nexprlist COMMA expr */
111602 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
111603         break;
111604       case 241: /* nexprlist ::= expr */
111605 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
111606         break;
111607       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
111608 {
111609   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
111610                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
111611                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
111612 }
111613         break;
111614       case 243: /* uniqueflag ::= UNIQUE */
111615       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
111616 {yygotominor.yy392 = OE_Abort;}
111617         break;
111618       case 244: /* uniqueflag ::= */
111619 {yygotominor.yy392 = OE_None;}
111620         break;
111621       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
111622 {
111623   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
111624   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
111625   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
111626   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
111627   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111628 }
111629         break;
111630       case 248: /* idxlist ::= nm collate sortorder */
111631 {
111632   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
111633   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
111634   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
111635   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
111636   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
111637 }
111638         break;
111639       case 249: /* collate ::= */
111640 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
111641         break;
111642       case 251: /* cmd ::= DROP INDEX ifexists fullname */
111643 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
111644         break;
111645       case 252: /* cmd ::= VACUUM */
111646       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
111647 {sqlite3Vacuum(pParse);}
111648         break;
111649       case 254: /* cmd ::= PRAGMA nm dbnm */
111650 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
111651         break;
111652       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
111653 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
111654         break;
111655       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
111656 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
111657         break;
111658       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
111659 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
111660         break;
111661       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
111662 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
111663         break;
111664       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
111665 {
111666   Token all;
111667   all.z = yymsp[-3].minor.yy0.z;
111668   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
111669   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
111670 }
111671         break;
111672       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
111673 {
111674   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
111675   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
111676 }
111677         break;
111678       case 270: /* trigger_time ::= BEFORE */
111679       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
111680 { yygotominor.yy392 = TK_BEFORE; }
111681         break;
111682       case 271: /* trigger_time ::= AFTER */
111683 { yygotominor.yy392 = TK_AFTER;  }
111684         break;
111685       case 272: /* trigger_time ::= INSTEAD OF */
111686 { yygotominor.yy392 = TK_INSTEAD;}
111687         break;
111688       case 274: /* trigger_event ::= DELETE|INSERT */
111689       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
111690 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
111691         break;
111692       case 276: /* trigger_event ::= UPDATE OF inscollist */
111693 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
111694         break;
111695       case 279: /* when_clause ::= */
111696       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
111697 { yygotominor.yy122 = 0; }
111698         break;
111699       case 280: /* when_clause ::= WHEN expr */
111700       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
111701 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
111702         break;
111703       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
111704 {
111705   assert( yymsp[-2].minor.yy327!=0 );
111706   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
111707   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
111708   yygotominor.yy327 = yymsp[-2].minor.yy327;
111709 }
111710         break;
111711       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
111712 {
111713   assert( yymsp[-1].minor.yy327!=0 );
111714   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
111715   yygotominor.yy327 = yymsp[-1].minor.yy327;
111716 }
111717         break;
111718       case 284: /* trnm ::= nm DOT nm */
111719 {
111720   yygotominor.yy0 = yymsp[0].minor.yy0;
111721   sqlite3ErrorMsg(pParse,
111722         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
111723         "statements within triggers");
111724 }
111725         break;
111726       case 286: /* tridxby ::= INDEXED BY nm */
111727 {
111728   sqlite3ErrorMsg(pParse,
111729         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
111730         "within triggers");
111731 }
111732         break;
111733       case 287: /* tridxby ::= NOT INDEXED */
111734 {
111735   sqlite3ErrorMsg(pParse,
111736         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
111737         "within triggers");
111738 }
111739         break;
111740       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
111741 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
111742         break;
111743       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
111744 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
111745         break;
111746       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
111747 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
111748         break;
111749       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
111750 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
111751         break;
111752       case 292: /* trigger_cmd ::= select */
111753 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
111754         break;
111755       case 293: /* expr ::= RAISE LP IGNORE RP */
111756 {
111757   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
111758   if( yygotominor.yy342.pExpr ){
111759     yygotominor.yy342.pExpr->affinity = OE_Ignore;
111760   }
111761   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
111762   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111763 }
111764         break;
111765       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
111766 {
111767   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
111768   if( yygotominor.yy342.pExpr ) {
111769     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
111770   }
111771   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
111772   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
111773 }
111774         break;
111775       case 295: /* raisetype ::= ROLLBACK */
111776 {yygotominor.yy392 = OE_Rollback;}
111777         break;
111778       case 297: /* raisetype ::= FAIL */
111779 {yygotominor.yy392 = OE_Fail;}
111780         break;
111781       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
111782 {
111783   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
111784 }
111785         break;
111786       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
111787 {
111788   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
111789 }
111790         break;
111791       case 300: /* cmd ::= DETACH database_kw_opt expr */
111792 {
111793   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
111794 }
111795         break;
111796       case 305: /* cmd ::= REINDEX */
111797 {sqlite3Reindex(pParse, 0, 0);}
111798         break;
111799       case 306: /* cmd ::= REINDEX nm dbnm */
111800 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
111801         break;
111802       case 307: /* cmd ::= ANALYZE */
111803 {sqlite3Analyze(pParse, 0, 0);}
111804         break;
111805       case 308: /* cmd ::= ANALYZE nm dbnm */
111806 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
111807         break;
111808       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
111809 {
111810   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
111811 }
111812         break;
111813       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
111814 {
111815   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
111816 }
111817         break;
111818       case 311: /* add_column_fullname ::= fullname */
111819 {
111820   pParse->db->lookaside.bEnabled = 0;
111821   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
111822 }
111823         break;
111824       case 314: /* cmd ::= create_vtab */
111825 {sqlite3VtabFinishParse(pParse,0);}
111826         break;
111827       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
111828 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
111829         break;
111830       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
111831 {
111832     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
111833 }
111834         break;
111835       case 319: /* vtabarg ::= */
111836 {sqlite3VtabArgInit(pParse);}
111837         break;
111838       case 321: /* vtabargtoken ::= ANY */
111839       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
111840       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
111841 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
111842         break;
111843       default:
111844       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
111845       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
111846       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
111847       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
111848       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
111849       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
111850       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
111851       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
111852       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
111853       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
111854       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
111855       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
111856       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
111857       /* (44) type ::= */ yytestcase(yyruleno==44);
111858       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
111859       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
111860       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
111861       /* (54) carglist ::= */ yytestcase(yyruleno==54);
111862       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
111863       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
111864       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
111865       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
111866       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
111867       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
111868       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
111869       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
111870       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
111871       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
111872       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
111873       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
111874       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
111875       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
111876       /* (324) anylist ::= */ yytestcase(yyruleno==324);
111877       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
111878       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
111879         break;
111880   };
111881   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
111882   yygoto = yyRuleInfo[yyruleno].lhs;
111883   yysize = yyRuleInfo[yyruleno].nrhs;
111884   yypParser->yyidx -= yysize;
111885   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
111886   if( yyact < YYNSTATE ){
111887 #ifdef NDEBUG
111888     /* If we are not debugging and the reduce action popped at least
111889     ** one element off the stack, then we can push the new element back
111890     ** onto the stack here, and skip the stack overflow test in yy_shift().
111891     ** That gives a significant speed improvement. */
111892     if( yysize ){
111893       yypParser->yyidx++;
111894       yymsp -= yysize-1;
111895       yymsp->stateno = (YYACTIONTYPE)yyact;
111896       yymsp->major = (YYCODETYPE)yygoto;
111897       yymsp->minor = yygotominor;
111898     }else
111899 #endif
111900     {
111901       yy_shift(yypParser,yyact,yygoto,&yygotominor);
111902     }
111903   }else{
111904     assert( yyact == YYNSTATE + YYNRULE + 1 );
111905     yy_accept(yypParser);
111906   }
111907 }
111908 
111909 /*
111910 ** The following code executes when the parse fails
111911 */
111912 #ifndef YYNOERRORRECOVERY
111913 static void yy_parse_failed(
111914   yyParser *yypParser           /* The parser */
111915 ){
111916   sqlite3ParserARG_FETCH;
111917 #ifndef NDEBUG
111918   if( yyTraceFILE ){
111919     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
111920   }
111921 #endif
111922   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111923   /* Here code is inserted which will be executed whenever the
111924   ** parser fails */
111925   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111926 }
111927 #endif /* YYNOERRORRECOVERY */
111928 
111929 /*
111930 ** The following code executes when a syntax error first occurs.
111931 */
111932 static void yy_syntax_error(
111933   yyParser *yypParser,           /* The parser */
111934   int yymajor,                   /* The major type of the error token */
111935   YYMINORTYPE yyminor            /* The minor type of the error token */
111936 ){
111937   sqlite3ParserARG_FETCH;
111938 #define TOKEN (yyminor.yy0)
111939 
111940   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
111941   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
111942   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
111943   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111944 }
111945 
111946 /*
111947 ** The following is executed when the parser accepts
111948 */
111949 static void yy_accept(
111950   yyParser *yypParser           /* The parser */
111951 ){
111952   sqlite3ParserARG_FETCH;
111953 #ifndef NDEBUG
111954   if( yyTraceFILE ){
111955     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
111956   }
111957 #endif
111958   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111959   /* Here code is inserted which will be executed whenever the
111960   ** parser accepts */
111961   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111962 }
111963 
111964 /* The main parser program.
111965 ** The first argument is a pointer to a structure obtained from
111966 ** "sqlite3ParserAlloc" which describes the current state of the parser.
111967 ** The second argument is the major token number.  The third is
111968 ** the minor token.  The fourth optional argument is whatever the
111969 ** user wants (and specified in the grammar) and is available for
111970 ** use by the action routines.
111971 **
111972 ** Inputs:
111973 ** <ul>
111974 ** <li> A pointer to the parser (an opaque structure.)
111975 ** <li> The major token number.
111976 ** <li> The minor token number.
111977 ** <li> An option argument of a grammar-specified type.
111978 ** </ul>
111979 **
111980 ** Outputs:
111981 ** None.
111982 */
111983 SQLITE_PRIVATE void sqlite3Parser(
111984   void *yyp,                   /* The parser */
111985   int yymajor,                 /* The major token code number */
111986   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
111987   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
111988 ){
111989   YYMINORTYPE yyminorunion;
111990   int yyact;            /* The parser action. */
111991 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111992   int yyendofinput;     /* True if we are at the end of input */
111993 #endif
111994 #ifdef YYERRORSYMBOL
111995   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
111996 #endif
111997   yyParser *yypParser;  /* The parser */
111998 
111999   /* (re)initialize the parser, if necessary */
112000   yypParser = (yyParser*)yyp;
112001   if( yypParser->yyidx<0 ){
112002 #if YYSTACKDEPTH<=0
112003     if( yypParser->yystksz <=0 ){
112004       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
112005       yyminorunion = yyzerominor;
112006       yyStackOverflow(yypParser, &yyminorunion);
112007       return;
112008     }
112009 #endif
112010     yypParser->yyidx = 0;
112011     yypParser->yyerrcnt = -1;
112012     yypParser->yystack[0].stateno = 0;
112013     yypParser->yystack[0].major = 0;
112014   }
112015   yyminorunion.yy0 = yyminor;
112016 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
112017   yyendofinput = (yymajor==0);
112018 #endif
112019   sqlite3ParserARG_STORE;
112020 
112021 #ifndef NDEBUG
112022   if( yyTraceFILE ){
112023     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
112024   }
112025 #endif
112026 
112027   do{
112028     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
112029     if( yyact<YYNSTATE ){
112030       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
112031       yypParser->yyerrcnt--;
112032       yymajor = YYNOCODE;
112033     }else if( yyact < YYNSTATE + YYNRULE ){
112034       yy_reduce(yypParser,yyact-YYNSTATE);
112035     }else{
112036       assert( yyact == YY_ERROR_ACTION );
112037 #ifdef YYERRORSYMBOL
112038       int yymx;
112039 #endif
112040 #ifndef NDEBUG
112041       if( yyTraceFILE ){
112042         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
112043       }
112044 #endif
112045 #ifdef YYERRORSYMBOL
112046       /* A syntax error has occurred.
112047       ** The response to an error depends upon whether or not the
112048       ** grammar defines an error token "ERROR".
112049       **
112050       ** This is what we do if the grammar does define ERROR:
112051       **
112052       **  * Call the %syntax_error function.
112053       **
112054       **  * Begin popping the stack until we enter a state where
112055       **    it is legal to shift the error symbol, then shift
112056       **    the error symbol.
112057       **
112058       **  * Set the error count to three.
112059       **
112060       **  * Begin accepting and shifting new tokens.  No new error
112061       **    processing will occur until three tokens have been
112062       **    shifted successfully.
112063       **
112064       */
112065       if( yypParser->yyerrcnt<0 ){
112066         yy_syntax_error(yypParser,yymajor,yyminorunion);
112067       }
112068       yymx = yypParser->yystack[yypParser->yyidx].major;
112069       if( yymx==YYERRORSYMBOL || yyerrorhit ){
112070 #ifndef NDEBUG
112071         if( yyTraceFILE ){
112072           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
112073              yyTracePrompt,yyTokenName[yymajor]);
112074         }
112075 #endif
112076         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
112077         yymajor = YYNOCODE;
112078       }else{
112079          while(
112080           yypParser->yyidx >= 0 &&
112081           yymx != YYERRORSYMBOL &&
112082           (yyact = yy_find_reduce_action(
112083                         yypParser->yystack[yypParser->yyidx].stateno,
112084                         YYERRORSYMBOL)) >= YYNSTATE
112085         ){
112086           yy_pop_parser_stack(yypParser);
112087         }
112088         if( yypParser->yyidx < 0 || yymajor==0 ){
112089           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112090           yy_parse_failed(yypParser);
112091           yymajor = YYNOCODE;
112092         }else if( yymx!=YYERRORSYMBOL ){
112093           YYMINORTYPE u2;
112094           u2.YYERRSYMDT = 0;
112095           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
112096         }
112097       }
112098       yypParser->yyerrcnt = 3;
112099       yyerrorhit = 1;
112100 #elif defined(YYNOERRORRECOVERY)
112101       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
112102       ** do any kind of error recovery.  Instead, simply invoke the syntax
112103       ** error routine and continue going as if nothing had happened.
112104       **
112105       ** Applications can set this macro (for example inside %include) if
112106       ** they intend to abandon the parse upon the first syntax error seen.
112107       */
112108       yy_syntax_error(yypParser,yymajor,yyminorunion);
112109       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112110       yymajor = YYNOCODE;
112111 
112112 #else  /* YYERRORSYMBOL is not defined */
112113       /* This is what we do if the grammar does not define ERROR:
112114       **
112115       **  * Report an error message, and throw away the input token.
112116       **
112117       **  * If the input token is $, then fail the parse.
112118       **
112119       ** As before, subsequent error messages are suppressed until
112120       ** three input tokens have been successfully shifted.
112121       */
112122       if( yypParser->yyerrcnt<=0 ){
112123         yy_syntax_error(yypParser,yymajor,yyminorunion);
112124       }
112125       yypParser->yyerrcnt = 3;
112126       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
112127       if( yyendofinput ){
112128         yy_parse_failed(yypParser);
112129       }
112130       yymajor = YYNOCODE;
112131 #endif
112132     }
112133   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
112134   return;
112135 }
112136 
112137 /************** End of parse.c ***********************************************/
112138 /************** Begin file tokenize.c ****************************************/
112139 /*
112140 ** 2001 September 15
112141 **
112142 ** The author disclaims copyright to this source code.  In place of
112143 ** a legal notice, here is a blessing:
112144 **
112145 **    May you do good and not evil.
112146 **    May you find forgiveness for yourself and forgive others.
112147 **    May you share freely, never taking more than you give.
112148 **
112149 *************************************************************************
112150 ** An tokenizer for SQL
112151 **
112152 ** This file contains C code that splits an SQL input string up into
112153 ** individual tokens and sends those tokens one-by-one over to the
112154 ** parser for analysis.
112155 */
112156 /* #include <stdlib.h> */
112157 
112158 /*
112159 ** The charMap() macro maps alphabetic characters into their
112160 ** lower-case ASCII equivalent.  On ASCII machines, this is just
112161 ** an upper-to-lower case map.  On EBCDIC machines we also need
112162 ** to adjust the encoding.  Only alphabetic characters and underscores
112163 ** need to be translated.
112164 */
112165 #ifdef SQLITE_ASCII
112166 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
112167 #endif
112168 #ifdef SQLITE_EBCDIC
112169 # define charMap(X) ebcdicToAscii[(unsigned char)X]
112170 const unsigned char ebcdicToAscii[] = {
112171 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
112172    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
112173    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
112174    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
112175    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
112176    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
112177    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
112178    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
112179    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
112180    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
112181    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
112182    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
112183    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
112184    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
112185    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
112186    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
112187    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
112188 };
112189 #endif
112190 
112191 /*
112192 ** The sqlite3KeywordCode function looks up an identifier to determine if
112193 ** it is a keyword.  If it is a keyword, the token code of that keyword is
112194 ** returned.  If the input is not a keyword, TK_ID is returned.
112195 **
112196 ** The implementation of this routine was generated by a program,
112197 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
112198 ** The output of the mkkeywordhash.c program is written into a file
112199 ** named keywordhash.h and then included into this source file by
112200 ** the #include below.
112201 */
112202 /************** Include keywordhash.h in the middle of tokenize.c ************/
112203 /************** Begin file keywordhash.h *************************************/
112204 /***** This file contains automatically generated code ******
112205 **
112206 ** The code in this file has been automatically generated by
112207 **
112208 **   sqlite/tool/mkkeywordhash.c
112209 **
112210 ** The code in this file implements a function that determines whether
112211 ** or not a given identifier is really an SQL keyword.  The same thing
112212 ** might be implemented more directly using a hand-written hash table.
112213 ** But by using this automatically generated code, the size of the code
112214 ** is substantially reduced.  This is important for embedded applications
112215 ** on platforms with limited memory.
112216 */
112217 /* Hash score: 175 */
112218 static int keywordCode(const char *z, int n){
112219   /* zText[] encodes 811 bytes of keywords in 541 bytes */
112220   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
112221   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
112222   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
112223   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
112224   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
112225   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
112226   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
112227   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
112228   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
112229   /*   INITIALLY                                                          */
112230   static const char zText[540] = {
112231     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
112232     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
112233     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
112234     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
112235     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
112236     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
112237     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
112238     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
112239     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
112240     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
112241     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
112242     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
112243     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
112244     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
112245     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
112246     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
112247     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
112248     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
112249     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
112250     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
112251     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
112252     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
112253     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
112254     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
112255     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
112256     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
112257     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
112258     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
112259     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
112260     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
112261   };
112262   static const unsigned char aHash[127] = {
112263       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
112264       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
112265      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
112266        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
112267        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
112268       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
112269       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
112270       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
112271       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
112272       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
112273   };
112274   static const unsigned char aNext[121] = {
112275        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
112276        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
112277        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
112278        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
112279        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
112280       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
112281       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
112282        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
112283      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
112284       35,  64,   0,   0,
112285   };
112286   static const unsigned char aLen[121] = {
112287        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
112288        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
112289       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
112290        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
112291        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
112292        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
112293        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
112294        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
112295        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
112296        6,   4,   9,   3,
112297   };
112298   static const unsigned short int aOffset[121] = {
112299        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
112300       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
112301       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
112302      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
112303      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
112304      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
112305      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
112306      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
112307      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
112308      521, 527, 531, 536,
112309   };
112310   static const unsigned char aCode[121] = {
112311     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
112312     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
112313     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
112314     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
112315     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
112316     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
112317     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
112318     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
112319     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
112320     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
112321     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
112322     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
112323     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
112324     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
112325     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
112326     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
112327     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
112328     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
112329     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
112330     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
112331     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
112332     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
112333     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
112334     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
112335     TK_ALL,
112336   };
112337   int h, i;
112338   if( n<2 ) return TK_ID;
112339   h = ((charMap(z[0])*4) ^
112340       (charMap(z[n-1])*3) ^
112341       n) % 127;
112342   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
112343     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
112344       testcase( i==0 ); /* REINDEX */
112345       testcase( i==1 ); /* INDEXED */
112346       testcase( i==2 ); /* INDEX */
112347       testcase( i==3 ); /* DESC */
112348       testcase( i==4 ); /* ESCAPE */
112349       testcase( i==5 ); /* EACH */
112350       testcase( i==6 ); /* CHECK */
112351       testcase( i==7 ); /* KEY */
112352       testcase( i==8 ); /* BEFORE */
112353       testcase( i==9 ); /* FOREIGN */
112354       testcase( i==10 ); /* FOR */
112355       testcase( i==11 ); /* IGNORE */
112356       testcase( i==12 ); /* REGEXP */
112357       testcase( i==13 ); /* EXPLAIN */
112358       testcase( i==14 ); /* INSTEAD */
112359       testcase( i==15 ); /* ADD */
112360       testcase( i==16 ); /* DATABASE */
112361       testcase( i==17 ); /* AS */
112362       testcase( i==18 ); /* SELECT */
112363       testcase( i==19 ); /* TABLE */
112364       testcase( i==20 ); /* LEFT */
112365       testcase( i==21 ); /* THEN */
112366       testcase( i==22 ); /* END */
112367       testcase( i==23 ); /* DEFERRABLE */
112368       testcase( i==24 ); /* ELSE */
112369       testcase( i==25 ); /* EXCEPT */
112370       testcase( i==26 ); /* TRANSACTION */
112371       testcase( i==27 ); /* ACTION */
112372       testcase( i==28 ); /* ON */
112373       testcase( i==29 ); /* NATURAL */
112374       testcase( i==30 ); /* ALTER */
112375       testcase( i==31 ); /* RAISE */
112376       testcase( i==32 ); /* EXCLUSIVE */
112377       testcase( i==33 ); /* EXISTS */
112378       testcase( i==34 ); /* SAVEPOINT */
112379       testcase( i==35 ); /* INTERSECT */
112380       testcase( i==36 ); /* TRIGGER */
112381       testcase( i==37 ); /* REFERENCES */
112382       testcase( i==38 ); /* CONSTRAINT */
112383       testcase( i==39 ); /* INTO */
112384       testcase( i==40 ); /* OFFSET */
112385       testcase( i==41 ); /* OF */
112386       testcase( i==42 ); /* SET */
112387       testcase( i==43 ); /* TEMPORARY */
112388       testcase( i==44 ); /* TEMP */
112389       testcase( i==45 ); /* OR */
112390       testcase( i==46 ); /* UNIQUE */
112391       testcase( i==47 ); /* QUERY */
112392       testcase( i==48 ); /* ATTACH */
112393       testcase( i==49 ); /* HAVING */
112394       testcase( i==50 ); /* GROUP */
112395       testcase( i==51 ); /* UPDATE */
112396       testcase( i==52 ); /* BEGIN */
112397       testcase( i==53 ); /* INNER */
112398       testcase( i==54 ); /* RELEASE */
112399       testcase( i==55 ); /* BETWEEN */
112400       testcase( i==56 ); /* NOTNULL */
112401       testcase( i==57 ); /* NOT */
112402       testcase( i==58 ); /* NO */
112403       testcase( i==59 ); /* NULL */
112404       testcase( i==60 ); /* LIKE */
112405       testcase( i==61 ); /* CASCADE */
112406       testcase( i==62 ); /* ASC */
112407       testcase( i==63 ); /* DELETE */
112408       testcase( i==64 ); /* CASE */
112409       testcase( i==65 ); /* COLLATE */
112410       testcase( i==66 ); /* CREATE */
112411       testcase( i==67 ); /* CURRENT_DATE */
112412       testcase( i==68 ); /* DETACH */
112413       testcase( i==69 ); /* IMMEDIATE */
112414       testcase( i==70 ); /* JOIN */
112415       testcase( i==71 ); /* INSERT */
112416       testcase( i==72 ); /* MATCH */
112417       testcase( i==73 ); /* PLAN */
112418       testcase( i==74 ); /* ANALYZE */
112419       testcase( i==75 ); /* PRAGMA */
112420       testcase( i==76 ); /* ABORT */
112421       testcase( i==77 ); /* VALUES */
112422       testcase( i==78 ); /* VIRTUAL */
112423       testcase( i==79 ); /* LIMIT */
112424       testcase( i==80 ); /* WHEN */
112425       testcase( i==81 ); /* WHERE */
112426       testcase( i==82 ); /* RENAME */
112427       testcase( i==83 ); /* AFTER */
112428       testcase( i==84 ); /* REPLACE */
112429       testcase( i==85 ); /* AND */
112430       testcase( i==86 ); /* DEFAULT */
112431       testcase( i==87 ); /* AUTOINCREMENT */
112432       testcase( i==88 ); /* TO */
112433       testcase( i==89 ); /* IN */
112434       testcase( i==90 ); /* CAST */
112435       testcase( i==91 ); /* COLUMN */
112436       testcase( i==92 ); /* COMMIT */
112437       testcase( i==93 ); /* CONFLICT */
112438       testcase( i==94 ); /* CROSS */
112439       testcase( i==95 ); /* CURRENT_TIMESTAMP */
112440       testcase( i==96 ); /* CURRENT_TIME */
112441       testcase( i==97 ); /* PRIMARY */
112442       testcase( i==98 ); /* DEFERRED */
112443       testcase( i==99 ); /* DISTINCT */
112444       testcase( i==100 ); /* IS */
112445       testcase( i==101 ); /* DROP */
112446       testcase( i==102 ); /* FAIL */
112447       testcase( i==103 ); /* FROM */
112448       testcase( i==104 ); /* FULL */
112449       testcase( i==105 ); /* GLOB */
112450       testcase( i==106 ); /* BY */
112451       testcase( i==107 ); /* IF */
112452       testcase( i==108 ); /* ISNULL */
112453       testcase( i==109 ); /* ORDER */
112454       testcase( i==110 ); /* RESTRICT */
112455       testcase( i==111 ); /* OUTER */
112456       testcase( i==112 ); /* RIGHT */
112457       testcase( i==113 ); /* ROLLBACK */
112458       testcase( i==114 ); /* ROW */
112459       testcase( i==115 ); /* UNION */
112460       testcase( i==116 ); /* USING */
112461       testcase( i==117 ); /* VACUUM */
112462       testcase( i==118 ); /* VIEW */
112463       testcase( i==119 ); /* INITIALLY */
112464       testcase( i==120 ); /* ALL */
112465       return aCode[i];
112466     }
112467   }
112468   return TK_ID;
112469 }
112470 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
112471   return keywordCode((char*)z, n);
112472 }
112473 #define SQLITE_N_KEYWORD 121
112474 
112475 /************** End of keywordhash.h *****************************************/
112476 /************** Continuing where we left off in tokenize.c *******************/
112477 
112478 
112479 /*
112480 ** If X is a character that can be used in an identifier then
112481 ** IdChar(X) will be true.  Otherwise it is false.
112482 **
112483 ** For ASCII, any character with the high-order bit set is
112484 ** allowed in an identifier.  For 7-bit characters,
112485 ** sqlite3IsIdChar[X] must be 1.
112486 **
112487 ** For EBCDIC, the rules are more complex but have the same
112488 ** end result.
112489 **
112490 ** Ticket #1066.  the SQL standard does not allow '$' in the
112491 ** middle of identfiers.  But many SQL implementations do.
112492 ** SQLite will allow '$' in identifiers for compatibility.
112493 ** But the feature is undocumented.
112494 */
112495 #ifdef SQLITE_ASCII
112496 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112497 #endif
112498 #ifdef SQLITE_EBCDIC
112499 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
112500 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
112501     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
112502     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
112503     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
112504     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
112505     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
112506     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
112507     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
112508     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
112509     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
112510     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
112511     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
112512     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
112513 };
112514 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112515 #endif
112516 
112517 
112518 /*
112519 ** Return the length of the token that begins at z[0].
112520 ** Store the token type in *tokenType before returning.
112521 */
112522 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
112523   int i, c;
112524   switch( *z ){
112525     case ' ': case '\t': case '\n': case '\f': case '\r': {
112526       testcase( z[0]==' ' );
112527       testcase( z[0]=='\t' );
112528       testcase( z[0]=='\n' );
112529       testcase( z[0]=='\f' );
112530       testcase( z[0]=='\r' );
112531       for(i=1; sqlite3Isspace(z[i]); i++){}
112532       *tokenType = TK_SPACE;
112533       return i;
112534     }
112535     case '-': {
112536       if( z[1]=='-' ){
112537         /* IMP: R-50417-27976 -- syntax diagram for comments */
112538         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
112539         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
112540         return i;
112541       }
112542       *tokenType = TK_MINUS;
112543       return 1;
112544     }
112545     case '(': {
112546       *tokenType = TK_LP;
112547       return 1;
112548     }
112549     case ')': {
112550       *tokenType = TK_RP;
112551       return 1;
112552     }
112553     case ';': {
112554       *tokenType = TK_SEMI;
112555       return 1;
112556     }
112557     case '+': {
112558       *tokenType = TK_PLUS;
112559       return 1;
112560     }
112561     case '*': {
112562       *tokenType = TK_STAR;
112563       return 1;
112564     }
112565     case '/': {
112566       if( z[1]!='*' || z[2]==0 ){
112567         *tokenType = TK_SLASH;
112568         return 1;
112569       }
112570       /* IMP: R-50417-27976 -- syntax diagram for comments */
112571       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
112572       if( c ) i++;
112573       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
112574       return i;
112575     }
112576     case '%': {
112577       *tokenType = TK_REM;
112578       return 1;
112579     }
112580     case '=': {
112581       *tokenType = TK_EQ;
112582       return 1 + (z[1]=='=');
112583     }
112584     case '<': {
112585       if( (c=z[1])=='=' ){
112586         *tokenType = TK_LE;
112587         return 2;
112588       }else if( c=='>' ){
112589         *tokenType = TK_NE;
112590         return 2;
112591       }else if( c=='<' ){
112592         *tokenType = TK_LSHIFT;
112593         return 2;
112594       }else{
112595         *tokenType = TK_LT;
112596         return 1;
112597       }
112598     }
112599     case '>': {
112600       if( (c=z[1])=='=' ){
112601         *tokenType = TK_GE;
112602         return 2;
112603       }else if( c=='>' ){
112604         *tokenType = TK_RSHIFT;
112605         return 2;
112606       }else{
112607         *tokenType = TK_GT;
112608         return 1;
112609       }
112610     }
112611     case '!': {
112612       if( z[1]!='=' ){
112613         *tokenType = TK_ILLEGAL;
112614         return 2;
112615       }else{
112616         *tokenType = TK_NE;
112617         return 2;
112618       }
112619     }
112620     case '|': {
112621       if( z[1]!='|' ){
112622         *tokenType = TK_BITOR;
112623         return 1;
112624       }else{
112625         *tokenType = TK_CONCAT;
112626         return 2;
112627       }
112628     }
112629     case ',': {
112630       *tokenType = TK_COMMA;
112631       return 1;
112632     }
112633     case '&': {
112634       *tokenType = TK_BITAND;
112635       return 1;
112636     }
112637     case '~': {
112638       *tokenType = TK_BITNOT;
112639       return 1;
112640     }
112641     case '`':
112642     case '\'':
112643     case '"': {
112644       int delim = z[0];
112645       testcase( delim=='`' );
112646       testcase( delim=='\'' );
112647       testcase( delim=='"' );
112648       for(i=1; (c=z[i])!=0; i++){
112649         if( c==delim ){
112650           if( z[i+1]==delim ){
112651             i++;
112652           }else{
112653             break;
112654           }
112655         }
112656       }
112657       if( c=='\'' ){
112658         *tokenType = TK_STRING;
112659         return i+1;
112660       }else if( c!=0 ){
112661         *tokenType = TK_ID;
112662         return i+1;
112663       }else{
112664         *tokenType = TK_ILLEGAL;
112665         return i;
112666       }
112667     }
112668     case '.': {
112669 #ifndef SQLITE_OMIT_FLOATING_POINT
112670       if( !sqlite3Isdigit(z[1]) )
112671 #endif
112672       {
112673         *tokenType = TK_DOT;
112674         return 1;
112675       }
112676       /* If the next character is a digit, this is a floating point
112677       ** number that begins with ".".  Fall thru into the next case */
112678     }
112679     case '0': case '1': case '2': case '3': case '4':
112680     case '5': case '6': case '7': case '8': case '9': {
112681       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
112682       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
112683       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
112684       testcase( z[0]=='9' );
112685       *tokenType = TK_INTEGER;
112686       for(i=0; sqlite3Isdigit(z[i]); i++){}
112687 #ifndef SQLITE_OMIT_FLOATING_POINT
112688       if( z[i]=='.' ){
112689         i++;
112690         while( sqlite3Isdigit(z[i]) ){ i++; }
112691         *tokenType = TK_FLOAT;
112692       }
112693       if( (z[i]=='e' || z[i]=='E') &&
112694            ( sqlite3Isdigit(z[i+1])
112695             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
112696            )
112697       ){
112698         i += 2;
112699         while( sqlite3Isdigit(z[i]) ){ i++; }
112700         *tokenType = TK_FLOAT;
112701       }
112702 #endif
112703       while( IdChar(z[i]) ){
112704         *tokenType = TK_ILLEGAL;
112705         i++;
112706       }
112707       return i;
112708     }
112709     case '[': {
112710       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
112711       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
112712       return i;
112713     }
112714     case '?': {
112715       *tokenType = TK_VARIABLE;
112716       for(i=1; sqlite3Isdigit(z[i]); i++){}
112717       return i;
112718     }
112719     case '#': {
112720       for(i=1; sqlite3Isdigit(z[i]); i++){}
112721       if( i>1 ){
112722         /* Parameters of the form #NNN (where NNN is a number) are used
112723         ** internally by sqlite3NestedParse.  */
112724         *tokenType = TK_REGISTER;
112725         return i;
112726       }
112727       /* Fall through into the next case if the '#' is not followed by
112728       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
112729     }
112730 #ifndef SQLITE_OMIT_TCL_VARIABLE
112731     case '$':
112732 #endif
112733     case '@':  /* For compatibility with MS SQL Server */
112734     case ':': {
112735       int n = 0;
112736       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
112737       *tokenType = TK_VARIABLE;
112738       for(i=1; (c=z[i])!=0; i++){
112739         if( IdChar(c) ){
112740           n++;
112741 #ifndef SQLITE_OMIT_TCL_VARIABLE
112742         }else if( c=='(' && n>0 ){
112743           do{
112744             i++;
112745           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
112746           if( c==')' ){
112747             i++;
112748           }else{
112749             *tokenType = TK_ILLEGAL;
112750           }
112751           break;
112752         }else if( c==':' && z[i+1]==':' ){
112753           i++;
112754 #endif
112755         }else{
112756           break;
112757         }
112758       }
112759       if( n==0 ) *tokenType = TK_ILLEGAL;
112760       return i;
112761     }
112762 #ifndef SQLITE_OMIT_BLOB_LITERAL
112763     case 'x': case 'X': {
112764       testcase( z[0]=='x' ); testcase( z[0]=='X' );
112765       if( z[1]=='\'' ){
112766         *tokenType = TK_BLOB;
112767         for(i=2; sqlite3Isxdigit(z[i]); i++){}
112768         if( z[i]!='\'' || i%2 ){
112769           *tokenType = TK_ILLEGAL;
112770           while( z[i] && z[i]!='\'' ){ i++; }
112771         }
112772         if( z[i] ) i++;
112773         return i;
112774       }
112775       /* Otherwise fall through to the next case */
112776     }
112777 #endif
112778     default: {
112779       if( !IdChar(*z) ){
112780         break;
112781       }
112782       for(i=1; IdChar(z[i]); i++){}
112783       *tokenType = keywordCode((char*)z, i);
112784       return i;
112785     }
112786   }
112787   *tokenType = TK_ILLEGAL;
112788   return 1;
112789 }
112790 
112791 /*
112792 ** Run the parser on the given SQL string.  The parser structure is
112793 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
112794 ** then an and attempt is made to write an error message into
112795 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
112796 ** error message.
112797 */
112798 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
112799   int nErr = 0;                   /* Number of errors encountered */
112800   int i;                          /* Loop counter */
112801   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
112802   int tokenType;                  /* type of the next token */
112803   int lastTokenParsed = -1;       /* type of the previous token */
112804   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
112805   sqlite3 *db = pParse->db;       /* The database connection */
112806   int mxSqlLen;                   /* Max length of an SQL string */
112807 
112808 
112809   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
112810   if( db->activeVdbeCnt==0 ){
112811     db->u1.isInterrupted = 0;
112812   }
112813   pParse->rc = SQLITE_OK;
112814   pParse->zTail = zSql;
112815   i = 0;
112816   assert( pzErrMsg!=0 );
112817   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
112818   if( pEngine==0 ){
112819     db->mallocFailed = 1;
112820     return SQLITE_NOMEM;
112821   }
112822   assert( pParse->pNewTable==0 );
112823   assert( pParse->pNewTrigger==0 );
112824   assert( pParse->nVar==0 );
112825   assert( pParse->nzVar==0 );
112826   assert( pParse->azVar==0 );
112827   enableLookaside = db->lookaside.bEnabled;
112828   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
112829   while( !db->mallocFailed && zSql[i]!=0 ){
112830     assert( i>=0 );
112831     pParse->sLastToken.z = &zSql[i];
112832     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
112833     i += pParse->sLastToken.n;
112834     if( i>mxSqlLen ){
112835       pParse->rc = SQLITE_TOOBIG;
112836       break;
112837     }
112838     switch( tokenType ){
112839       case TK_SPACE: {
112840         if( db->u1.isInterrupted ){
112841           sqlite3ErrorMsg(pParse, "interrupt");
112842           pParse->rc = SQLITE_INTERRUPT;
112843           goto abort_parse;
112844         }
112845         break;
112846       }
112847       case TK_ILLEGAL: {
112848         sqlite3DbFree(db, *pzErrMsg);
112849         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
112850                         &pParse->sLastToken);
112851         nErr++;
112852         goto abort_parse;
112853       }
112854       case TK_SEMI: {
112855         pParse->zTail = &zSql[i];
112856         /* Fall thru into the default case */
112857       }
112858       default: {
112859         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
112860         lastTokenParsed = tokenType;
112861         if( pParse->rc!=SQLITE_OK ){
112862           goto abort_parse;
112863         }
112864         break;
112865       }
112866     }
112867   }
112868 abort_parse:
112869   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
112870     if( lastTokenParsed!=TK_SEMI ){
112871       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
112872       pParse->zTail = &zSql[i];
112873     }
112874     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
112875   }
112876 #ifdef YYTRACKMAXSTACKDEPTH
112877   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
112878       sqlite3ParserStackPeak(pEngine)
112879   );
112880 #endif /* YYDEBUG */
112881   sqlite3ParserFree(pEngine, sqlite3_free);
112882   db->lookaside.bEnabled = enableLookaside;
112883   if( db->mallocFailed ){
112884     pParse->rc = SQLITE_NOMEM;
112885   }
112886   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
112887     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
112888   }
112889   assert( pzErrMsg!=0 );
112890   if( pParse->zErrMsg ){
112891     *pzErrMsg = pParse->zErrMsg;
112892     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
112893     pParse->zErrMsg = 0;
112894     nErr++;
112895   }
112896   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
112897     sqlite3VdbeDelete(pParse->pVdbe);
112898     pParse->pVdbe = 0;
112899   }
112900 #ifndef SQLITE_OMIT_SHARED_CACHE
112901   if( pParse->nested==0 ){
112902     sqlite3DbFree(db, pParse->aTableLock);
112903     pParse->aTableLock = 0;
112904     pParse->nTableLock = 0;
112905   }
112906 #endif
112907 #ifndef SQLITE_OMIT_VIRTUALTABLE
112908   sqlite3_free(pParse->apVtabLock);
112909 #endif
112910 
112911   if( !IN_DECLARE_VTAB ){
112912     /* If the pParse->declareVtab flag is set, do not delete any table
112913     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
112914     ** will take responsibility for freeing the Table structure.
112915     */
112916     sqlite3DeleteTable(db, pParse->pNewTable);
112917   }
112918 
112919   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
112920   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
112921   sqlite3DbFree(db, pParse->azVar);
112922   sqlite3DbFree(db, pParse->aAlias);
112923   while( pParse->pAinc ){
112924     AutoincInfo *p = pParse->pAinc;
112925     pParse->pAinc = p->pNext;
112926     sqlite3DbFree(db, p);
112927   }
112928   while( pParse->pZombieTab ){
112929     Table *p = pParse->pZombieTab;
112930     pParse->pZombieTab = p->pNextZombie;
112931     sqlite3DeleteTable(db, p);
112932   }
112933   if( nErr>0 && pParse->rc==SQLITE_OK ){
112934     pParse->rc = SQLITE_ERROR;
112935   }
112936   return nErr;
112937 }
112938 
112939 /************** End of tokenize.c ********************************************/
112940 /************** Begin file complete.c ****************************************/
112941 /*
112942 ** 2001 September 15
112943 **
112944 ** The author disclaims copyright to this source code.  In place of
112945 ** a legal notice, here is a blessing:
112946 **
112947 **    May you do good and not evil.
112948 **    May you find forgiveness for yourself and forgive others.
112949 **    May you share freely, never taking more than you give.
112950 **
112951 *************************************************************************
112952 ** An tokenizer for SQL
112953 **
112954 ** This file contains C code that implements the sqlite3_complete() API.
112955 ** This code used to be part of the tokenizer.c source file.  But by
112956 ** separating it out, the code will be automatically omitted from
112957 ** static links that do not use it.
112958 */
112959 #ifndef SQLITE_OMIT_COMPLETE
112960 
112961 /*
112962 ** This is defined in tokenize.c.  We just have to import the definition.
112963 */
112964 #ifndef SQLITE_AMALGAMATION
112965 #ifdef SQLITE_ASCII
112966 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112967 #endif
112968 #ifdef SQLITE_EBCDIC
112969 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
112970 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112971 #endif
112972 #endif /* SQLITE_AMALGAMATION */
112973 
112974 
112975 /*
112976 ** Token types used by the sqlite3_complete() routine.  See the header
112977 ** comments on that procedure for additional information.
112978 */
112979 #define tkSEMI    0
112980 #define tkWS      1
112981 #define tkOTHER   2
112982 #ifndef SQLITE_OMIT_TRIGGER
112983 #define tkEXPLAIN 3
112984 #define tkCREATE  4
112985 #define tkTEMP    5
112986 #define tkTRIGGER 6
112987 #define tkEND     7
112988 #endif
112989 
112990 /*
112991 ** Return TRUE if the given SQL string ends in a semicolon.
112992 **
112993 ** Special handling is require for CREATE TRIGGER statements.
112994 ** Whenever the CREATE TRIGGER keywords are seen, the statement
112995 ** must end with ";END;".
112996 **
112997 ** This implementation uses a state machine with 8 states:
112998 **
112999 **   (0) INVALID   We have not yet seen a non-whitespace character.
113000 **
113001 **   (1) START     At the beginning or end of an SQL statement.  This routine
113002 **                 returns 1 if it ends in the START state and 0 if it ends
113003 **                 in any other state.
113004 **
113005 **   (2) NORMAL    We are in the middle of statement which ends with a single
113006 **                 semicolon.
113007 **
113008 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
113009 **                 a statement.
113010 **
113011 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
113012 **                 statement, possibly preceeded by EXPLAIN and/or followed by
113013 **                 TEMP or TEMPORARY
113014 **
113015 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
113016 **                 ended by a semicolon, the keyword END, and another semicolon.
113017 **
113018 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
113019 **                 the end of a trigger definition.
113020 **
113021 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
113022 **                 of a trigger difinition.
113023 **
113024 ** Transitions between states above are determined by tokens extracted
113025 ** from the input.  The following tokens are significant:
113026 **
113027 **   (0) tkSEMI      A semicolon.
113028 **   (1) tkWS        Whitespace.
113029 **   (2) tkOTHER     Any other SQL token.
113030 **   (3) tkEXPLAIN   The "explain" keyword.
113031 **   (4) tkCREATE    The "create" keyword.
113032 **   (5) tkTEMP      The "temp" or "temporary" keyword.
113033 **   (6) tkTRIGGER   The "trigger" keyword.
113034 **   (7) tkEND       The "end" keyword.
113035 **
113036 ** Whitespace never causes a state transition and is always ignored.
113037 ** This means that a SQL string of all whitespace is invalid.
113038 **
113039 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
113040 ** to recognize the end of a trigger can be omitted.  All we have to do
113041 ** is look for a semicolon that is not part of an string or comment.
113042 */
113043 SQLITE_API int sqlite3_complete(const char *zSql){
113044   u8 state = 0;   /* Current state, using numbers defined in header comment */
113045   u8 token;       /* Value of the next token */
113046 
113047 #ifndef SQLITE_OMIT_TRIGGER
113048   /* A complex statement machine used to detect the end of a CREATE TRIGGER
113049   ** statement.  This is the normal case.
113050   */
113051   static const u8 trans[8][8] = {
113052                      /* Token:                                                */
113053      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
113054      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
113055      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
113056      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
113057      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
113058      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
113059      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
113060      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
113061      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
113062   };
113063 #else
113064   /* If triggers are not supported by this compile then the statement machine
113065   ** used to detect the end of a statement is much simplier
113066   */
113067   static const u8 trans[3][3] = {
113068                      /* Token:           */
113069      /* State:       **  SEMI  WS  OTHER */
113070      /* 0 INVALID: */ {    1,  0,     2, },
113071      /* 1   START: */ {    1,  1,     2, },
113072      /* 2  NORMAL: */ {    1,  2,     2, },
113073   };
113074 #endif /* SQLITE_OMIT_TRIGGER */
113075 
113076   while( *zSql ){
113077     switch( *zSql ){
113078       case ';': {  /* A semicolon */
113079         token = tkSEMI;
113080         break;
113081       }
113082       case ' ':
113083       case '\r':
113084       case '\t':
113085       case '\n':
113086       case '\f': {  /* White space is ignored */
113087         token = tkWS;
113088         break;
113089       }
113090       case '/': {   /* C-style comments */
113091         if( zSql[1]!='*' ){
113092           token = tkOTHER;
113093           break;
113094         }
113095         zSql += 2;
113096         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
113097         if( zSql[0]==0 ) return 0;
113098         zSql++;
113099         token = tkWS;
113100         break;
113101       }
113102       case '-': {   /* SQL-style comments from "--" to end of line */
113103         if( zSql[1]!='-' ){
113104           token = tkOTHER;
113105           break;
113106         }
113107         while( *zSql && *zSql!='\n' ){ zSql++; }
113108         if( *zSql==0 ) return state==1;
113109         token = tkWS;
113110         break;
113111       }
113112       case '[': {   /* Microsoft-style identifiers in [...] */
113113         zSql++;
113114         while( *zSql && *zSql!=']' ){ zSql++; }
113115         if( *zSql==0 ) return 0;
113116         token = tkOTHER;
113117         break;
113118       }
113119       case '`':     /* Grave-accent quoted symbols used by MySQL */
113120       case '"':     /* single- and double-quoted strings */
113121       case '\'': {
113122         int c = *zSql;
113123         zSql++;
113124         while( *zSql && *zSql!=c ){ zSql++; }
113125         if( *zSql==0 ) return 0;
113126         token = tkOTHER;
113127         break;
113128       }
113129       default: {
113130 #ifdef SQLITE_EBCDIC
113131         unsigned char c;
113132 #endif
113133         if( IdChar((u8)*zSql) ){
113134           /* Keywords and unquoted identifiers */
113135           int nId;
113136           for(nId=1; IdChar(zSql[nId]); nId++){}
113137 #ifdef SQLITE_OMIT_TRIGGER
113138           token = tkOTHER;
113139 #else
113140           switch( *zSql ){
113141             case 'c': case 'C': {
113142               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
113143                 token = tkCREATE;
113144               }else{
113145                 token = tkOTHER;
113146               }
113147               break;
113148             }
113149             case 't': case 'T': {
113150               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
113151                 token = tkTRIGGER;
113152               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
113153                 token = tkTEMP;
113154               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
113155                 token = tkTEMP;
113156               }else{
113157                 token = tkOTHER;
113158               }
113159               break;
113160             }
113161             case 'e':  case 'E': {
113162               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
113163                 token = tkEND;
113164               }else
113165 #ifndef SQLITE_OMIT_EXPLAIN
113166               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
113167                 token = tkEXPLAIN;
113168               }else
113169 #endif
113170               {
113171                 token = tkOTHER;
113172               }
113173               break;
113174             }
113175             default: {
113176               token = tkOTHER;
113177               break;
113178             }
113179           }
113180 #endif /* SQLITE_OMIT_TRIGGER */
113181           zSql += nId-1;
113182         }else{
113183           /* Operators and special symbols */
113184           token = tkOTHER;
113185         }
113186         break;
113187       }
113188     }
113189     state = trans[state][token];
113190     zSql++;
113191   }
113192   return state==1;
113193 }
113194 
113195 #ifndef SQLITE_OMIT_UTF16
113196 /*
113197 ** This routine is the same as the sqlite3_complete() routine described
113198 ** above, except that the parameter is required to be UTF-16 encoded, not
113199 ** UTF-8.
113200 */
113201 SQLITE_API int sqlite3_complete16(const void *zSql){
113202   sqlite3_value *pVal;
113203   char const *zSql8;
113204   int rc = SQLITE_NOMEM;
113205 
113206 #ifndef SQLITE_OMIT_AUTOINIT
113207   rc = sqlite3_initialize();
113208   if( rc ) return rc;
113209 #endif
113210   pVal = sqlite3ValueNew(0);
113211   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
113212   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
113213   if( zSql8 ){
113214     rc = sqlite3_complete(zSql8);
113215   }else{
113216     rc = SQLITE_NOMEM;
113217   }
113218   sqlite3ValueFree(pVal);
113219   return sqlite3ApiExit(0, rc);
113220 }
113221 #endif /* SQLITE_OMIT_UTF16 */
113222 #endif /* SQLITE_OMIT_COMPLETE */
113223 
113224 /************** End of complete.c ********************************************/
113225 /************** Begin file main.c ********************************************/
113226 /*
113227 ** 2001 September 15
113228 **
113229 ** The author disclaims copyright to this source code.  In place of
113230 ** a legal notice, here is a blessing:
113231 **
113232 **    May you do good and not evil.
113233 **    May you find forgiveness for yourself and forgive others.
113234 **    May you share freely, never taking more than you give.
113235 **
113236 *************************************************************************
113237 ** Main file for the SQLite library.  The routines in this file
113238 ** implement the programmer interface to the library.  Routines in
113239 ** other files are for internal use by SQLite and should not be
113240 ** accessed by users of the library.
113241 */
113242 
113243 #ifdef SQLITE_ENABLE_FTS3
113244 /************** Include fts3.h in the middle of main.c ***********************/
113245 /************** Begin file fts3.h ********************************************/
113246 /*
113247 ** 2006 Oct 10
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 **
113258 ** This header file is used by programs that want to link against the
113259 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
113260 */
113261 
113262 #if 0
113263 extern "C" {
113264 #endif  /* __cplusplus */
113265 
113266 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
113267 
113268 #if 0
113269 }  /* extern "C" */
113270 #endif  /* __cplusplus */
113271 
113272 /************** End of fts3.h ************************************************/
113273 /************** Continuing where we left off in main.c ***********************/
113274 #endif
113275 #ifdef SQLITE_ENABLE_RTREE
113276 /************** Include rtree.h in the middle of main.c **********************/
113277 /************** Begin file rtree.h *******************************************/
113278 /*
113279 ** 2008 May 26
113280 **
113281 ** The author disclaims copyright to this source code.  In place of
113282 ** a legal notice, here is a blessing:
113283 **
113284 **    May you do good and not evil.
113285 **    May you find forgiveness for yourself and forgive others.
113286 **    May you share freely, never taking more than you give.
113287 **
113288 ******************************************************************************
113289 **
113290 ** This header file is used by programs that want to link against the
113291 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
113292 */
113293 
113294 #if 0
113295 extern "C" {
113296 #endif  /* __cplusplus */
113297 
113298 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
113299 
113300 #if 0
113301 }  /* extern "C" */
113302 #endif  /* __cplusplus */
113303 
113304 /************** End of rtree.h ***********************************************/
113305 /************** Continuing where we left off in main.c ***********************/
113306 #endif
113307 #ifdef SQLITE_ENABLE_ICU
113308 /************** Include sqliteicu.h in the middle of main.c ******************/
113309 /************** Begin file sqliteicu.h ***************************************/
113310 /*
113311 ** 2008 May 26
113312 **
113313 ** The author disclaims copyright to this source code.  In place of
113314 ** a legal notice, here is a blessing:
113315 **
113316 **    May you do good and not evil.
113317 **    May you find forgiveness for yourself and forgive others.
113318 **    May you share freely, never taking more than you give.
113319 **
113320 ******************************************************************************
113321 **
113322 ** This header file is used by programs that want to link against the
113323 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
113324 */
113325 
113326 #if 0
113327 extern "C" {
113328 #endif  /* __cplusplus */
113329 
113330 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
113331 
113332 #if 0
113333 }  /* extern "C" */
113334 #endif  /* __cplusplus */
113335 
113336 
113337 /************** End of sqliteicu.h *******************************************/
113338 /************** Continuing where we left off in main.c ***********************/
113339 #endif
113340 
113341 #ifndef SQLITE_AMALGAMATION
113342 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
113343 ** contains the text of SQLITE_VERSION macro.
113344 */
113345 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
113346 #endif
113347 
113348 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
113349 ** a pointer to the to the sqlite3_version[] string constant.
113350 */
113351 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
113352 
113353 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
113354 ** pointer to a string constant whose value is the same as the
113355 ** SQLITE_SOURCE_ID C preprocessor macro.
113356 */
113357 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
113358 
113359 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
113360 ** returns an integer equal to SQLITE_VERSION_NUMBER.
113361 */
113362 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
113363 
113364 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
113365 ** zero if and only if SQLite was compiled with mutexing code omitted due to
113366 ** the SQLITE_THREADSAFE compile-time option being set to 0.
113367 */
113368 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
113369 
113370 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
113371 /*
113372 ** If the following function pointer is not NULL and if
113373 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
113374 ** I/O active are written using this function.  These messages
113375 ** are intended for debugging activity only.
113376 */
113377 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
113378 #endif
113379 
113380 /*
113381 ** If the following global variable points to a string which is the
113382 ** name of a directory, then that directory will be used to store
113383 ** temporary files.
113384 **
113385 ** See also the "PRAGMA temp_store_directory" SQL command.
113386 */
113387 SQLITE_API char *sqlite3_temp_directory = 0;
113388 
113389 /*
113390 ** If the following global variable points to a string which is the
113391 ** name of a directory, then that directory will be used to store
113392 ** all database files specified with a relative pathname.
113393 **
113394 ** See also the "PRAGMA data_store_directory" SQL command.
113395 */
113396 SQLITE_API char *sqlite3_data_directory = 0;
113397 
113398 /*
113399 ** Initialize SQLite.
113400 **
113401 ** This routine must be called to initialize the memory allocation,
113402 ** VFS, and mutex subsystems prior to doing any serious work with
113403 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
113404 ** this routine will be called automatically by key routines such as
113405 ** sqlite3_open().
113406 **
113407 ** This routine is a no-op except on its very first call for the process,
113408 ** or for the first call after a call to sqlite3_shutdown.
113409 **
113410 ** The first thread to call this routine runs the initialization to
113411 ** completion.  If subsequent threads call this routine before the first
113412 ** thread has finished the initialization process, then the subsequent
113413 ** threads must block until the first thread finishes with the initialization.
113414 **
113415 ** The first thread might call this routine recursively.  Recursive
113416 ** calls to this routine should not block, of course.  Otherwise the
113417 ** initialization process would never complete.
113418 **
113419 ** Let X be the first thread to enter this routine.  Let Y be some other
113420 ** thread.  Then while the initial invocation of this routine by X is
113421 ** incomplete, it is required that:
113422 **
113423 **    *  Calls to this routine from Y must block until the outer-most
113424 **       call by X completes.
113425 **
113426 **    *  Recursive calls to this routine from thread X return immediately
113427 **       without blocking.
113428 */
113429 SQLITE_API int sqlite3_initialize(void){
113430   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
113431   int rc;                                      /* Result code */
113432 
113433 #ifdef SQLITE_OMIT_WSD
113434   rc = sqlite3_wsd_init(4096, 24);
113435   if( rc!=SQLITE_OK ){
113436     return rc;
113437   }
113438 #endif
113439 
113440   /* If SQLite is already completely initialized, then this call
113441   ** to sqlite3_initialize() should be a no-op.  But the initialization
113442   ** must be complete.  So isInit must not be set until the very end
113443   ** of this routine.
113444   */
113445   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
113446 
113447 #ifdef SQLITE_ENABLE_SQLLOG
113448   {
113449     extern void sqlite3_init_sqllog(void);
113450     sqlite3_init_sqllog();
113451   }
113452 #endif
113453 
113454   /* Make sure the mutex subsystem is initialized.  If unable to
113455   ** initialize the mutex subsystem, return early with the error.
113456   ** If the system is so sick that we are unable to allocate a mutex,
113457   ** there is not much SQLite is going to be able to do.
113458   **
113459   ** The mutex subsystem must take care of serializing its own
113460   ** initialization.
113461   */
113462   rc = sqlite3MutexInit();
113463   if( rc ) return rc;
113464 
113465   /* Initialize the malloc() system and the recursive pInitMutex mutex.
113466   ** This operation is protected by the STATIC_MASTER mutex.  Note that
113467   ** MutexAlloc() is called for a static mutex prior to initializing the
113468   ** malloc subsystem - this implies that the allocation of a static
113469   ** mutex must not require support from the malloc subsystem.
113470   */
113471   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
113472   sqlite3_mutex_enter(pMaster);
113473   sqlite3GlobalConfig.isMutexInit = 1;
113474   if( !sqlite3GlobalConfig.isMallocInit ){
113475     rc = sqlite3MallocInit();
113476   }
113477   if( rc==SQLITE_OK ){
113478     sqlite3GlobalConfig.isMallocInit = 1;
113479     if( !sqlite3GlobalConfig.pInitMutex ){
113480       sqlite3GlobalConfig.pInitMutex =
113481            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
113482       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
113483         rc = SQLITE_NOMEM;
113484       }
113485     }
113486   }
113487   if( rc==SQLITE_OK ){
113488     sqlite3GlobalConfig.nRefInitMutex++;
113489   }
113490   sqlite3_mutex_leave(pMaster);
113491 
113492   /* If rc is not SQLITE_OK at this point, then either the malloc
113493   ** subsystem could not be initialized or the system failed to allocate
113494   ** the pInitMutex mutex. Return an error in either case.  */
113495   if( rc!=SQLITE_OK ){
113496     return rc;
113497   }
113498 
113499   /* Do the rest of the initialization under the recursive mutex so
113500   ** that we will be able to handle recursive calls into
113501   ** sqlite3_initialize().  The recursive calls normally come through
113502   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
113503   ** recursive calls might also be possible.
113504   **
113505   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
113506   ** to the xInit method, so the xInit method need not be threadsafe.
113507   **
113508   ** The following mutex is what serializes access to the appdef pcache xInit
113509   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
113510   ** call to sqlite3PcacheInitialize().
113511   */
113512   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
113513   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
113514     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
113515     sqlite3GlobalConfig.inProgress = 1;
113516     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
113517     sqlite3RegisterGlobalFunctions();
113518     if( sqlite3GlobalConfig.isPCacheInit==0 ){
113519       rc = sqlite3PcacheInitialize();
113520     }
113521     if( rc==SQLITE_OK ){
113522       sqlite3GlobalConfig.isPCacheInit = 1;
113523       rc = sqlite3OsInit();
113524     }
113525     if( rc==SQLITE_OK ){
113526       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
113527           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
113528       sqlite3GlobalConfig.isInit = 1;
113529     }
113530     sqlite3GlobalConfig.inProgress = 0;
113531   }
113532   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
113533 
113534   /* Go back under the static mutex and clean up the recursive
113535   ** mutex to prevent a resource leak.
113536   */
113537   sqlite3_mutex_enter(pMaster);
113538   sqlite3GlobalConfig.nRefInitMutex--;
113539   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
113540     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
113541     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
113542     sqlite3GlobalConfig.pInitMutex = 0;
113543   }
113544   sqlite3_mutex_leave(pMaster);
113545 
113546   /* The following is just a sanity check to make sure SQLite has
113547   ** been compiled correctly.  It is important to run this code, but
113548   ** we don't want to run it too often and soak up CPU cycles for no
113549   ** reason.  So we run it once during initialization.
113550   */
113551 #ifndef NDEBUG
113552 #ifndef SQLITE_OMIT_FLOATING_POINT
113553   /* This section of code's only "output" is via assert() statements. */
113554   if ( rc==SQLITE_OK ){
113555     u64 x = (((u64)1)<<63)-1;
113556     double y;
113557     assert(sizeof(x)==8);
113558     assert(sizeof(x)==sizeof(y));
113559     memcpy(&y, &x, 8);
113560     assert( sqlite3IsNaN(y) );
113561   }
113562 #endif
113563 #endif
113564 
113565   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
113566   ** compile-time option.
113567   */
113568 #ifdef SQLITE_EXTRA_INIT
113569   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
113570     int SQLITE_EXTRA_INIT(const char*);
113571     rc = SQLITE_EXTRA_INIT(0);
113572   }
113573 #endif
113574 
113575   return rc;
113576 }
113577 
113578 /*
113579 ** Undo the effects of sqlite3_initialize().  Must not be called while
113580 ** there are outstanding database connections or memory allocations or
113581 ** while any part of SQLite is otherwise in use in any thread.  This
113582 ** routine is not threadsafe.  But it is safe to invoke this routine
113583 ** on when SQLite is already shut down.  If SQLite is already shut down
113584 ** when this routine is invoked, then this routine is a harmless no-op.
113585 */
113586 SQLITE_API int sqlite3_shutdown(void){
113587   if( sqlite3GlobalConfig.isInit ){
113588 #ifdef SQLITE_EXTRA_SHUTDOWN
113589     void SQLITE_EXTRA_SHUTDOWN(void);
113590     SQLITE_EXTRA_SHUTDOWN();
113591 #endif
113592     sqlite3_os_end();
113593     sqlite3_reset_auto_extension();
113594     sqlite3GlobalConfig.isInit = 0;
113595   }
113596   if( sqlite3GlobalConfig.isPCacheInit ){
113597     sqlite3PcacheShutdown();
113598     sqlite3GlobalConfig.isPCacheInit = 0;
113599   }
113600   if( sqlite3GlobalConfig.isMallocInit ){
113601     sqlite3MallocEnd();
113602     sqlite3GlobalConfig.isMallocInit = 0;
113603 
113604 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
113605     /* The heap subsystem has now been shutdown and these values are supposed
113606     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
113607     ** which would rely on that heap subsystem; therefore, make sure these
113608     ** values cannot refer to heap memory that was just invalidated when the
113609     ** heap subsystem was shutdown.  This is only done if the current call to
113610     ** this function resulted in the heap subsystem actually being shutdown.
113611     */
113612     sqlite3_data_directory = 0;
113613     sqlite3_temp_directory = 0;
113614 #endif
113615   }
113616   if( sqlite3GlobalConfig.isMutexInit ){
113617     sqlite3MutexEnd();
113618     sqlite3GlobalConfig.isMutexInit = 0;
113619   }
113620 
113621   return SQLITE_OK;
113622 }
113623 
113624 /*
113625 ** This API allows applications to modify the global configuration of
113626 ** the SQLite library at run-time.
113627 **
113628 ** This routine should only be called when there are no outstanding
113629 ** database connections or memory allocations.  This routine is not
113630 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
113631 ** behavior.
113632 */
113633 SQLITE_API int sqlite3_config(int op, ...){
113634   va_list ap;
113635   int rc = SQLITE_OK;
113636 
113637   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
113638   ** the SQLite library is in use. */
113639   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
113640 
113641   va_start(ap, op);
113642   switch( op ){
113643 
113644     /* Mutex configuration options are only available in a threadsafe
113645     ** compile.
113646     */
113647 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
113648     case SQLITE_CONFIG_SINGLETHREAD: {
113649       /* Disable all mutexing */
113650       sqlite3GlobalConfig.bCoreMutex = 0;
113651       sqlite3GlobalConfig.bFullMutex = 0;
113652       break;
113653     }
113654     case SQLITE_CONFIG_MULTITHREAD: {
113655       /* Disable mutexing of database connections */
113656       /* Enable mutexing of core data structures */
113657       sqlite3GlobalConfig.bCoreMutex = 1;
113658       sqlite3GlobalConfig.bFullMutex = 0;
113659       break;
113660     }
113661     case SQLITE_CONFIG_SERIALIZED: {
113662       /* Enable all mutexing */
113663       sqlite3GlobalConfig.bCoreMutex = 1;
113664       sqlite3GlobalConfig.bFullMutex = 1;
113665       break;
113666     }
113667     case SQLITE_CONFIG_MUTEX: {
113668       /* Specify an alternative mutex implementation */
113669       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
113670       break;
113671     }
113672     case SQLITE_CONFIG_GETMUTEX: {
113673       /* Retrieve the current mutex implementation */
113674       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
113675       break;
113676     }
113677 #endif
113678 
113679 
113680     case SQLITE_CONFIG_MALLOC: {
113681       /* Specify an alternative malloc implementation */
113682       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
113683       break;
113684     }
113685     case SQLITE_CONFIG_GETMALLOC: {
113686       /* Retrieve the current malloc() implementation */
113687       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
113688       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
113689       break;
113690     }
113691     case SQLITE_CONFIG_MEMSTATUS: {
113692       /* Enable or disable the malloc status collection */
113693       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
113694       break;
113695     }
113696     case SQLITE_CONFIG_SCRATCH: {
113697       /* Designate a buffer for scratch memory space */
113698       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
113699       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
113700       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
113701       break;
113702     }
113703     case SQLITE_CONFIG_PAGECACHE: {
113704       /* Designate a buffer for page cache memory space */
113705       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
113706       sqlite3GlobalConfig.szPage = va_arg(ap, int);
113707       sqlite3GlobalConfig.nPage = va_arg(ap, int);
113708       break;
113709     }
113710 
113711     case SQLITE_CONFIG_PCACHE: {
113712       /* no-op */
113713       break;
113714     }
113715     case SQLITE_CONFIG_GETPCACHE: {
113716       /* now an error */
113717       rc = SQLITE_ERROR;
113718       break;
113719     }
113720 
113721     case SQLITE_CONFIG_PCACHE2: {
113722       /* Specify an alternative page cache implementation */
113723       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
113724       break;
113725     }
113726     case SQLITE_CONFIG_GETPCACHE2: {
113727       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
113728         sqlite3PCacheSetDefault();
113729       }
113730       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
113731       break;
113732     }
113733 
113734 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
113735     case SQLITE_CONFIG_HEAP: {
113736       /* Designate a buffer for heap memory space */
113737       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
113738       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
113739       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
113740 
113741       if( sqlite3GlobalConfig.mnReq<1 ){
113742         sqlite3GlobalConfig.mnReq = 1;
113743       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
113744         /* cap min request size at 2^12 */
113745         sqlite3GlobalConfig.mnReq = (1<<12);
113746       }
113747 
113748       if( sqlite3GlobalConfig.pHeap==0 ){
113749         /* If the heap pointer is NULL, then restore the malloc implementation
113750         ** back to NULL pointers too.  This will cause the malloc to go
113751         ** back to its default implementation when sqlite3_initialize() is
113752         ** run.
113753         */
113754         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
113755       }else{
113756         /* The heap pointer is not NULL, then install one of the
113757         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
113758         ** ENABLE_MEMSYS5 is defined, return an error.
113759         */
113760 #ifdef SQLITE_ENABLE_MEMSYS3
113761         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
113762 #endif
113763 #ifdef SQLITE_ENABLE_MEMSYS5
113764         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
113765 #endif
113766       }
113767       break;
113768     }
113769 #endif
113770 
113771     case SQLITE_CONFIG_LOOKASIDE: {
113772       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
113773       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
113774       break;
113775     }
113776 
113777     /* Record a pointer to the logger funcction and its first argument.
113778     ** The default is NULL.  Logging is disabled if the function pointer is
113779     ** NULL.
113780     */
113781     case SQLITE_CONFIG_LOG: {
113782       /* MSVC is picky about pulling func ptrs from va lists.
113783       ** http://support.microsoft.com/kb/47961
113784       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
113785       */
113786       typedef void(*LOGFUNC_t)(void*,int,const char*);
113787       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
113788       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
113789       break;
113790     }
113791 
113792     case SQLITE_CONFIG_URI: {
113793       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
113794       break;
113795     }
113796 
113797     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
113798       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
113799       break;
113800     }
113801 
113802 #ifdef SQLITE_ENABLE_SQLLOG
113803     case SQLITE_CONFIG_SQLLOG: {
113804       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
113805       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
113806       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
113807       break;
113808     }
113809 #endif
113810 
113811     default: {
113812       rc = SQLITE_ERROR;
113813       break;
113814     }
113815   }
113816   va_end(ap);
113817   return rc;
113818 }
113819 
113820 /*
113821 ** Set up the lookaside buffers for a database connection.
113822 ** Return SQLITE_OK on success.
113823 ** If lookaside is already active, return SQLITE_BUSY.
113824 **
113825 ** The sz parameter is the number of bytes in each lookaside slot.
113826 ** The cnt parameter is the number of slots.  If pStart is NULL the
113827 ** space for the lookaside memory is obtained from sqlite3_malloc().
113828 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
113829 ** the lookaside memory.
113830 */
113831 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
113832   void *pStart;
113833   if( db->lookaside.nOut ){
113834     return SQLITE_BUSY;
113835   }
113836   /* Free any existing lookaside buffer for this handle before
113837   ** allocating a new one so we don't have to have space for
113838   ** both at the same time.
113839   */
113840   if( db->lookaside.bMalloced ){
113841     sqlite3_free(db->lookaside.pStart);
113842   }
113843   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
113844   ** than a pointer to be useful.
113845   */
113846   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
113847   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
113848   if( cnt<0 ) cnt = 0;
113849   if( sz==0 || cnt==0 ){
113850     sz = 0;
113851     pStart = 0;
113852   }else if( pBuf==0 ){
113853     sqlite3BeginBenignMalloc();
113854     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
113855     sqlite3EndBenignMalloc();
113856     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
113857   }else{
113858     pStart = pBuf;
113859   }
113860   db->lookaside.pStart = pStart;
113861   db->lookaside.pFree = 0;
113862   db->lookaside.sz = (u16)sz;
113863   if( pStart ){
113864     int i;
113865     LookasideSlot *p;
113866     assert( sz > (int)sizeof(LookasideSlot*) );
113867     p = (LookasideSlot*)pStart;
113868     for(i=cnt-1; i>=0; i--){
113869       p->pNext = db->lookaside.pFree;
113870       db->lookaside.pFree = p;
113871       p = (LookasideSlot*)&((u8*)p)[sz];
113872     }
113873     db->lookaside.pEnd = p;
113874     db->lookaside.bEnabled = 1;
113875     db->lookaside.bMalloced = pBuf==0 ?1:0;
113876   }else{
113877     db->lookaside.pEnd = 0;
113878     db->lookaside.bEnabled = 0;
113879     db->lookaside.bMalloced = 0;
113880   }
113881   return SQLITE_OK;
113882 }
113883 
113884 /*
113885 ** Return the mutex associated with a database connection.
113886 */
113887 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
113888   return db->mutex;
113889 }
113890 
113891 /*
113892 ** Free up as much memory as we can from the given database
113893 ** connection.
113894 */
113895 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
113896   int i;
113897   sqlite3_mutex_enter(db->mutex);
113898   sqlite3BtreeEnterAll(db);
113899   for(i=0; i<db->nDb; i++){
113900     Btree *pBt = db->aDb[i].pBt;
113901     if( pBt ){
113902       Pager *pPager = sqlite3BtreePager(pBt);
113903       sqlite3PagerShrink(pPager);
113904     }
113905   }
113906   sqlite3BtreeLeaveAll(db);
113907   sqlite3_mutex_leave(db->mutex);
113908   return SQLITE_OK;
113909 }
113910 
113911 /*
113912 ** Configuration settings for an individual database connection
113913 */
113914 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
113915   va_list ap;
113916   int rc;
113917   va_start(ap, op);
113918   switch( op ){
113919     case SQLITE_DBCONFIG_LOOKASIDE: {
113920       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
113921       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
113922       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
113923       rc = setupLookaside(db, pBuf, sz, cnt);
113924       break;
113925     }
113926     default: {
113927       static const struct {
113928         int op;      /* The opcode */
113929         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
113930       } aFlagOp[] = {
113931         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
113932         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
113933       };
113934       unsigned int i;
113935       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
113936       for(i=0; i<ArraySize(aFlagOp); i++){
113937         if( aFlagOp[i].op==op ){
113938           int onoff = va_arg(ap, int);
113939           int *pRes = va_arg(ap, int*);
113940           int oldFlags = db->flags;
113941           if( onoff>0 ){
113942             db->flags |= aFlagOp[i].mask;
113943           }else if( onoff==0 ){
113944             db->flags &= ~aFlagOp[i].mask;
113945           }
113946           if( oldFlags!=db->flags ){
113947             sqlite3ExpirePreparedStatements(db);
113948           }
113949           if( pRes ){
113950             *pRes = (db->flags & aFlagOp[i].mask)!=0;
113951           }
113952           rc = SQLITE_OK;
113953           break;
113954         }
113955       }
113956       break;
113957     }
113958   }
113959   va_end(ap);
113960   return rc;
113961 }
113962 
113963 
113964 /*
113965 ** Return true if the buffer z[0..n-1] contains all spaces.
113966 */
113967 static int allSpaces(const char *z, int n){
113968   while( n>0 && z[n-1]==' ' ){ n--; }
113969   return n==0;
113970 }
113971 
113972 /*
113973 ** This is the default collating function named "BINARY" which is always
113974 ** available.
113975 **
113976 ** If the padFlag argument is not NULL then space padding at the end
113977 ** of strings is ignored.  This implements the RTRIM collation.
113978 */
113979 static int binCollFunc(
113980   void *padFlag,
113981   int nKey1, const void *pKey1,
113982   int nKey2, const void *pKey2
113983 ){
113984   int rc, n;
113985   n = nKey1<nKey2 ? nKey1 : nKey2;
113986   rc = memcmp(pKey1, pKey2, n);
113987   if( rc==0 ){
113988     if( padFlag
113989      && allSpaces(((char*)pKey1)+n, nKey1-n)
113990      && allSpaces(((char*)pKey2)+n, nKey2-n)
113991     ){
113992       /* Leave rc unchanged at 0 */
113993     }else{
113994       rc = nKey1 - nKey2;
113995     }
113996   }
113997   return rc;
113998 }
113999 
114000 /*
114001 ** Another built-in collating sequence: NOCASE.
114002 **
114003 ** This collating sequence is intended to be used for "case independant
114004 ** comparison". SQLite's knowledge of upper and lower case equivalents
114005 ** extends only to the 26 characters used in the English language.
114006 **
114007 ** At the moment there is only a UTF-8 implementation.
114008 */
114009 static int nocaseCollatingFunc(
114010   void *NotUsed,
114011   int nKey1, const void *pKey1,
114012   int nKey2, const void *pKey2
114013 ){
114014   int r = sqlite3StrNICmp(
114015       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
114016   UNUSED_PARAMETER(NotUsed);
114017   if( 0==r ){
114018     r = nKey1-nKey2;
114019   }
114020   return r;
114021 }
114022 
114023 /*
114024 ** Return the ROWID of the most recent insert
114025 */
114026 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
114027   return db->lastRowid;
114028 }
114029 
114030 /*
114031 ** Return the number of changes in the most recent call to sqlite3_exec().
114032 */
114033 SQLITE_API int sqlite3_changes(sqlite3 *db){
114034   return db->nChange;
114035 }
114036 
114037 /*
114038 ** Return the number of changes since the database handle was opened.
114039 */
114040 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
114041   return db->nTotalChange;
114042 }
114043 
114044 /*
114045 ** Close all open savepoints. This function only manipulates fields of the
114046 ** database handle object, it does not close any savepoints that may be open
114047 ** at the b-tree/pager level.
114048 */
114049 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
114050   while( db->pSavepoint ){
114051     Savepoint *pTmp = db->pSavepoint;
114052     db->pSavepoint = pTmp->pNext;
114053     sqlite3DbFree(db, pTmp);
114054   }
114055   db->nSavepoint = 0;
114056   db->nStatement = 0;
114057   db->isTransactionSavepoint = 0;
114058 }
114059 
114060 /*
114061 ** Invoke the destructor function associated with FuncDef p, if any. Except,
114062 ** if this is not the last copy of the function, do not invoke it. Multiple
114063 ** copies of a single function are created when create_function() is called
114064 ** with SQLITE_ANY as the encoding.
114065 */
114066 static void functionDestroy(sqlite3 *db, FuncDef *p){
114067   FuncDestructor *pDestructor = p->pDestructor;
114068   if( pDestructor ){
114069     pDestructor->nRef--;
114070     if( pDestructor->nRef==0 ){
114071       pDestructor->xDestroy(pDestructor->pUserData);
114072       sqlite3DbFree(db, pDestructor);
114073     }
114074   }
114075 }
114076 
114077 /*
114078 ** Disconnect all sqlite3_vtab objects that belong to database connection
114079 ** db. This is called when db is being closed.
114080 */
114081 static void disconnectAllVtab(sqlite3 *db){
114082 #ifndef SQLITE_OMIT_VIRTUALTABLE
114083   int i;
114084   sqlite3BtreeEnterAll(db);
114085   for(i=0; i<db->nDb; i++){
114086     Schema *pSchema = db->aDb[i].pSchema;
114087     if( db->aDb[i].pSchema ){
114088       HashElem *p;
114089       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
114090         Table *pTab = (Table *)sqliteHashData(p);
114091         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
114092       }
114093     }
114094   }
114095   sqlite3BtreeLeaveAll(db);
114096 #else
114097   UNUSED_PARAMETER(db);
114098 #endif
114099 }
114100 
114101 /*
114102 ** Return TRUE if database connection db has unfinalized prepared
114103 ** statements or unfinished sqlite3_backup objects.
114104 */
114105 static int connectionIsBusy(sqlite3 *db){
114106   int j;
114107   assert( sqlite3_mutex_held(db->mutex) );
114108   if( db->pVdbe ) return 1;
114109   for(j=0; j<db->nDb; j++){
114110     Btree *pBt = db->aDb[j].pBt;
114111     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
114112   }
114113   return 0;
114114 }
114115 
114116 /*
114117 ** Close an existing SQLite database
114118 */
114119 static int sqlite3Close(sqlite3 *db, int forceZombie){
114120   if( !db ){
114121     return SQLITE_OK;
114122   }
114123   if( !sqlite3SafetyCheckSickOrOk(db) ){
114124     return SQLITE_MISUSE_BKPT;
114125   }
114126   sqlite3_mutex_enter(db->mutex);
114127 
114128   /* Force xDisconnect calls on all virtual tables */
114129   disconnectAllVtab(db);
114130 
114131   /* If a transaction is open, the disconnectAllVtab() call above
114132   ** will not have called the xDisconnect() method on any virtual
114133   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
114134   ** call will do so. We need to do this before the check for active
114135   ** SQL statements below, as the v-table implementation may be storing
114136   ** some prepared statements internally.
114137   */
114138   sqlite3VtabRollback(db);
114139 
114140   /* Legacy behavior (sqlite3_close() behavior) is to return
114141   ** SQLITE_BUSY if the connection can not be closed immediately.
114142   */
114143   if( !forceZombie && connectionIsBusy(db) ){
114144     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
114145        "statements or unfinished backups");
114146     sqlite3_mutex_leave(db->mutex);
114147     return SQLITE_BUSY;
114148   }
114149 
114150 #ifdef SQLITE_ENABLE_SQLLOG
114151   if( sqlite3GlobalConfig.xSqllog ){
114152     /* Closing the handle. Fourth parameter is passed the value 2. */
114153     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
114154   }
114155 #endif
114156 
114157   /* Convert the connection into a zombie and then close it.
114158   */
114159   db->magic = SQLITE_MAGIC_ZOMBIE;
114160   sqlite3LeaveMutexAndCloseZombie(db);
114161   return SQLITE_OK;
114162 }
114163 
114164 /*
114165 ** Two variations on the public interface for closing a database
114166 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
114167 ** leaves the connection option if there are unfinalized prepared
114168 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
114169 ** version forces the connection to become a zombie if there are
114170 ** unclosed resources, and arranges for deallocation when the last
114171 ** prepare statement or sqlite3_backup closes.
114172 */
114173 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
114174 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
114175 
114176 
114177 /*
114178 ** Close the mutex on database connection db.
114179 **
114180 ** Furthermore, if database connection db is a zombie (meaning that there
114181 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
114182 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
114183 ** finished, then free all resources.
114184 */
114185 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
114186   HashElem *i;                    /* Hash table iterator */
114187   int j;
114188 
114189   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
114190   ** or if the connection has not yet been closed by sqlite3_close_v2(),
114191   ** then just leave the mutex and return.
114192   */
114193   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
114194     sqlite3_mutex_leave(db->mutex);
114195     return;
114196   }
114197 
114198   /* If we reach this point, it means that the database connection has
114199   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
114200   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
114201   ** go ahead and free all resources.
114202   */
114203 
114204   /* Free any outstanding Savepoint structures. */
114205   sqlite3CloseSavepoints(db);
114206 
114207   /* Close all database connections */
114208   for(j=0; j<db->nDb; j++){
114209     struct Db *pDb = &db->aDb[j];
114210     if( pDb->pBt ){
114211       sqlite3BtreeClose(pDb->pBt);
114212       pDb->pBt = 0;
114213       if( j!=1 ){
114214         pDb->pSchema = 0;
114215       }
114216     }
114217   }
114218   /* Clear the TEMP schema separately and last */
114219   if( db->aDb[1].pSchema ){
114220     sqlite3SchemaClear(db->aDb[1].pSchema);
114221   }
114222   sqlite3VtabUnlockList(db);
114223 
114224   /* Free up the array of auxiliary databases */
114225   sqlite3CollapseDatabaseArray(db);
114226   assert( db->nDb<=2 );
114227   assert( db->aDb==db->aDbStatic );
114228 
114229   /* Tell the code in notify.c that the connection no longer holds any
114230   ** locks and does not require any further unlock-notify callbacks.
114231   */
114232   sqlite3ConnectionClosed(db);
114233 
114234   for(j=0; j<ArraySize(db->aFunc.a); j++){
114235     FuncDef *pNext, *pHash, *p;
114236     for(p=db->aFunc.a[j]; p; p=pHash){
114237       pHash = p->pHash;
114238       while( p ){
114239         functionDestroy(db, p);
114240         pNext = p->pNext;
114241         sqlite3DbFree(db, p);
114242         p = pNext;
114243       }
114244     }
114245   }
114246   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
114247     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
114248     /* Invoke any destructors registered for collation sequence user data. */
114249     for(j=0; j<3; j++){
114250       if( pColl[j].xDel ){
114251         pColl[j].xDel(pColl[j].pUser);
114252       }
114253     }
114254     sqlite3DbFree(db, pColl);
114255   }
114256   sqlite3HashClear(&db->aCollSeq);
114257 #ifndef SQLITE_OMIT_VIRTUALTABLE
114258   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
114259     Module *pMod = (Module *)sqliteHashData(i);
114260     if( pMod->xDestroy ){
114261       pMod->xDestroy(pMod->pAux);
114262     }
114263     sqlite3DbFree(db, pMod);
114264   }
114265   sqlite3HashClear(&db->aModule);
114266 #endif
114267 
114268   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
114269   if( db->pErr ){
114270     sqlite3ValueFree(db->pErr);
114271   }
114272   sqlite3CloseExtensions(db);
114273 
114274   db->magic = SQLITE_MAGIC_ERROR;
114275 
114276   /* The temp-database schema is allocated differently from the other schema
114277   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
114278   ** So it needs to be freed here. Todo: Why not roll the temp schema into
114279   ** the same sqliteMalloc() as the one that allocates the database
114280   ** structure?
114281   */
114282   sqlite3DbFree(db, db->aDb[1].pSchema);
114283   sqlite3_mutex_leave(db->mutex);
114284   db->magic = SQLITE_MAGIC_CLOSED;
114285   sqlite3_mutex_free(db->mutex);
114286   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
114287   if( db->lookaside.bMalloced ){
114288     sqlite3_free(db->lookaside.pStart);
114289   }
114290   sqlite3_free(db);
114291 }
114292 
114293 /*
114294 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
114295 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
114296 ** breaker") and made to return tripCode if there are any further
114297 ** attempts to use that cursor.
114298 */
114299 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
114300   int i;
114301   int inTrans = 0;
114302   assert( sqlite3_mutex_held(db->mutex) );
114303   sqlite3BeginBenignMalloc();
114304   for(i=0; i<db->nDb; i++){
114305     Btree *p = db->aDb[i].pBt;
114306     if( p ){
114307       if( sqlite3BtreeIsInTrans(p) ){
114308         inTrans = 1;
114309       }
114310       sqlite3BtreeRollback(p, tripCode);
114311       db->aDb[i].inTrans = 0;
114312     }
114313   }
114314   sqlite3VtabRollback(db);
114315   sqlite3EndBenignMalloc();
114316 
114317   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
114318     sqlite3ExpirePreparedStatements(db);
114319     sqlite3ResetAllSchemasOfConnection(db);
114320   }
114321 
114322   /* Any deferred constraint violations have now been resolved. */
114323   db->nDeferredCons = 0;
114324 
114325   /* If one has been configured, invoke the rollback-hook callback */
114326   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
114327     db->xRollbackCallback(db->pRollbackArg);
114328   }
114329 }
114330 
114331 /*
114332 ** Return a static string that describes the kind of error specified in the
114333 ** argument.
114334 */
114335 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
114336   static const char* const aMsg[] = {
114337     /* SQLITE_OK          */ "not an error",
114338     /* SQLITE_ERROR       */ "SQL logic error or missing database",
114339     /* SQLITE_INTERNAL    */ 0,
114340     /* SQLITE_PERM        */ "access permission denied",
114341     /* SQLITE_ABORT       */ "callback requested query abort",
114342     /* SQLITE_BUSY        */ "database is locked",
114343     /* SQLITE_LOCKED      */ "database table is locked",
114344     /* SQLITE_NOMEM       */ "out of memory",
114345     /* SQLITE_READONLY    */ "attempt to write a readonly database",
114346     /* SQLITE_INTERRUPT   */ "interrupted",
114347     /* SQLITE_IOERR       */ "disk I/O error",
114348     /* SQLITE_CORRUPT     */ "database disk image is malformed",
114349     /* SQLITE_NOTFOUND    */ "unknown operation",
114350     /* SQLITE_FULL        */ "database or disk is full",
114351     /* SQLITE_CANTOPEN    */ "unable to open database file",
114352     /* SQLITE_PROTOCOL    */ "locking protocol",
114353     /* SQLITE_EMPTY       */ "table contains no data",
114354     /* SQLITE_SCHEMA      */ "database schema has changed",
114355     /* SQLITE_TOOBIG      */ "string or blob too big",
114356     /* SQLITE_CONSTRAINT  */ "constraint failed",
114357     /* SQLITE_MISMATCH    */ "datatype mismatch",
114358     /* SQLITE_MISUSE      */ "library routine called out of sequence",
114359     /* SQLITE_NOLFS       */ "large file support is disabled",
114360     /* SQLITE_AUTH        */ "authorization denied",
114361     /* SQLITE_FORMAT      */ "auxiliary database format error",
114362     /* SQLITE_RANGE       */ "bind or column index out of range",
114363     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
114364   };
114365   const char *zErr = "unknown error";
114366   switch( rc ){
114367     case SQLITE_ABORT_ROLLBACK: {
114368       zErr = "abort due to ROLLBACK";
114369       break;
114370     }
114371     default: {
114372       rc &= 0xff;
114373       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
114374         zErr = aMsg[rc];
114375       }
114376       break;
114377     }
114378   }
114379   return zErr;
114380 }
114381 
114382 /*
114383 ** This routine implements a busy callback that sleeps and tries
114384 ** again until a timeout value is reached.  The timeout value is
114385 ** an integer number of milliseconds passed in as the first
114386 ** argument.
114387 */
114388 static int sqliteDefaultBusyCallback(
114389  void *ptr,               /* Database connection */
114390  int count                /* Number of times table has been busy */
114391 ){
114392 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
114393   static const u8 delays[] =
114394      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
114395   static const u8 totals[] =
114396      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
114397 # define NDELAY ArraySize(delays)
114398   sqlite3 *db = (sqlite3 *)ptr;
114399   int timeout = db->busyTimeout;
114400   int delay, prior;
114401 
114402   assert( count>=0 );
114403   if( count < NDELAY ){
114404     delay = delays[count];
114405     prior = totals[count];
114406   }else{
114407     delay = delays[NDELAY-1];
114408     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
114409   }
114410   if( prior + delay > timeout ){
114411     delay = timeout - prior;
114412     if( delay<=0 ) return 0;
114413   }
114414   sqlite3OsSleep(db->pVfs, delay*1000);
114415   return 1;
114416 #else
114417   sqlite3 *db = (sqlite3 *)ptr;
114418   int timeout = ((sqlite3 *)ptr)->busyTimeout;
114419   if( (count+1)*1000 > timeout ){
114420     return 0;
114421   }
114422   sqlite3OsSleep(db->pVfs, 1000000);
114423   return 1;
114424 #endif
114425 }
114426 
114427 /*
114428 ** Invoke the given busy handler.
114429 **
114430 ** This routine is called when an operation failed with a lock.
114431 ** If this routine returns non-zero, the lock is retried.  If it
114432 ** returns 0, the operation aborts with an SQLITE_BUSY error.
114433 */
114434 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
114435   int rc;
114436   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
114437   rc = p->xFunc(p->pArg, p->nBusy);
114438   if( rc==0 ){
114439     p->nBusy = -1;
114440   }else{
114441     p->nBusy++;
114442   }
114443   return rc;
114444 }
114445 
114446 /*
114447 ** This routine sets the busy callback for an Sqlite database to the
114448 ** given callback function with the given argument.
114449 */
114450 SQLITE_API int sqlite3_busy_handler(
114451   sqlite3 *db,
114452   int (*xBusy)(void*,int),
114453   void *pArg
114454 ){
114455   sqlite3_mutex_enter(db->mutex);
114456   db->busyHandler.xFunc = xBusy;
114457   db->busyHandler.pArg = pArg;
114458   db->busyHandler.nBusy = 0;
114459   db->busyTimeout = 0;
114460   sqlite3_mutex_leave(db->mutex);
114461   return SQLITE_OK;
114462 }
114463 
114464 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
114465 /*
114466 ** This routine sets the progress callback for an Sqlite database to the
114467 ** given callback function with the given argument. The progress callback will
114468 ** be invoked every nOps opcodes.
114469 */
114470 SQLITE_API void sqlite3_progress_handler(
114471   sqlite3 *db,
114472   int nOps,
114473   int (*xProgress)(void*),
114474   void *pArg
114475 ){
114476   sqlite3_mutex_enter(db->mutex);
114477   if( nOps>0 ){
114478     db->xProgress = xProgress;
114479     db->nProgressOps = nOps;
114480     db->pProgressArg = pArg;
114481   }else{
114482     db->xProgress = 0;
114483     db->nProgressOps = 0;
114484     db->pProgressArg = 0;
114485   }
114486   sqlite3_mutex_leave(db->mutex);
114487 }
114488 #endif
114489 
114490 
114491 /*
114492 ** This routine installs a default busy handler that waits for the
114493 ** specified number of milliseconds before returning 0.
114494 */
114495 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
114496   if( ms>0 ){
114497     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
114498     db->busyTimeout = ms;
114499   }else{
114500     sqlite3_busy_handler(db, 0, 0);
114501   }
114502   return SQLITE_OK;
114503 }
114504 
114505 /*
114506 ** Cause any pending operation to stop at its earliest opportunity.
114507 */
114508 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
114509   db->u1.isInterrupted = 1;
114510 }
114511 
114512 
114513 /*
114514 ** This function is exactly the same as sqlite3_create_function(), except
114515 ** that it is designed to be called by internal code. The difference is
114516 ** that if a malloc() fails in sqlite3_create_function(), an error code
114517 ** is returned and the mallocFailed flag cleared.
114518 */
114519 SQLITE_PRIVATE int sqlite3CreateFunc(
114520   sqlite3 *db,
114521   const char *zFunctionName,
114522   int nArg,
114523   int enc,
114524   void *pUserData,
114525   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114526   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114527   void (*xFinal)(sqlite3_context*),
114528   FuncDestructor *pDestructor
114529 ){
114530   FuncDef *p;
114531   int nName;
114532 
114533   assert( sqlite3_mutex_held(db->mutex) );
114534   if( zFunctionName==0 ||
114535       (xFunc && (xFinal || xStep)) ||
114536       (!xFunc && (xFinal && !xStep)) ||
114537       (!xFunc && (!xFinal && xStep)) ||
114538       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
114539       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
114540     return SQLITE_MISUSE_BKPT;
114541   }
114542 
114543 #ifndef SQLITE_OMIT_UTF16
114544   /* If SQLITE_UTF16 is specified as the encoding type, transform this
114545   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
114546   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
114547   **
114548   ** If SQLITE_ANY is specified, add three versions of the function
114549   ** to the hash table.
114550   */
114551   if( enc==SQLITE_UTF16 ){
114552     enc = SQLITE_UTF16NATIVE;
114553   }else if( enc==SQLITE_ANY ){
114554     int rc;
114555     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
114556          pUserData, xFunc, xStep, xFinal, pDestructor);
114557     if( rc==SQLITE_OK ){
114558       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
114559           pUserData, xFunc, xStep, xFinal, pDestructor);
114560     }
114561     if( rc!=SQLITE_OK ){
114562       return rc;
114563     }
114564     enc = SQLITE_UTF16BE;
114565   }
114566 #else
114567   enc = SQLITE_UTF8;
114568 #endif
114569 
114570   /* Check if an existing function is being overridden or deleted. If so,
114571   ** and there are active VMs, then return SQLITE_BUSY. If a function
114572   ** is being overridden/deleted but there are no active VMs, allow the
114573   ** operation to continue but invalidate all precompiled statements.
114574   */
114575   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
114576   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
114577     if( db->activeVdbeCnt ){
114578       sqlite3Error(db, SQLITE_BUSY,
114579         "unable to delete/modify user-function due to active statements");
114580       assert( !db->mallocFailed );
114581       return SQLITE_BUSY;
114582     }else{
114583       sqlite3ExpirePreparedStatements(db);
114584     }
114585   }
114586 
114587   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
114588   assert(p || db->mallocFailed);
114589   if( !p ){
114590     return SQLITE_NOMEM;
114591   }
114592 
114593   /* If an older version of the function with a configured destructor is
114594   ** being replaced invoke the destructor function here. */
114595   functionDestroy(db, p);
114596 
114597   if( pDestructor ){
114598     pDestructor->nRef++;
114599   }
114600   p->pDestructor = pDestructor;
114601   p->flags = 0;
114602   p->xFunc = xFunc;
114603   p->xStep = xStep;
114604   p->xFinalize = xFinal;
114605   p->pUserData = pUserData;
114606   p->nArg = (u16)nArg;
114607   return SQLITE_OK;
114608 }
114609 
114610 /*
114611 ** Create new user functions.
114612 */
114613 SQLITE_API int sqlite3_create_function(
114614   sqlite3 *db,
114615   const char *zFunc,
114616   int nArg,
114617   int enc,
114618   void *p,
114619   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114620   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114621   void (*xFinal)(sqlite3_context*)
114622 ){
114623   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
114624                                     xFinal, 0);
114625 }
114626 
114627 SQLITE_API int sqlite3_create_function_v2(
114628   sqlite3 *db,
114629   const char *zFunc,
114630   int nArg,
114631   int enc,
114632   void *p,
114633   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
114634   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
114635   void (*xFinal)(sqlite3_context*),
114636   void (*xDestroy)(void *)
114637 ){
114638   int rc = SQLITE_ERROR;
114639   FuncDestructor *pArg = 0;
114640   sqlite3_mutex_enter(db->mutex);
114641   if( xDestroy ){
114642     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
114643     if( !pArg ){
114644       xDestroy(p);
114645       goto out;
114646     }
114647     pArg->xDestroy = xDestroy;
114648     pArg->pUserData = p;
114649   }
114650   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
114651   if( pArg && pArg->nRef==0 ){
114652     assert( rc!=SQLITE_OK );
114653     xDestroy(p);
114654     sqlite3DbFree(db, pArg);
114655   }
114656 
114657  out:
114658   rc = sqlite3ApiExit(db, rc);
114659   sqlite3_mutex_leave(db->mutex);
114660   return rc;
114661 }
114662 
114663 #ifndef SQLITE_OMIT_UTF16
114664 SQLITE_API int sqlite3_create_function16(
114665   sqlite3 *db,
114666   const void *zFunctionName,
114667   int nArg,
114668   int eTextRep,
114669   void *p,
114670   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
114671   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
114672   void (*xFinal)(sqlite3_context*)
114673 ){
114674   int rc;
114675   char *zFunc8;
114676   sqlite3_mutex_enter(db->mutex);
114677   assert( !db->mallocFailed );
114678   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
114679   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
114680   sqlite3DbFree(db, zFunc8);
114681   rc = sqlite3ApiExit(db, rc);
114682   sqlite3_mutex_leave(db->mutex);
114683   return rc;
114684 }
114685 #endif
114686 
114687 
114688 /*
114689 ** Declare that a function has been overloaded by a virtual table.
114690 **
114691 ** If the function already exists as a regular global function, then
114692 ** this routine is a no-op.  If the function does not exist, then create
114693 ** a new one that always throws a run-time error.
114694 **
114695 ** When virtual tables intend to provide an overloaded function, they
114696 ** should call this routine to make sure the global function exists.
114697 ** A global function must exist in order for name resolution to work
114698 ** properly.
114699 */
114700 SQLITE_API int sqlite3_overload_function(
114701   sqlite3 *db,
114702   const char *zName,
114703   int nArg
114704 ){
114705   int nName = sqlite3Strlen30(zName);
114706   int rc = SQLITE_OK;
114707   sqlite3_mutex_enter(db->mutex);
114708   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
114709     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
114710                            0, sqlite3InvalidFunction, 0, 0, 0);
114711   }
114712   rc = sqlite3ApiExit(db, rc);
114713   sqlite3_mutex_leave(db->mutex);
114714   return rc;
114715 }
114716 
114717 #ifndef SQLITE_OMIT_TRACE
114718 /*
114719 ** Register a trace function.  The pArg from the previously registered trace
114720 ** is returned.
114721 **
114722 ** A NULL trace function means that no tracing is executes.  A non-NULL
114723 ** trace is a pointer to a function that is invoked at the start of each
114724 ** SQL statement.
114725 */
114726 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
114727   void *pOld;
114728   sqlite3_mutex_enter(db->mutex);
114729   pOld = db->pTraceArg;
114730   db->xTrace = xTrace;
114731   db->pTraceArg = pArg;
114732   sqlite3_mutex_leave(db->mutex);
114733   return pOld;
114734 }
114735 /*
114736 ** Register a profile function.  The pArg from the previously registered
114737 ** profile function is returned.
114738 **
114739 ** A NULL profile function means that no profiling is executes.  A non-NULL
114740 ** profile is a pointer to a function that is invoked at the conclusion of
114741 ** each SQL statement that is run.
114742 */
114743 SQLITE_API void *sqlite3_profile(
114744   sqlite3 *db,
114745   void (*xProfile)(void*,const char*,sqlite_uint64),
114746   void *pArg
114747 ){
114748   void *pOld;
114749   sqlite3_mutex_enter(db->mutex);
114750   pOld = db->pProfileArg;
114751   db->xProfile = xProfile;
114752   db->pProfileArg = pArg;
114753   sqlite3_mutex_leave(db->mutex);
114754   return pOld;
114755 }
114756 #endif /* SQLITE_OMIT_TRACE */
114757 
114758 /*
114759 ** Register a function to be invoked when a transaction commits.
114760 ** If the invoked function returns non-zero, then the commit becomes a
114761 ** rollback.
114762 */
114763 SQLITE_API void *sqlite3_commit_hook(
114764   sqlite3 *db,              /* Attach the hook to this database */
114765   int (*xCallback)(void*),  /* Function to invoke on each commit */
114766   void *pArg                /* Argument to the function */
114767 ){
114768   void *pOld;
114769   sqlite3_mutex_enter(db->mutex);
114770   pOld = db->pCommitArg;
114771   db->xCommitCallback = xCallback;
114772   db->pCommitArg = pArg;
114773   sqlite3_mutex_leave(db->mutex);
114774   return pOld;
114775 }
114776 
114777 /*
114778 ** Register a callback to be invoked each time a row is updated,
114779 ** inserted or deleted using this database connection.
114780 */
114781 SQLITE_API void *sqlite3_update_hook(
114782   sqlite3 *db,              /* Attach the hook to this database */
114783   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
114784   void *pArg                /* Argument to the function */
114785 ){
114786   void *pRet;
114787   sqlite3_mutex_enter(db->mutex);
114788   pRet = db->pUpdateArg;
114789   db->xUpdateCallback = xCallback;
114790   db->pUpdateArg = pArg;
114791   sqlite3_mutex_leave(db->mutex);
114792   return pRet;
114793 }
114794 
114795 /*
114796 ** Register a callback to be invoked each time a transaction is rolled
114797 ** back by this database connection.
114798 */
114799 SQLITE_API void *sqlite3_rollback_hook(
114800   sqlite3 *db,              /* Attach the hook to this database */
114801   void (*xCallback)(void*), /* Callback function */
114802   void *pArg                /* Argument to the function */
114803 ){
114804   void *pRet;
114805   sqlite3_mutex_enter(db->mutex);
114806   pRet = db->pRollbackArg;
114807   db->xRollbackCallback = xCallback;
114808   db->pRollbackArg = pArg;
114809   sqlite3_mutex_leave(db->mutex);
114810   return pRet;
114811 }
114812 
114813 #ifndef SQLITE_OMIT_WAL
114814 /*
114815 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
114816 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
114817 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
114818 ** wal_autocheckpoint()).
114819 */
114820 SQLITE_PRIVATE int sqlite3WalDefaultHook(
114821   void *pClientData,     /* Argument */
114822   sqlite3 *db,           /* Connection */
114823   const char *zDb,       /* Database */
114824   int nFrame             /* Size of WAL */
114825 ){
114826   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
114827     sqlite3BeginBenignMalloc();
114828     sqlite3_wal_checkpoint(db, zDb);
114829     sqlite3EndBenignMalloc();
114830   }
114831   return SQLITE_OK;
114832 }
114833 #endif /* SQLITE_OMIT_WAL */
114834 
114835 /*
114836 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
114837 ** a database after committing a transaction if there are nFrame or
114838 ** more frames in the log file. Passing zero or a negative value as the
114839 ** nFrame parameter disables automatic checkpoints entirely.
114840 **
114841 ** The callback registered by this function replaces any existing callback
114842 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
114843 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
114844 ** configured by this function.
114845 */
114846 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
114847 #ifdef SQLITE_OMIT_WAL
114848   UNUSED_PARAMETER(db);
114849   UNUSED_PARAMETER(nFrame);
114850 #else
114851   if( nFrame>0 ){
114852     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
114853   }else{
114854     sqlite3_wal_hook(db, 0, 0);
114855   }
114856 #endif
114857   return SQLITE_OK;
114858 }
114859 
114860 /*
114861 ** Register a callback to be invoked each time a transaction is written
114862 ** into the write-ahead-log by this database connection.
114863 */
114864 SQLITE_API void *sqlite3_wal_hook(
114865   sqlite3 *db,                    /* Attach the hook to this db handle */
114866   int(*xCallback)(void *, sqlite3*, const char*, int),
114867   void *pArg                      /* First argument passed to xCallback() */
114868 ){
114869 #ifndef SQLITE_OMIT_WAL
114870   void *pRet;
114871   sqlite3_mutex_enter(db->mutex);
114872   pRet = db->pWalArg;
114873   db->xWalCallback = xCallback;
114874   db->pWalArg = pArg;
114875   sqlite3_mutex_leave(db->mutex);
114876   return pRet;
114877 #else
114878   return 0;
114879 #endif
114880 }
114881 
114882 /*
114883 ** Checkpoint database zDb.
114884 */
114885 SQLITE_API int sqlite3_wal_checkpoint_v2(
114886   sqlite3 *db,                    /* Database handle */
114887   const char *zDb,                /* Name of attached database (or NULL) */
114888   int eMode,                      /* SQLITE_CHECKPOINT_* value */
114889   int *pnLog,                     /* OUT: Size of WAL log in frames */
114890   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
114891 ){
114892 #ifdef SQLITE_OMIT_WAL
114893   return SQLITE_OK;
114894 #else
114895   int rc;                         /* Return code */
114896   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
114897 
114898   /* Initialize the output variables to -1 in case an error occurs. */
114899   if( pnLog ) *pnLog = -1;
114900   if( pnCkpt ) *pnCkpt = -1;
114901 
114902   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
114903   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
114904   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
114905   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
114906     return SQLITE_MISUSE;
114907   }
114908 
114909   sqlite3_mutex_enter(db->mutex);
114910   if( zDb && zDb[0] ){
114911     iDb = sqlite3FindDbName(db, zDb);
114912   }
114913   if( iDb<0 ){
114914     rc = SQLITE_ERROR;
114915     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
114916   }else{
114917     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
114918     sqlite3Error(db, rc, 0);
114919   }
114920   rc = sqlite3ApiExit(db, rc);
114921   sqlite3_mutex_leave(db->mutex);
114922   return rc;
114923 #endif
114924 }
114925 
114926 
114927 /*
114928 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
114929 ** to contains a zero-length string, all attached databases are
114930 ** checkpointed.
114931 */
114932 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
114933   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
114934 }
114935 
114936 #ifndef SQLITE_OMIT_WAL
114937 /*
114938 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
114939 ** not currently open in WAL mode.
114940 **
114941 ** If a transaction is open on the database being checkpointed, this
114942 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
114943 ** an error occurs while running the checkpoint, an SQLite error code is
114944 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
114945 **
114946 ** The mutex on database handle db should be held by the caller. The mutex
114947 ** associated with the specific b-tree being checkpointed is taken by
114948 ** this function while the checkpoint is running.
114949 **
114950 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
114951 ** checkpointed. If an error is encountered it is returned immediately -
114952 ** no attempt is made to checkpoint any remaining databases.
114953 **
114954 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
114955 */
114956 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
114957   int rc = SQLITE_OK;             /* Return code */
114958   int i;                          /* Used to iterate through attached dbs */
114959   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
114960 
114961   assert( sqlite3_mutex_held(db->mutex) );
114962   assert( !pnLog || *pnLog==-1 );
114963   assert( !pnCkpt || *pnCkpt==-1 );
114964 
114965   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
114966     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
114967       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
114968       pnLog = 0;
114969       pnCkpt = 0;
114970       if( rc==SQLITE_BUSY ){
114971         bBusy = 1;
114972         rc = SQLITE_OK;
114973       }
114974     }
114975   }
114976 
114977   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
114978 }
114979 #endif /* SQLITE_OMIT_WAL */
114980 
114981 /*
114982 ** This function returns true if main-memory should be used instead of
114983 ** a temporary file for transient pager files and statement journals.
114984 ** The value returned depends on the value of db->temp_store (runtime
114985 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
114986 ** following table describes the relationship between these two values
114987 ** and this functions return value.
114988 **
114989 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
114990 **   -----------------     --------------     ------------------------------
114991 **   0                     any                file      (return 0)
114992 **   1                     1                  file      (return 0)
114993 **   1                     2                  memory    (return 1)
114994 **   1                     0                  file      (return 0)
114995 **   2                     1                  file      (return 0)
114996 **   2                     2                  memory    (return 1)
114997 **   2                     0                  memory    (return 1)
114998 **   3                     any                memory    (return 1)
114999 */
115000 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
115001 #if SQLITE_TEMP_STORE==1
115002   return ( db->temp_store==2 );
115003 #endif
115004 #if SQLITE_TEMP_STORE==2
115005   return ( db->temp_store!=1 );
115006 #endif
115007 #if SQLITE_TEMP_STORE==3
115008   return 1;
115009 #endif
115010 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
115011   return 0;
115012 #endif
115013 }
115014 
115015 /*
115016 ** Return UTF-8 encoded English language explanation of the most recent
115017 ** error.
115018 */
115019 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
115020   const char *z;
115021   if( !db ){
115022     return sqlite3ErrStr(SQLITE_NOMEM);
115023   }
115024   if( !sqlite3SafetyCheckSickOrOk(db) ){
115025     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
115026   }
115027   sqlite3_mutex_enter(db->mutex);
115028   if( db->mallocFailed ){
115029     z = sqlite3ErrStr(SQLITE_NOMEM);
115030   }else{
115031     z = (char*)sqlite3_value_text(db->pErr);
115032     assert( !db->mallocFailed );
115033     if( z==0 ){
115034       z = sqlite3ErrStr(db->errCode);
115035     }
115036   }
115037   sqlite3_mutex_leave(db->mutex);
115038   return z;
115039 }
115040 
115041 #ifndef SQLITE_OMIT_UTF16
115042 /*
115043 ** Return UTF-16 encoded English language explanation of the most recent
115044 ** error.
115045 */
115046 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
115047   static const u16 outOfMem[] = {
115048     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
115049   };
115050   static const u16 misuse[] = {
115051     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
115052     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
115053     'c', 'a', 'l', 'l', 'e', 'd', ' ',
115054     'o', 'u', 't', ' ',
115055     'o', 'f', ' ',
115056     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
115057   };
115058 
115059   const void *z;
115060   if( !db ){
115061     return (void *)outOfMem;
115062   }
115063   if( !sqlite3SafetyCheckSickOrOk(db) ){
115064     return (void *)misuse;
115065   }
115066   sqlite3_mutex_enter(db->mutex);
115067   if( db->mallocFailed ){
115068     z = (void *)outOfMem;
115069   }else{
115070     z = sqlite3_value_text16(db->pErr);
115071     if( z==0 ){
115072       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
115073            SQLITE_UTF8, SQLITE_STATIC);
115074       z = sqlite3_value_text16(db->pErr);
115075     }
115076     /* A malloc() may have failed within the call to sqlite3_value_text16()
115077     ** above. If this is the case, then the db->mallocFailed flag needs to
115078     ** be cleared before returning. Do this directly, instead of via
115079     ** sqlite3ApiExit(), to avoid setting the database handle error message.
115080     */
115081     db->mallocFailed = 0;
115082   }
115083   sqlite3_mutex_leave(db->mutex);
115084   return z;
115085 }
115086 #endif /* SQLITE_OMIT_UTF16 */
115087 
115088 /*
115089 ** Return the most recent error code generated by an SQLite routine. If NULL is
115090 ** passed to this function, we assume a malloc() failed during sqlite3_open().
115091 */
115092 SQLITE_API int sqlite3_errcode(sqlite3 *db){
115093   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
115094     return SQLITE_MISUSE_BKPT;
115095   }
115096   if( !db || db->mallocFailed ){
115097     return SQLITE_NOMEM;
115098   }
115099   return db->errCode & db->errMask;
115100 }
115101 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
115102   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
115103     return SQLITE_MISUSE_BKPT;
115104   }
115105   if( !db || db->mallocFailed ){
115106     return SQLITE_NOMEM;
115107   }
115108   return db->errCode;
115109 }
115110 
115111 /*
115112 ** Return a string that describes the kind of error specified in the
115113 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
115114 ** function.
115115 */
115116 SQLITE_API const char *sqlite3_errstr(int rc){
115117   return sqlite3ErrStr(rc);
115118 }
115119 
115120 /*
115121 ** Create a new collating function for database "db".  The name is zName
115122 ** and the encoding is enc.
115123 */
115124 static int createCollation(
115125   sqlite3* db,
115126   const char *zName,
115127   u8 enc,
115128   void* pCtx,
115129   int(*xCompare)(void*,int,const void*,int,const void*),
115130   void(*xDel)(void*)
115131 ){
115132   CollSeq *pColl;
115133   int enc2;
115134   int nName = sqlite3Strlen30(zName);
115135 
115136   assert( sqlite3_mutex_held(db->mutex) );
115137 
115138   /* If SQLITE_UTF16 is specified as the encoding type, transform this
115139   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
115140   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
115141   */
115142   enc2 = enc;
115143   testcase( enc2==SQLITE_UTF16 );
115144   testcase( enc2==SQLITE_UTF16_ALIGNED );
115145   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
115146     enc2 = SQLITE_UTF16NATIVE;
115147   }
115148   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
115149     return SQLITE_MISUSE_BKPT;
115150   }
115151 
115152   /* Check if this call is removing or replacing an existing collation
115153   ** sequence. If so, and there are active VMs, return busy. If there
115154   ** are no active VMs, invalidate any pre-compiled statements.
115155   */
115156   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
115157   if( pColl && pColl->xCmp ){
115158     if( db->activeVdbeCnt ){
115159       sqlite3Error(db, SQLITE_BUSY,
115160         "unable to delete/modify collation sequence due to active statements");
115161       return SQLITE_BUSY;
115162     }
115163     sqlite3ExpirePreparedStatements(db);
115164 
115165     /* If collation sequence pColl was created directly by a call to
115166     ** sqlite3_create_collation, and not generated by synthCollSeq(),
115167     ** then any copies made by synthCollSeq() need to be invalidated.
115168     ** Also, collation destructor - CollSeq.xDel() - function may need
115169     ** to be called.
115170     */
115171     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
115172       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
115173       int j;
115174       for(j=0; j<3; j++){
115175         CollSeq *p = &aColl[j];
115176         if( p->enc==pColl->enc ){
115177           if( p->xDel ){
115178             p->xDel(p->pUser);
115179           }
115180           p->xCmp = 0;
115181         }
115182       }
115183     }
115184   }
115185 
115186   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
115187   if( pColl==0 ) return SQLITE_NOMEM;
115188   pColl->xCmp = xCompare;
115189   pColl->pUser = pCtx;
115190   pColl->xDel = xDel;
115191   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
115192   sqlite3Error(db, SQLITE_OK, 0);
115193   return SQLITE_OK;
115194 }
115195 
115196 
115197 /*
115198 ** This array defines hard upper bounds on limit values.  The
115199 ** initializer must be kept in sync with the SQLITE_LIMIT_*
115200 ** #defines in sqlite3.h.
115201 */
115202 static const int aHardLimit[] = {
115203   SQLITE_MAX_LENGTH,
115204   SQLITE_MAX_SQL_LENGTH,
115205   SQLITE_MAX_COLUMN,
115206   SQLITE_MAX_EXPR_DEPTH,
115207   SQLITE_MAX_COMPOUND_SELECT,
115208   SQLITE_MAX_VDBE_OP,
115209   SQLITE_MAX_FUNCTION_ARG,
115210   SQLITE_MAX_ATTACHED,
115211   SQLITE_MAX_LIKE_PATTERN_LENGTH,
115212   SQLITE_MAX_VARIABLE_NUMBER,
115213   SQLITE_MAX_TRIGGER_DEPTH,
115214 };
115215 
115216 /*
115217 ** Make sure the hard limits are set to reasonable values
115218 */
115219 #if SQLITE_MAX_LENGTH<100
115220 # error SQLITE_MAX_LENGTH must be at least 100
115221 #endif
115222 #if SQLITE_MAX_SQL_LENGTH<100
115223 # error SQLITE_MAX_SQL_LENGTH must be at least 100
115224 #endif
115225 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
115226 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
115227 #endif
115228 #if SQLITE_MAX_COMPOUND_SELECT<2
115229 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
115230 #endif
115231 #if SQLITE_MAX_VDBE_OP<40
115232 # error SQLITE_MAX_VDBE_OP must be at least 40
115233 #endif
115234 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
115235 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
115236 #endif
115237 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
115238 # error SQLITE_MAX_ATTACHED must be between 0 and 62
115239 #endif
115240 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
115241 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
115242 #endif
115243 #if SQLITE_MAX_COLUMN>32767
115244 # error SQLITE_MAX_COLUMN must not exceed 32767
115245 #endif
115246 #if SQLITE_MAX_TRIGGER_DEPTH<1
115247 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
115248 #endif
115249 
115250 
115251 /*
115252 ** Change the value of a limit.  Report the old value.
115253 ** If an invalid limit index is supplied, report -1.
115254 ** Make no changes but still report the old value if the
115255 ** new limit is negative.
115256 **
115257 ** A new lower limit does not shrink existing constructs.
115258 ** It merely prevents new constructs that exceed the limit
115259 ** from forming.
115260 */
115261 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
115262   int oldLimit;
115263 
115264 
115265   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
115266   ** there is a hard upper bound set at compile-time by a C preprocessor
115267   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
115268   ** "_MAX_".)
115269   */
115270   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
115271   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
115272   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
115273   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
115274   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
115275   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
115276   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
115277   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
115278   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
115279                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
115280   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
115281   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
115282   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
115283 
115284 
115285   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
115286     return -1;
115287   }
115288   oldLimit = db->aLimit[limitId];
115289   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
115290     if( newLimit>aHardLimit[limitId] ){
115291       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
115292     }
115293     db->aLimit[limitId] = newLimit;
115294   }
115295   return oldLimit;                     /* IMP: R-53341-35419 */
115296 }
115297 
115298 /*
115299 ** This function is used to parse both URIs and non-URI filenames passed by the
115300 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
115301 ** URIs specified as part of ATTACH statements.
115302 **
115303 ** The first argument to this function is the name of the VFS to use (or
115304 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
115305 ** query parameter. The second argument contains the URI (or non-URI filename)
115306 ** itself. When this function is called the *pFlags variable should contain
115307 ** the default flags to open the database handle with. The value stored in
115308 ** *pFlags may be updated before returning if the URI filename contains
115309 ** "cache=xxx" or "mode=xxx" query parameters.
115310 **
115311 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
115312 ** the VFS that should be used to open the database file. *pzFile is set to
115313 ** point to a buffer containing the name of the file to open. It is the
115314 ** responsibility of the caller to eventually call sqlite3_free() to release
115315 ** this buffer.
115316 **
115317 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
115318 ** may be set to point to a buffer containing an English language error
115319 ** message. It is the responsibility of the caller to eventually release
115320 ** this buffer by calling sqlite3_free().
115321 */
115322 SQLITE_PRIVATE int sqlite3ParseUri(
115323   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
115324   const char *zUri,               /* Nul-terminated URI to parse */
115325   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
115326   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
115327   char **pzFile,                  /* OUT: Filename component of URI */
115328   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
115329 ){
115330   int rc = SQLITE_OK;
115331   unsigned int flags = *pFlags;
115332   const char *zVfs = zDefaultVfs;
115333   char *zFile;
115334   char c;
115335   int nUri = sqlite3Strlen30(zUri);
115336 
115337   assert( *pzErrMsg==0 );
115338 
115339   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
115340    && nUri>=5 && memcmp(zUri, "file:", 5)==0
115341   ){
115342     char *zOpt;
115343     int eState;                   /* Parser state when parsing URI */
115344     int iIn;                      /* Input character index */
115345     int iOut = 0;                 /* Output character index */
115346     int nByte = nUri+2;           /* Bytes of space to allocate */
115347 
115348     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
115349     ** method that there may be extra parameters following the file-name.  */
115350     flags |= SQLITE_OPEN_URI;
115351 
115352     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
115353     zFile = sqlite3_malloc(nByte);
115354     if( !zFile ) return SQLITE_NOMEM;
115355 
115356     /* Discard the scheme and authority segments of the URI. */
115357     if( zUri[5]=='/' && zUri[6]=='/' ){
115358       iIn = 7;
115359       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
115360 
115361       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
115362         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
115363             iIn-7, &zUri[7]);
115364         rc = SQLITE_ERROR;
115365         goto parse_uri_out;
115366       }
115367     }else{
115368       iIn = 5;
115369     }
115370 
115371     /* Copy the filename and any query parameters into the zFile buffer.
115372     ** Decode %HH escape codes along the way.
115373     **
115374     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
115375     ** on the parsing context. As follows:
115376     **
115377     **   0: Parsing file-name.
115378     **   1: Parsing name section of a name=value query parameter.
115379     **   2: Parsing value section of a name=value query parameter.
115380     */
115381     eState = 0;
115382     while( (c = zUri[iIn])!=0 && c!='#' ){
115383       iIn++;
115384       if( c=='%'
115385        && sqlite3Isxdigit(zUri[iIn])
115386        && sqlite3Isxdigit(zUri[iIn+1])
115387       ){
115388         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
115389         octet += sqlite3HexToInt(zUri[iIn++]);
115390 
115391         assert( octet>=0 && octet<256 );
115392         if( octet==0 ){
115393           /* This branch is taken when "%00" appears within the URI. In this
115394           ** case we ignore all text in the remainder of the path, name or
115395           ** value currently being parsed. So ignore the current character
115396           ** and skip to the next "?", "=" or "&", as appropriate. */
115397           while( (c = zUri[iIn])!=0 && c!='#'
115398               && (eState!=0 || c!='?')
115399               && (eState!=1 || (c!='=' && c!='&'))
115400               && (eState!=2 || c!='&')
115401           ){
115402             iIn++;
115403           }
115404           continue;
115405         }
115406         c = octet;
115407       }else if( eState==1 && (c=='&' || c=='=') ){
115408         if( zFile[iOut-1]==0 ){
115409           /* An empty option name. Ignore this option altogether. */
115410           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
115411           continue;
115412         }
115413         if( c=='&' ){
115414           zFile[iOut++] = '\0';
115415         }else{
115416           eState = 2;
115417         }
115418         c = 0;
115419       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
115420         c = 0;
115421         eState = 1;
115422       }
115423       zFile[iOut++] = c;
115424     }
115425     if( eState==1 ) zFile[iOut++] = '\0';
115426     zFile[iOut++] = '\0';
115427     zFile[iOut++] = '\0';
115428 
115429     /* Check if there were any options specified that should be interpreted
115430     ** here. Options that are interpreted here include "vfs" and those that
115431     ** correspond to flags that may be passed to the sqlite3_open_v2()
115432     ** method. */
115433     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
115434     while( zOpt[0] ){
115435       int nOpt = sqlite3Strlen30(zOpt);
115436       char *zVal = &zOpt[nOpt+1];
115437       int nVal = sqlite3Strlen30(zVal);
115438 
115439       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
115440         zVfs = zVal;
115441       }else{
115442         struct OpenMode {
115443           const char *z;
115444           int mode;
115445         } *aMode = 0;
115446         char *zModeType = 0;
115447         int mask = 0;
115448         int limit = 0;
115449 
115450         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
115451           static struct OpenMode aCacheMode[] = {
115452             { "shared",  SQLITE_OPEN_SHAREDCACHE },
115453             { "private", SQLITE_OPEN_PRIVATECACHE },
115454             { 0, 0 }
115455           };
115456 
115457           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
115458           aMode = aCacheMode;
115459           limit = mask;
115460           zModeType = "cache";
115461         }
115462         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
115463           static struct OpenMode aOpenMode[] = {
115464             { "ro",  SQLITE_OPEN_READONLY },
115465             { "rw",  SQLITE_OPEN_READWRITE },
115466             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
115467             { "memory", SQLITE_OPEN_MEMORY },
115468             { 0, 0 }
115469           };
115470 
115471           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
115472                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
115473           aMode = aOpenMode;
115474           limit = mask & flags;
115475           zModeType = "access";
115476         }
115477 
115478         if( aMode ){
115479           int i;
115480           int mode = 0;
115481           for(i=0; aMode[i].z; i++){
115482             const char *z = aMode[i].z;
115483             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
115484               mode = aMode[i].mode;
115485               break;
115486             }
115487           }
115488           if( mode==0 ){
115489             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
115490             rc = SQLITE_ERROR;
115491             goto parse_uri_out;
115492           }
115493           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
115494             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
115495                                         zModeType, zVal);
115496             rc = SQLITE_PERM;
115497             goto parse_uri_out;
115498           }
115499           flags = (flags & ~mask) | mode;
115500         }
115501       }
115502 
115503       zOpt = &zVal[nVal+1];
115504     }
115505 
115506   }else{
115507     zFile = sqlite3_malloc(nUri+2);
115508     if( !zFile ) return SQLITE_NOMEM;
115509     memcpy(zFile, zUri, nUri);
115510     zFile[nUri] = '\0';
115511     zFile[nUri+1] = '\0';
115512     flags &= ~SQLITE_OPEN_URI;
115513   }
115514 
115515   *ppVfs = sqlite3_vfs_find(zVfs);
115516   if( *ppVfs==0 ){
115517     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
115518     rc = SQLITE_ERROR;
115519   }
115520  parse_uri_out:
115521   if( rc!=SQLITE_OK ){
115522     sqlite3_free(zFile);
115523     zFile = 0;
115524   }
115525   *pFlags = flags;
115526   *pzFile = zFile;
115527   return rc;
115528 }
115529 
115530 
115531 /*
115532 ** This routine does the work of opening a database on behalf of
115533 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
115534 ** is UTF-8 encoded.
115535 */
115536 static int openDatabase(
115537   const char *zFilename, /* Database filename UTF-8 encoded */
115538   sqlite3 **ppDb,        /* OUT: Returned database handle */
115539   unsigned int flags,    /* Operational flags */
115540   const char *zVfs       /* Name of the VFS to use */
115541 ){
115542   sqlite3 *db;                    /* Store allocated handle here */
115543   int rc;                         /* Return code */
115544   int isThreadsafe;               /* True for threadsafe connections */
115545   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
115546   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
115547 
115548   *ppDb = 0;
115549 #ifndef SQLITE_OMIT_AUTOINIT
115550   rc = sqlite3_initialize();
115551   if( rc ) return rc;
115552 #endif
115553 
115554   /* Only allow sensible combinations of bits in the flags argument.
115555   ** Throw an error if any non-sense combination is used.  If we
115556   ** do not block illegal combinations here, it could trigger
115557   ** assert() statements in deeper layers.  Sensible combinations
115558   ** are:
115559   **
115560   **  1:  SQLITE_OPEN_READONLY
115561   **  2:  SQLITE_OPEN_READWRITE
115562   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
115563   */
115564   assert( SQLITE_OPEN_READONLY  == 0x01 );
115565   assert( SQLITE_OPEN_READWRITE == 0x02 );
115566   assert( SQLITE_OPEN_CREATE    == 0x04 );
115567   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
115568   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
115569   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
115570   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
115571 
115572   if( sqlite3GlobalConfig.bCoreMutex==0 ){
115573     isThreadsafe = 0;
115574   }else if( flags & SQLITE_OPEN_NOMUTEX ){
115575     isThreadsafe = 0;
115576   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
115577     isThreadsafe = 1;
115578   }else{
115579     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
115580   }
115581   if( flags & SQLITE_OPEN_PRIVATECACHE ){
115582     flags &= ~SQLITE_OPEN_SHAREDCACHE;
115583   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
115584     flags |= SQLITE_OPEN_SHAREDCACHE;
115585   }
115586 
115587   /* Remove harmful bits from the flags parameter
115588   **
115589   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
115590   ** dealt with in the previous code block.  Besides these, the only
115591   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
115592   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
115593   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
115594   ** off all other flags.
115595   */
115596   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
115597                SQLITE_OPEN_EXCLUSIVE |
115598                SQLITE_OPEN_MAIN_DB |
115599                SQLITE_OPEN_TEMP_DB |
115600                SQLITE_OPEN_TRANSIENT_DB |
115601                SQLITE_OPEN_MAIN_JOURNAL |
115602                SQLITE_OPEN_TEMP_JOURNAL |
115603                SQLITE_OPEN_SUBJOURNAL |
115604                SQLITE_OPEN_MASTER_JOURNAL |
115605                SQLITE_OPEN_NOMUTEX |
115606                SQLITE_OPEN_FULLMUTEX |
115607                SQLITE_OPEN_WAL
115608              );
115609 
115610   /* Allocate the sqlite data structure */
115611   db = sqlite3MallocZero( sizeof(sqlite3) );
115612   if( db==0 ) goto opendb_out;
115613   if( isThreadsafe ){
115614     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
115615     if( db->mutex==0 ){
115616       sqlite3_free(db);
115617       db = 0;
115618       goto opendb_out;
115619     }
115620   }
115621   sqlite3_mutex_enter(db->mutex);
115622   db->errMask = 0xff;
115623   db->nDb = 2;
115624   db->magic = SQLITE_MAGIC_BUSY;
115625   db->aDb = db->aDbStatic;
115626 
115627   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
115628   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
115629   db->autoCommit = 1;
115630   db->nextAutovac = -1;
115631   db->nextPagesize = 0;
115632   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
115633 #if SQLITE_DEFAULT_FILE_FORMAT<4
115634                  | SQLITE_LegacyFileFmt
115635 #endif
115636 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
115637                  | SQLITE_LoadExtension
115638 #endif
115639 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
115640                  | SQLITE_RecTriggers
115641 #endif
115642 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
115643                  | SQLITE_ForeignKeys
115644 #endif
115645       ;
115646   sqlite3HashInit(&db->aCollSeq);
115647 #ifndef SQLITE_OMIT_VIRTUALTABLE
115648   sqlite3HashInit(&db->aModule);
115649 #endif
115650 
115651   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
115652   ** and UTF-16, so add a version for each to avoid any unnecessary
115653   ** conversions. The only error that can occur here is a malloc() failure.
115654   */
115655   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
115656   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
115657   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
115658   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
115659   if( db->mallocFailed ){
115660     goto opendb_out;
115661   }
115662   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
115663   assert( db->pDfltColl!=0 );
115664 
115665   /* Also add a UTF-8 case-insensitive collation sequence. */
115666   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
115667 
115668   /* Parse the filename/URI argument. */
115669   db->openFlags = flags;
115670   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
115671   if( rc!=SQLITE_OK ){
115672     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
115673     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
115674     sqlite3_free(zErrMsg);
115675     goto opendb_out;
115676   }
115677 
115678   /* Open the backend database driver */
115679   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
115680                         flags | SQLITE_OPEN_MAIN_DB);
115681   if( rc!=SQLITE_OK ){
115682     if( rc==SQLITE_IOERR_NOMEM ){
115683       rc = SQLITE_NOMEM;
115684     }
115685     sqlite3Error(db, rc, 0);
115686     goto opendb_out;
115687   }
115688   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
115689   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
115690 
115691 
115692   /* The default safety_level for the main database is 'full'; for the temp
115693   ** database it is 'NONE'. This matches the pager layer defaults.
115694   */
115695   db->aDb[0].zName = "main";
115696   db->aDb[0].safety_level = 3;
115697   db->aDb[1].zName = "temp";
115698   db->aDb[1].safety_level = 1;
115699 
115700   db->magic = SQLITE_MAGIC_OPEN;
115701   if( db->mallocFailed ){
115702     goto opendb_out;
115703   }
115704 
115705   /* Register all built-in functions, but do not attempt to read the
115706   ** database schema yet. This is delayed until the first time the database
115707   ** is accessed.
115708   */
115709   sqlite3Error(db, SQLITE_OK, 0);
115710   sqlite3RegisterBuiltinFunctions(db);
115711 
115712   /* Load automatic extensions - extensions that have been registered
115713   ** using the sqlite3_automatic_extension() API.
115714   */
115715   rc = sqlite3_errcode(db);
115716   if( rc==SQLITE_OK ){
115717     sqlite3AutoLoadExtensions(db);
115718     rc = sqlite3_errcode(db);
115719     if( rc!=SQLITE_OK ){
115720       goto opendb_out;
115721     }
115722   }
115723 
115724 #ifdef SQLITE_ENABLE_FTS1
115725   if( !db->mallocFailed ){
115726     extern int sqlite3Fts1Init(sqlite3*);
115727     rc = sqlite3Fts1Init(db);
115728   }
115729 #endif
115730 
115731 #ifdef SQLITE_ENABLE_FTS2
115732   if( !db->mallocFailed && rc==SQLITE_OK ){
115733     extern int sqlite3Fts2Init(sqlite3*);
115734     rc = sqlite3Fts2Init(db);
115735   }
115736 #endif
115737 
115738 #ifdef SQLITE_ENABLE_FTS3
115739   if( !db->mallocFailed && rc==SQLITE_OK ){
115740     rc = sqlite3Fts3Init(db);
115741   }
115742 #endif
115743 
115744 #ifdef SQLITE_ENABLE_ICU
115745   if( !db->mallocFailed && rc==SQLITE_OK ){
115746     rc = sqlite3IcuInit(db);
115747   }
115748 #endif
115749 
115750 #ifdef SQLITE_ENABLE_RTREE
115751   if( !db->mallocFailed && rc==SQLITE_OK){
115752     rc = sqlite3RtreeInit(db);
115753   }
115754 #endif
115755 
115756   sqlite3Error(db, rc, 0);
115757 
115758   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
115759   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
115760   ** mode.  Doing nothing at all also makes NORMAL the default.
115761   */
115762 #ifdef SQLITE_DEFAULT_LOCKING_MODE
115763   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
115764   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
115765                           SQLITE_DEFAULT_LOCKING_MODE);
115766 #endif
115767 
115768   /* Enable the lookaside-malloc subsystem */
115769   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
115770                         sqlite3GlobalConfig.nLookaside);
115771 
115772   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
115773 
115774 opendb_out:
115775   sqlite3_free(zOpen);
115776   if( db ){
115777     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
115778     sqlite3_mutex_leave(db->mutex);
115779   }
115780   rc = sqlite3_errcode(db);
115781   assert( db!=0 || rc==SQLITE_NOMEM );
115782   if( rc==SQLITE_NOMEM ){
115783     sqlite3_close(db);
115784     db = 0;
115785   }else if( rc!=SQLITE_OK ){
115786     db->magic = SQLITE_MAGIC_SICK;
115787   }
115788   *ppDb = db;
115789 #ifdef SQLITE_ENABLE_SQLLOG
115790   if( sqlite3GlobalConfig.xSqllog ){
115791     /* Opening a db handle. Fourth parameter is passed 0. */
115792     void *pArg = sqlite3GlobalConfig.pSqllogArg;
115793     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
115794   }
115795 #endif
115796   return sqlite3ApiExit(0, rc);
115797 }
115798 
115799 /*
115800 ** Open a new database handle.
115801 */
115802 SQLITE_API int sqlite3_open(
115803   const char *zFilename,
115804   sqlite3 **ppDb
115805 ){
115806   return openDatabase(zFilename, ppDb,
115807                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115808 }
115809 SQLITE_API int sqlite3_open_v2(
115810   const char *filename,   /* Database filename (UTF-8) */
115811   sqlite3 **ppDb,         /* OUT: SQLite db handle */
115812   int flags,              /* Flags */
115813   const char *zVfs        /* Name of VFS module to use */
115814 ){
115815   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
115816 }
115817 
115818 #ifndef SQLITE_OMIT_UTF16
115819 /*
115820 ** Open a new database handle.
115821 */
115822 SQLITE_API int sqlite3_open16(
115823   const void *zFilename,
115824   sqlite3 **ppDb
115825 ){
115826   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
115827   sqlite3_value *pVal;
115828   int rc;
115829 
115830   assert( zFilename );
115831   assert( ppDb );
115832   *ppDb = 0;
115833 #ifndef SQLITE_OMIT_AUTOINIT
115834   rc = sqlite3_initialize();
115835   if( rc ) return rc;
115836 #endif
115837   pVal = sqlite3ValueNew(0);
115838   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
115839   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
115840   if( zFilename8 ){
115841     rc = openDatabase(zFilename8, ppDb,
115842                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
115843     assert( *ppDb || rc==SQLITE_NOMEM );
115844     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
115845       ENC(*ppDb) = SQLITE_UTF16NATIVE;
115846     }
115847   }else{
115848     rc = SQLITE_NOMEM;
115849   }
115850   sqlite3ValueFree(pVal);
115851 
115852   return sqlite3ApiExit(0, rc);
115853 }
115854 #endif /* SQLITE_OMIT_UTF16 */
115855 
115856 /*
115857 ** Register a new collation sequence with the database handle db.
115858 */
115859 SQLITE_API int sqlite3_create_collation(
115860   sqlite3* db,
115861   const char *zName,
115862   int enc,
115863   void* pCtx,
115864   int(*xCompare)(void*,int,const void*,int,const void*)
115865 ){
115866   int rc;
115867   sqlite3_mutex_enter(db->mutex);
115868   assert( !db->mallocFailed );
115869   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
115870   rc = sqlite3ApiExit(db, rc);
115871   sqlite3_mutex_leave(db->mutex);
115872   return rc;
115873 }
115874 
115875 /*
115876 ** Register a new collation sequence with the database handle db.
115877 */
115878 SQLITE_API int sqlite3_create_collation_v2(
115879   sqlite3* db,
115880   const char *zName,
115881   int enc,
115882   void* pCtx,
115883   int(*xCompare)(void*,int,const void*,int,const void*),
115884   void(*xDel)(void*)
115885 ){
115886   int rc;
115887   sqlite3_mutex_enter(db->mutex);
115888   assert( !db->mallocFailed );
115889   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
115890   rc = sqlite3ApiExit(db, rc);
115891   sqlite3_mutex_leave(db->mutex);
115892   return rc;
115893 }
115894 
115895 #ifndef SQLITE_OMIT_UTF16
115896 /*
115897 ** Register a new collation sequence with the database handle db.
115898 */
115899 SQLITE_API int sqlite3_create_collation16(
115900   sqlite3* db,
115901   const void *zName,
115902   int enc,
115903   void* pCtx,
115904   int(*xCompare)(void*,int,const void*,int,const void*)
115905 ){
115906   int rc = SQLITE_OK;
115907   char *zName8;
115908   sqlite3_mutex_enter(db->mutex);
115909   assert( !db->mallocFailed );
115910   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
115911   if( zName8 ){
115912     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
115913     sqlite3DbFree(db, zName8);
115914   }
115915   rc = sqlite3ApiExit(db, rc);
115916   sqlite3_mutex_leave(db->mutex);
115917   return rc;
115918 }
115919 #endif /* SQLITE_OMIT_UTF16 */
115920 
115921 /*
115922 ** Register a collation sequence factory callback with the database handle
115923 ** db. Replace any previously installed collation sequence factory.
115924 */
115925 SQLITE_API int sqlite3_collation_needed(
115926   sqlite3 *db,
115927   void *pCollNeededArg,
115928   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
115929 ){
115930   sqlite3_mutex_enter(db->mutex);
115931   db->xCollNeeded = xCollNeeded;
115932   db->xCollNeeded16 = 0;
115933   db->pCollNeededArg = pCollNeededArg;
115934   sqlite3_mutex_leave(db->mutex);
115935   return SQLITE_OK;
115936 }
115937 
115938 #ifndef SQLITE_OMIT_UTF16
115939 /*
115940 ** Register a collation sequence factory callback with the database handle
115941 ** db. Replace any previously installed collation sequence factory.
115942 */
115943 SQLITE_API int sqlite3_collation_needed16(
115944   sqlite3 *db,
115945   void *pCollNeededArg,
115946   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
115947 ){
115948   sqlite3_mutex_enter(db->mutex);
115949   db->xCollNeeded = 0;
115950   db->xCollNeeded16 = xCollNeeded16;
115951   db->pCollNeededArg = pCollNeededArg;
115952   sqlite3_mutex_leave(db->mutex);
115953   return SQLITE_OK;
115954 }
115955 #endif /* SQLITE_OMIT_UTF16 */
115956 
115957 #ifndef SQLITE_OMIT_DEPRECATED
115958 /*
115959 ** This function is now an anachronism. It used to be used to recover from a
115960 ** malloc() failure, but SQLite now does this automatically.
115961 */
115962 SQLITE_API int sqlite3_global_recover(void){
115963   return SQLITE_OK;
115964 }
115965 #endif
115966 
115967 /*
115968 ** Test to see whether or not the database connection is in autocommit
115969 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
115970 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
115971 ** by the next COMMIT or ROLLBACK.
115972 **
115973 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
115974 */
115975 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
115976   return db->autoCommit;
115977 }
115978 
115979 /*
115980 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
115981 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
115982 ** constants.  They server two purposes:
115983 **
115984 **   1.  Serve as a convenient place to set a breakpoint in a debugger
115985 **       to detect when version error conditions occurs.
115986 **
115987 **   2.  Invoke sqlite3_log() to provide the source code location where
115988 **       a low-level error is first detected.
115989 */
115990 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
115991   testcase( sqlite3GlobalConfig.xLog!=0 );
115992   sqlite3_log(SQLITE_CORRUPT,
115993               "database corruption at line %d of [%.10s]",
115994               lineno, 20+sqlite3_sourceid());
115995   return SQLITE_CORRUPT;
115996 }
115997 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
115998   testcase( sqlite3GlobalConfig.xLog!=0 );
115999   sqlite3_log(SQLITE_MISUSE,
116000               "misuse at line %d of [%.10s]",
116001               lineno, 20+sqlite3_sourceid());
116002   return SQLITE_MISUSE;
116003 }
116004 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
116005   testcase( sqlite3GlobalConfig.xLog!=0 );
116006   sqlite3_log(SQLITE_CANTOPEN,
116007               "cannot open file at line %d of [%.10s]",
116008               lineno, 20+sqlite3_sourceid());
116009   return SQLITE_CANTOPEN;
116010 }
116011 
116012 
116013 #ifndef SQLITE_OMIT_DEPRECATED
116014 /*
116015 ** This is a convenience routine that makes sure that all thread-specific
116016 ** data for this thread has been deallocated.
116017 **
116018 ** SQLite no longer uses thread-specific data so this routine is now a
116019 ** no-op.  It is retained for historical compatibility.
116020 */
116021 SQLITE_API void sqlite3_thread_cleanup(void){
116022 }
116023 #endif
116024 
116025 /*
116026 ** Return meta information about a specific column of a database table.
116027 ** See comment in sqlite3.h (sqlite.h.in) for details.
116028 */
116029 #ifdef SQLITE_ENABLE_COLUMN_METADATA
116030 SQLITE_API int sqlite3_table_column_metadata(
116031   sqlite3 *db,                /* Connection handle */
116032   const char *zDbName,        /* Database name or NULL */
116033   const char *zTableName,     /* Table name */
116034   const char *zColumnName,    /* Column name */
116035   char const **pzDataType,    /* OUTPUT: Declared data type */
116036   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
116037   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
116038   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
116039   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
116040 ){
116041   int rc;
116042   char *zErrMsg = 0;
116043   Table *pTab = 0;
116044   Column *pCol = 0;
116045   int iCol;
116046 
116047   char const *zDataType = 0;
116048   char const *zCollSeq = 0;
116049   int notnull = 0;
116050   int primarykey = 0;
116051   int autoinc = 0;
116052 
116053   /* Ensure the database schema has been loaded */
116054   sqlite3_mutex_enter(db->mutex);
116055   sqlite3BtreeEnterAll(db);
116056   rc = sqlite3Init(db, &zErrMsg);
116057   if( SQLITE_OK!=rc ){
116058     goto error_out;
116059   }
116060 
116061   /* Locate the table in question */
116062   pTab = sqlite3FindTable(db, zTableName, zDbName);
116063   if( !pTab || pTab->pSelect ){
116064     pTab = 0;
116065     goto error_out;
116066   }
116067 
116068   /* Find the column for which info is requested */
116069   if( sqlite3IsRowid(zColumnName) ){
116070     iCol = pTab->iPKey;
116071     if( iCol>=0 ){
116072       pCol = &pTab->aCol[iCol];
116073     }
116074   }else{
116075     for(iCol=0; iCol<pTab->nCol; iCol++){
116076       pCol = &pTab->aCol[iCol];
116077       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
116078         break;
116079       }
116080     }
116081     if( iCol==pTab->nCol ){
116082       pTab = 0;
116083       goto error_out;
116084     }
116085   }
116086 
116087   /* The following block stores the meta information that will be returned
116088   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
116089   ** and autoinc. At this point there are two possibilities:
116090   **
116091   **     1. The specified column name was rowid", "oid" or "_rowid_"
116092   **        and there is no explicitly declared IPK column.
116093   **
116094   **     2. The table is not a view and the column name identified an
116095   **        explicitly declared column. Copy meta information from *pCol.
116096   */
116097   if( pCol ){
116098     zDataType = pCol->zType;
116099     zCollSeq = pCol->zColl;
116100     notnull = pCol->notNull!=0;
116101     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
116102     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
116103   }else{
116104     zDataType = "INTEGER";
116105     primarykey = 1;
116106   }
116107   if( !zCollSeq ){
116108     zCollSeq = "BINARY";
116109   }
116110 
116111 error_out:
116112   sqlite3BtreeLeaveAll(db);
116113 
116114   /* Whether the function call succeeded or failed, set the output parameters
116115   ** to whatever their local counterparts contain. If an error did occur,
116116   ** this has the effect of zeroing all output parameters.
116117   */
116118   if( pzDataType ) *pzDataType = zDataType;
116119   if( pzCollSeq ) *pzCollSeq = zCollSeq;
116120   if( pNotNull ) *pNotNull = notnull;
116121   if( pPrimaryKey ) *pPrimaryKey = primarykey;
116122   if( pAutoinc ) *pAutoinc = autoinc;
116123 
116124   if( SQLITE_OK==rc && !pTab ){
116125     sqlite3DbFree(db, zErrMsg);
116126     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
116127         zColumnName);
116128     rc = SQLITE_ERROR;
116129   }
116130   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
116131   sqlite3DbFree(db, zErrMsg);
116132   rc = sqlite3ApiExit(db, rc);
116133   sqlite3_mutex_leave(db->mutex);
116134   return rc;
116135 }
116136 #endif
116137 
116138 /*
116139 ** Sleep for a little while.  Return the amount of time slept.
116140 */
116141 SQLITE_API int sqlite3_sleep(int ms){
116142   sqlite3_vfs *pVfs;
116143   int rc;
116144   pVfs = sqlite3_vfs_find(0);
116145   if( pVfs==0 ) return 0;
116146 
116147   /* This function works in milliseconds, but the underlying OsSleep()
116148   ** API uses microseconds. Hence the 1000's.
116149   */
116150   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
116151   return rc;
116152 }
116153 
116154 /*
116155 ** Enable or disable the extended result codes.
116156 */
116157 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
116158   sqlite3_mutex_enter(db->mutex);
116159   db->errMask = onoff ? 0xffffffff : 0xff;
116160   sqlite3_mutex_leave(db->mutex);
116161   return SQLITE_OK;
116162 }
116163 
116164 /*
116165 ** Invoke the xFileControl method on a particular database.
116166 */
116167 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
116168   int rc = SQLITE_ERROR;
116169   Btree *pBtree;
116170 
116171   sqlite3_mutex_enter(db->mutex);
116172   pBtree = sqlite3DbNameToBtree(db, zDbName);
116173   if( pBtree ){
116174     Pager *pPager;
116175     sqlite3_file *fd;
116176     sqlite3BtreeEnter(pBtree);
116177     pPager = sqlite3BtreePager(pBtree);
116178     assert( pPager!=0 );
116179     fd = sqlite3PagerFile(pPager);
116180     assert( fd!=0 );
116181     if( op==SQLITE_FCNTL_FILE_POINTER ){
116182       *(sqlite3_file**)pArg = fd;
116183       rc = SQLITE_OK;
116184     }else if( fd->pMethods ){
116185       rc = sqlite3OsFileControl(fd, op, pArg);
116186     }else{
116187       rc = SQLITE_NOTFOUND;
116188     }
116189     sqlite3BtreeLeave(pBtree);
116190   }
116191   sqlite3_mutex_leave(db->mutex);
116192   return rc;
116193 }
116194 
116195 /*
116196 ** Interface to the testing logic.
116197 */
116198 SQLITE_API int sqlite3_test_control(int op, ...){
116199   int rc = 0;
116200 #ifndef SQLITE_OMIT_BUILTIN_TEST
116201   va_list ap;
116202   va_start(ap, op);
116203   switch( op ){
116204 
116205     /*
116206     ** Save the current state of the PRNG.
116207     */
116208     case SQLITE_TESTCTRL_PRNG_SAVE: {
116209       sqlite3PrngSaveState();
116210       break;
116211     }
116212 
116213     /*
116214     ** Restore the state of the PRNG to the last state saved using
116215     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
116216     ** this verb acts like PRNG_RESET.
116217     */
116218     case SQLITE_TESTCTRL_PRNG_RESTORE: {
116219       sqlite3PrngRestoreState();
116220       break;
116221     }
116222 
116223     /*
116224     ** Reset the PRNG back to its uninitialized state.  The next call
116225     ** to sqlite3_randomness() will reseed the PRNG using a single call
116226     ** to the xRandomness method of the default VFS.
116227     */
116228     case SQLITE_TESTCTRL_PRNG_RESET: {
116229       sqlite3PrngResetState();
116230       break;
116231     }
116232 
116233     /*
116234     **  sqlite3_test_control(BITVEC_TEST, size, program)
116235     **
116236     ** Run a test against a Bitvec object of size.  The program argument
116237     ** is an array of integers that defines the test.  Return -1 on a
116238     ** memory allocation error, 0 on success, or non-zero for an error.
116239     ** See the sqlite3BitvecBuiltinTest() for additional information.
116240     */
116241     case SQLITE_TESTCTRL_BITVEC_TEST: {
116242       int sz = va_arg(ap, int);
116243       int *aProg = va_arg(ap, int*);
116244       rc = sqlite3BitvecBuiltinTest(sz, aProg);
116245       break;
116246     }
116247 
116248     /*
116249     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
116250     **
116251     ** Register hooks to call to indicate which malloc() failures
116252     ** are benign.
116253     */
116254     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
116255       typedef void (*void_function)(void);
116256       void_function xBenignBegin;
116257       void_function xBenignEnd;
116258       xBenignBegin = va_arg(ap, void_function);
116259       xBenignEnd = va_arg(ap, void_function);
116260       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
116261       break;
116262     }
116263 
116264     /*
116265     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
116266     **
116267     ** Set the PENDING byte to the value in the argument, if X>0.
116268     ** Make no changes if X==0.  Return the value of the pending byte
116269     ** as it existing before this routine was called.
116270     **
116271     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
116272     ** an incompatible database file format.  Changing the PENDING byte
116273     ** while any database connection is open results in undefined and
116274     ** dileterious behavior.
116275     */
116276     case SQLITE_TESTCTRL_PENDING_BYTE: {
116277       rc = PENDING_BYTE;
116278 #ifndef SQLITE_OMIT_WSD
116279       {
116280         unsigned int newVal = va_arg(ap, unsigned int);
116281         if( newVal ) sqlite3PendingByte = newVal;
116282       }
116283 #endif
116284       break;
116285     }
116286 
116287     /*
116288     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
116289     **
116290     ** This action provides a run-time test to see whether or not
116291     ** assert() was enabled at compile-time.  If X is true and assert()
116292     ** is enabled, then the return value is true.  If X is true and
116293     ** assert() is disabled, then the return value is zero.  If X is
116294     ** false and assert() is enabled, then the assertion fires and the
116295     ** process aborts.  If X is false and assert() is disabled, then the
116296     ** return value is zero.
116297     */
116298     case SQLITE_TESTCTRL_ASSERT: {
116299       volatile int x = 0;
116300       assert( (x = va_arg(ap,int))!=0 );
116301       rc = x;
116302       break;
116303     }
116304 
116305 
116306     /*
116307     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
116308     **
116309     ** This action provides a run-time test to see how the ALWAYS and
116310     ** NEVER macros were defined at compile-time.
116311     **
116312     ** The return value is ALWAYS(X).
116313     **
116314     ** The recommended test is X==2.  If the return value is 2, that means
116315     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
116316     ** default setting.  If the return value is 1, then ALWAYS() is either
116317     ** hard-coded to true or else it asserts if its argument is false.
116318     ** The first behavior (hard-coded to true) is the case if
116319     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
116320     ** behavior (assert if the argument to ALWAYS() is false) is the case if
116321     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
116322     **
116323     ** The run-time test procedure might look something like this:
116324     **
116325     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
116326     **      // ALWAYS() and NEVER() are no-op pass-through macros
116327     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
116328     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
116329     **    }else{
116330     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
116331     **    }
116332     */
116333     case SQLITE_TESTCTRL_ALWAYS: {
116334       int x = va_arg(ap,int);
116335       rc = ALWAYS(x);
116336       break;
116337     }
116338 
116339     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
116340     **
116341     ** Set the nReserve size to N for the main database on the database
116342     ** connection db.
116343     */
116344     case SQLITE_TESTCTRL_RESERVE: {
116345       sqlite3 *db = va_arg(ap, sqlite3*);
116346       int x = va_arg(ap,int);
116347       sqlite3_mutex_enter(db->mutex);
116348       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
116349       sqlite3_mutex_leave(db->mutex);
116350       break;
116351     }
116352 
116353     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
116354     **
116355     ** Enable or disable various optimizations for testing purposes.  The
116356     ** argument N is a bitmask of optimizations to be disabled.  For normal
116357     ** operation N should be 0.  The idea is that a test program (like the
116358     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
116359     ** with various optimizations disabled to verify that the same answer
116360     ** is obtained in every case.
116361     */
116362     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
116363       sqlite3 *db = va_arg(ap, sqlite3*);
116364       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
116365       break;
116366     }
116367 
116368 #ifdef SQLITE_N_KEYWORD
116369     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
116370     **
116371     ** If zWord is a keyword recognized by the parser, then return the
116372     ** number of keywords.  Or if zWord is not a keyword, return 0.
116373     **
116374     ** This test feature is only available in the amalgamation since
116375     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
116376     ** is built using separate source files.
116377     */
116378     case SQLITE_TESTCTRL_ISKEYWORD: {
116379       const char *zWord = va_arg(ap, const char*);
116380       int n = sqlite3Strlen30(zWord);
116381       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
116382       break;
116383     }
116384 #endif
116385 
116386     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
116387     **
116388     ** Pass pFree into sqlite3ScratchFree().
116389     ** If sz>0 then allocate a scratch buffer into pNew.
116390     */
116391     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
116392       void *pFree, **ppNew;
116393       int sz;
116394       sz = va_arg(ap, int);
116395       ppNew = va_arg(ap, void**);
116396       pFree = va_arg(ap, void*);
116397       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
116398       sqlite3ScratchFree(pFree);
116399       break;
116400     }
116401 
116402     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
116403     **
116404     ** If parameter onoff is non-zero, configure the wrappers so that all
116405     ** subsequent calls to localtime() and variants fail. If onoff is zero,
116406     ** undo this setting.
116407     */
116408     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
116409       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
116410       break;
116411     }
116412 
116413 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
116414     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
116415     **                        sqlite3_stmt*,const char**);
116416     **
116417     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
116418     ** a string that describes the optimized parse tree.  This test-control
116419     ** returns a pointer to that string.
116420     */
116421     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
116422       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
116423       const char **pzRet = va_arg(ap, const char**);
116424       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
116425       break;
116426     }
116427 #endif
116428 
116429   }
116430   va_end(ap);
116431 #endif /* SQLITE_OMIT_BUILTIN_TEST */
116432   return rc;
116433 }
116434 
116435 /*
116436 ** This is a utility routine, useful to VFS implementations, that checks
116437 ** to see if a database file was a URI that contained a specific query
116438 ** parameter, and if so obtains the value of the query parameter.
116439 **
116440 ** The zFilename argument is the filename pointer passed into the xOpen()
116441 ** method of a VFS implementation.  The zParam argument is the name of the
116442 ** query parameter we seek.  This routine returns the value of the zParam
116443 ** parameter if it exists.  If the parameter does not exist, this routine
116444 ** returns a NULL pointer.
116445 */
116446 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
116447   if( zFilename==0 ) return 0;
116448   zFilename += sqlite3Strlen30(zFilename) + 1;
116449   while( zFilename[0] ){
116450     int x = strcmp(zFilename, zParam);
116451     zFilename += sqlite3Strlen30(zFilename) + 1;
116452     if( x==0 ) return zFilename;
116453     zFilename += sqlite3Strlen30(zFilename) + 1;
116454   }
116455   return 0;
116456 }
116457 
116458 /*
116459 ** Return a boolean value for a query parameter.
116460 */
116461 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
116462   const char *z = sqlite3_uri_parameter(zFilename, zParam);
116463   bDflt = bDflt!=0;
116464   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
116465 }
116466 
116467 /*
116468 ** Return a 64-bit integer value for a query parameter.
116469 */
116470 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
116471   const char *zFilename,    /* Filename as passed to xOpen */
116472   const char *zParam,       /* URI parameter sought */
116473   sqlite3_int64 bDflt       /* return if parameter is missing */
116474 ){
116475   const char *z = sqlite3_uri_parameter(zFilename, zParam);
116476   sqlite3_int64 v;
116477   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
116478     bDflt = v;
116479   }
116480   return bDflt;
116481 }
116482 
116483 /*
116484 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
116485 */
116486 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
116487   int i;
116488   for(i=0; i<db->nDb; i++){
116489     if( db->aDb[i].pBt
116490      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
116491     ){
116492       return db->aDb[i].pBt;
116493     }
116494   }
116495   return 0;
116496 }
116497 
116498 /*
116499 ** Return the filename of the database associated with a database
116500 ** connection.
116501 */
116502 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
116503   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
116504   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
116505 }
116506 
116507 /*
116508 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
116509 ** no such database exists.
116510 */
116511 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
116512   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
116513   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
116514 }
116515 
116516 /************** End of main.c ************************************************/
116517 /************** Begin file notify.c ******************************************/
116518 /*
116519 ** 2009 March 3
116520 **
116521 ** The author disclaims copyright to this source code.  In place of
116522 ** a legal notice, here is a blessing:
116523 **
116524 **    May you do good and not evil.
116525 **    May you find forgiveness for yourself and forgive others.
116526 **    May you share freely, never taking more than you give.
116527 **
116528 *************************************************************************
116529 **
116530 ** This file contains the implementation of the sqlite3_unlock_notify()
116531 ** API method and its associated functionality.
116532 */
116533 
116534 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
116535 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
116536 
116537 /*
116538 ** Public interfaces:
116539 **
116540 **   sqlite3ConnectionBlocked()
116541 **   sqlite3ConnectionUnlocked()
116542 **   sqlite3ConnectionClosed()
116543 **   sqlite3_unlock_notify()
116544 */
116545 
116546 #define assertMutexHeld() \
116547   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
116548 
116549 /*
116550 ** Head of a linked list of all sqlite3 objects created by this process
116551 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
116552 ** is not NULL. This variable may only accessed while the STATIC_MASTER
116553 ** mutex is held.
116554 */
116555 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
116556 
116557 #ifndef NDEBUG
116558 /*
116559 ** This function is a complex assert() that verifies the following
116560 ** properties of the blocked connections list:
116561 **
116562 **   1) Each entry in the list has a non-NULL value for either
116563 **      pUnlockConnection or pBlockingConnection, or both.
116564 **
116565 **   2) All entries in the list that share a common value for
116566 **      xUnlockNotify are grouped together.
116567 **
116568 **   3) If the argument db is not NULL, then none of the entries in the
116569 **      blocked connections list have pUnlockConnection or pBlockingConnection
116570 **      set to db. This is used when closing connection db.
116571 */
116572 static void checkListProperties(sqlite3 *db){
116573   sqlite3 *p;
116574   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
116575     int seen = 0;
116576     sqlite3 *p2;
116577 
116578     /* Verify property (1) */
116579     assert( p->pUnlockConnection || p->pBlockingConnection );
116580 
116581     /* Verify property (2) */
116582     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
116583       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
116584       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
116585       assert( db==0 || p->pUnlockConnection!=db );
116586       assert( db==0 || p->pBlockingConnection!=db );
116587     }
116588   }
116589 }
116590 #else
116591 # define checkListProperties(x)
116592 #endif
116593 
116594 /*
116595 ** Remove connection db from the blocked connections list. If connection
116596 ** db is not currently a part of the list, this function is a no-op.
116597 */
116598 static void removeFromBlockedList(sqlite3 *db){
116599   sqlite3 **pp;
116600   assertMutexHeld();
116601   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
116602     if( *pp==db ){
116603       *pp = (*pp)->pNextBlocked;
116604       break;
116605     }
116606   }
116607 }
116608 
116609 /*
116610 ** Add connection db to the blocked connections list. It is assumed
116611 ** that it is not already a part of the list.
116612 */
116613 static void addToBlockedList(sqlite3 *db){
116614   sqlite3 **pp;
116615   assertMutexHeld();
116616   for(
116617     pp=&sqlite3BlockedList;
116618     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
116619     pp=&(*pp)->pNextBlocked
116620   );
116621   db->pNextBlocked = *pp;
116622   *pp = db;
116623 }
116624 
116625 /*
116626 ** Obtain the STATIC_MASTER mutex.
116627 */
116628 static void enterMutex(void){
116629   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
116630   checkListProperties(0);
116631 }
116632 
116633 /*
116634 ** Release the STATIC_MASTER mutex.
116635 */
116636 static void leaveMutex(void){
116637   assertMutexHeld();
116638   checkListProperties(0);
116639   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
116640 }
116641 
116642 /*
116643 ** Register an unlock-notify callback.
116644 **
116645 ** This is called after connection "db" has attempted some operation
116646 ** but has received an SQLITE_LOCKED error because another connection
116647 ** (call it pOther) in the same process was busy using the same shared
116648 ** cache.  pOther is found by looking at db->pBlockingConnection.
116649 **
116650 ** If there is no blocking connection, the callback is invoked immediately,
116651 ** before this routine returns.
116652 **
116653 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
116654 ** a deadlock.
116655 **
116656 ** Otherwise, make arrangements to invoke xNotify when pOther drops
116657 ** its locks.
116658 **
116659 ** Each call to this routine overrides any prior callbacks registered
116660 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
116661 ** cancelled.
116662 */
116663 SQLITE_API int sqlite3_unlock_notify(
116664   sqlite3 *db,
116665   void (*xNotify)(void **, int),
116666   void *pArg
116667 ){
116668   int rc = SQLITE_OK;
116669 
116670   sqlite3_mutex_enter(db->mutex);
116671   enterMutex();
116672 
116673   if( xNotify==0 ){
116674     removeFromBlockedList(db);
116675     db->pBlockingConnection = 0;
116676     db->pUnlockConnection = 0;
116677     db->xUnlockNotify = 0;
116678     db->pUnlockArg = 0;
116679   }else if( 0==db->pBlockingConnection ){
116680     /* The blocking transaction has been concluded. Or there never was a
116681     ** blocking transaction. In either case, invoke the notify callback
116682     ** immediately.
116683     */
116684     xNotify(&pArg, 1);
116685   }else{
116686     sqlite3 *p;
116687 
116688     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
116689     if( p ){
116690       rc = SQLITE_LOCKED;              /* Deadlock detected. */
116691     }else{
116692       db->pUnlockConnection = db->pBlockingConnection;
116693       db->xUnlockNotify = xNotify;
116694       db->pUnlockArg = pArg;
116695       removeFromBlockedList(db);
116696       addToBlockedList(db);
116697     }
116698   }
116699 
116700   leaveMutex();
116701   assert( !db->mallocFailed );
116702   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
116703   sqlite3_mutex_leave(db->mutex);
116704   return rc;
116705 }
116706 
116707 /*
116708 ** This function is called while stepping or preparing a statement
116709 ** associated with connection db. The operation will return SQLITE_LOCKED
116710 ** to the user because it requires a lock that will not be available
116711 ** until connection pBlocker concludes its current transaction.
116712 */
116713 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
116714   enterMutex();
116715   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
116716     addToBlockedList(db);
116717   }
116718   db->pBlockingConnection = pBlocker;
116719   leaveMutex();
116720 }
116721 
116722 /*
116723 ** This function is called when
116724 ** the transaction opened by database db has just finished. Locks held
116725 ** by database connection db have been released.
116726 **
116727 ** This function loops through each entry in the blocked connections
116728 ** list and does the following:
116729 **
116730 **   1) If the sqlite3.pBlockingConnection member of a list entry is
116731 **      set to db, then set pBlockingConnection=0.
116732 **
116733 **   2) If the sqlite3.pUnlockConnection member of a list entry is
116734 **      set to db, then invoke the configured unlock-notify callback and
116735 **      set pUnlockConnection=0.
116736 **
116737 **   3) If the two steps above mean that pBlockingConnection==0 and
116738 **      pUnlockConnection==0, remove the entry from the blocked connections
116739 **      list.
116740 */
116741 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
116742   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
116743   int nArg = 0;                            /* Number of entries in aArg[] */
116744   sqlite3 **pp;                            /* Iterator variable */
116745   void **aArg;               /* Arguments to the unlock callback */
116746   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
116747   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
116748 
116749   aArg = aStatic;
116750   enterMutex();         /* Enter STATIC_MASTER mutex */
116751 
116752   /* This loop runs once for each entry in the blocked-connections list. */
116753   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
116754     sqlite3 *p = *pp;
116755 
116756     /* Step 1. */
116757     if( p->pBlockingConnection==db ){
116758       p->pBlockingConnection = 0;
116759     }
116760 
116761     /* Step 2. */
116762     if( p->pUnlockConnection==db ){
116763       assert( p->xUnlockNotify );
116764       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
116765         xUnlockNotify(aArg, nArg);
116766         nArg = 0;
116767       }
116768 
116769       sqlite3BeginBenignMalloc();
116770       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
116771       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
116772       if( (!aDyn && nArg==(int)ArraySize(aStatic))
116773        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
116774       ){
116775         /* The aArg[] array needs to grow. */
116776         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
116777         if( pNew ){
116778           memcpy(pNew, aArg, nArg*sizeof(void *));
116779           sqlite3_free(aDyn);
116780           aDyn = aArg = pNew;
116781         }else{
116782           /* This occurs when the array of context pointers that need to
116783           ** be passed to the unlock-notify callback is larger than the
116784           ** aStatic[] array allocated on the stack and the attempt to
116785           ** allocate a larger array from the heap has failed.
116786           **
116787           ** This is a difficult situation to handle. Returning an error
116788           ** code to the caller is insufficient, as even if an error code
116789           ** is returned the transaction on connection db will still be
116790           ** closed and the unlock-notify callbacks on blocked connections
116791           ** will go unissued. This might cause the application to wait
116792           ** indefinitely for an unlock-notify callback that will never
116793           ** arrive.
116794           **
116795           ** Instead, invoke the unlock-notify callback with the context
116796           ** array already accumulated. We can then clear the array and
116797           ** begin accumulating any further context pointers without
116798           ** requiring any dynamic allocation. This is sub-optimal because
116799           ** it means that instead of one callback with a large array of
116800           ** context pointers the application will receive two or more
116801           ** callbacks with smaller arrays of context pointers, which will
116802           ** reduce the applications ability to prioritize multiple
116803           ** connections. But it is the best that can be done under the
116804           ** circumstances.
116805           */
116806           xUnlockNotify(aArg, nArg);
116807           nArg = 0;
116808         }
116809       }
116810       sqlite3EndBenignMalloc();
116811 
116812       aArg[nArg++] = p->pUnlockArg;
116813       xUnlockNotify = p->xUnlockNotify;
116814       p->pUnlockConnection = 0;
116815       p->xUnlockNotify = 0;
116816       p->pUnlockArg = 0;
116817     }
116818 
116819     /* Step 3. */
116820     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
116821       /* Remove connection p from the blocked connections list. */
116822       *pp = p->pNextBlocked;
116823       p->pNextBlocked = 0;
116824     }else{
116825       pp = &p->pNextBlocked;
116826     }
116827   }
116828 
116829   if( nArg!=0 ){
116830     xUnlockNotify(aArg, nArg);
116831   }
116832   sqlite3_free(aDyn);
116833   leaveMutex();         /* Leave STATIC_MASTER mutex */
116834 }
116835 
116836 /*
116837 ** This is called when the database connection passed as an argument is
116838 ** being closed. The connection is removed from the blocked list.
116839 */
116840 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
116841   sqlite3ConnectionUnlocked(db);
116842   enterMutex();
116843   removeFromBlockedList(db);
116844   checkListProperties(db);
116845   leaveMutex();
116846 }
116847 #endif
116848 
116849 /************** End of notify.c **********************************************/
116850 /************** Begin file fts3.c ********************************************/
116851 /*
116852 ** 2006 Oct 10
116853 **
116854 ** The author disclaims copyright to this source code.  In place of
116855 ** a legal notice, here is a blessing:
116856 **
116857 **    May you do good and not evil.
116858 **    May you find forgiveness for yourself and forgive others.
116859 **    May you share freely, never taking more than you give.
116860 **
116861 ******************************************************************************
116862 **
116863 ** This is an SQLite module implementing full-text search.
116864 */
116865 
116866 /*
116867 ** The code in this file is only compiled if:
116868 **
116869 **     * The FTS3 module is being built as an extension
116870 **       (in which case SQLITE_CORE is not defined), or
116871 **
116872 **     * The FTS3 module is being built into the core of
116873 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
116874 */
116875 
116876 /* The full-text index is stored in a series of b+tree (-like)
116877 ** structures called segments which map terms to doclists.  The
116878 ** structures are like b+trees in layout, but are constructed from the
116879 ** bottom up in optimal fashion and are not updatable.  Since trees
116880 ** are built from the bottom up, things will be described from the
116881 ** bottom up.
116882 **
116883 **
116884 **** Varints ****
116885 ** The basic unit of encoding is a variable-length integer called a
116886 ** varint.  We encode variable-length integers in little-endian order
116887 ** using seven bits * per byte as follows:
116888 **
116889 ** KEY:
116890 **         A = 0xxxxxxx    7 bits of data and one flag bit
116891 **         B = 1xxxxxxx    7 bits of data and one flag bit
116892 **
116893 **  7 bits - A
116894 ** 14 bits - BA
116895 ** 21 bits - BBA
116896 ** and so on.
116897 **
116898 ** This is similar in concept to how sqlite encodes "varints" but
116899 ** the encoding is not the same.  SQLite varints are big-endian
116900 ** are are limited to 9 bytes in length whereas FTS3 varints are
116901 ** little-endian and can be up to 10 bytes in length (in theory).
116902 **
116903 ** Example encodings:
116904 **
116905 **     1:    0x01
116906 **   127:    0x7f
116907 **   128:    0x81 0x00
116908 **
116909 **
116910 **** Document lists ****
116911 ** A doclist (document list) holds a docid-sorted list of hits for a
116912 ** given term.  Doclists hold docids and associated token positions.
116913 ** A docid is the unique integer identifier for a single document.
116914 ** A position is the index of a word within the document.  The first
116915 ** word of the document has a position of 0.
116916 **
116917 ** FTS3 used to optionally store character offsets using a compile-time
116918 ** option.  But that functionality is no longer supported.
116919 **
116920 ** A doclist is stored like this:
116921 **
116922 ** array {
116923 **   varint docid;          (delta from previous doclist)
116924 **   array {                (position list for column 0)
116925 **     varint position;     (2 more than the delta from previous position)
116926 **   }
116927 **   array {
116928 **     varint POS_COLUMN;   (marks start of position list for new column)
116929 **     varint column;       (index of new column)
116930 **     array {
116931 **       varint position;   (2 more than the delta from previous position)
116932 **     }
116933 **   }
116934 **   varint POS_END;        (marks end of positions for this document.
116935 ** }
116936 **
116937 ** Here, array { X } means zero or more occurrences of X, adjacent in
116938 ** memory.  A "position" is an index of a token in the token stream
116939 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
116940 ** in the same logical place as the position element, and act as sentinals
116941 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
116942 ** The positions numbers are not stored literally but rather as two more
116943 ** than the difference from the prior position, or the just the position plus
116944 ** 2 for the first position.  Example:
116945 **
116946 **   label:       A B C D E  F  G H   I  J K
116947 **   value:     123 5 9 1 1 14 35 0 234 72 0
116948 **
116949 ** The 123 value is the first docid.  For column zero in this document
116950 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
116951 ** at D signals the start of a new column; the 1 at E indicates that the
116952 ** new column is column number 1.  There are two positions at 12 and 45
116953 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
116954 ** 234 at I is the delta to next docid (357).  It has one position 70
116955 ** (72-2) and then terminates with the 0 at K.
116956 **
116957 ** A "position-list" is the list of positions for multiple columns for
116958 ** a single docid.  A "column-list" is the set of positions for a single
116959 ** column.  Hence, a position-list consists of one or more column-lists,
116960 ** a document record consists of a docid followed by a position-list and
116961 ** a doclist consists of one or more document records.
116962 **
116963 ** A bare doclist omits the position information, becoming an
116964 ** array of varint-encoded docids.
116965 **
116966 **** Segment leaf nodes ****
116967 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
116968 ** nodes are written using LeafWriter, and read using LeafReader (to
116969 ** iterate through a single leaf node's data) and LeavesReader (to
116970 ** iterate through a segment's entire leaf layer).  Leaf nodes have
116971 ** the format:
116972 **
116973 ** varint iHeight;             (height from leaf level, always 0)
116974 ** varint nTerm;               (length of first term)
116975 ** char pTerm[nTerm];          (content of first term)
116976 ** varint nDoclist;            (length of term's associated doclist)
116977 ** char pDoclist[nDoclist];    (content of doclist)
116978 ** array {
116979 **                             (further terms are delta-encoded)
116980 **   varint nPrefix;           (length of prefix shared with previous term)
116981 **   varint nSuffix;           (length of unshared suffix)
116982 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
116983 **   varint nDoclist;          (length of term's associated doclist)
116984 **   char pDoclist[nDoclist];  (content of doclist)
116985 ** }
116986 **
116987 ** Here, array { X } means zero or more occurrences of X, adjacent in
116988 ** memory.
116989 **
116990 ** Leaf nodes are broken into blocks which are stored contiguously in
116991 ** the %_segments table in sorted order.  This means that when the end
116992 ** of a node is reached, the next term is in the node with the next
116993 ** greater node id.
116994 **
116995 ** New data is spilled to a new leaf node when the current node
116996 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
116997 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
116998 ** node (a leaf node with a single term and doclist).  The goal of
116999 ** these settings is to pack together groups of small doclists while
117000 ** making it efficient to directly access large doclists.  The
117001 ** assumption is that large doclists represent terms which are more
117002 ** likely to be query targets.
117003 **
117004 ** TODO(shess) It may be useful for blocking decisions to be more
117005 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
117006 ** node rather than splitting into 2k and .5k nodes.  My intuition is
117007 ** that this might extend through 2x or 4x the pagesize.
117008 **
117009 **
117010 **** Segment interior nodes ****
117011 ** Segment interior nodes store blockids for subtree nodes and terms
117012 ** to describe what data is stored by the each subtree.  Interior
117013 ** nodes are written using InteriorWriter, and read using
117014 ** InteriorReader.  InteriorWriters are created as needed when
117015 ** SegmentWriter creates new leaf nodes, or when an interior node
117016 ** itself grows too big and must be split.  The format of interior
117017 ** nodes:
117018 **
117019 ** varint iHeight;           (height from leaf level, always >0)
117020 ** varint iBlockid;          (block id of node's leftmost subtree)
117021 ** optional {
117022 **   varint nTerm;           (length of first term)
117023 **   char pTerm[nTerm];      (content of first term)
117024 **   array {
117025 **                                (further terms are delta-encoded)
117026 **     varint nPrefix;            (length of shared prefix with previous term)
117027 **     varint nSuffix;            (length of unshared suffix)
117028 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
117029 **   }
117030 ** }
117031 **
117032 ** Here, optional { X } means an optional element, while array { X }
117033 ** means zero or more occurrences of X, adjacent in memory.
117034 **
117035 ** An interior node encodes n terms separating n+1 subtrees.  The
117036 ** subtree blocks are contiguous, so only the first subtree's blockid
117037 ** is encoded.  The subtree at iBlockid will contain all terms less
117038 ** than the first term encoded (or all terms if no term is encoded).
117039 ** Otherwise, for terms greater than or equal to pTerm[i] but less
117040 ** than pTerm[i+1], the subtree for that term will be rooted at
117041 ** iBlockid+i.  Interior nodes only store enough term data to
117042 ** distinguish adjacent children (if the rightmost term of the left
117043 ** child is "something", and the leftmost term of the right child is
117044 ** "wicked", only "w" is stored).
117045 **
117046 ** New data is spilled to a new interior node at the same height when
117047 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
117048 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
117049 ** interior nodes and making the tree too skinny.  The interior nodes
117050 ** at a given height are naturally tracked by interior nodes at
117051 ** height+1, and so on.
117052 **
117053 **
117054 **** Segment directory ****
117055 ** The segment directory in table %_segdir stores meta-information for
117056 ** merging and deleting segments, and also the root node of the
117057 ** segment's tree.
117058 **
117059 ** The root node is the top node of the segment's tree after encoding
117060 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
117061 ** This could be either a leaf node or an interior node.  If the top
117062 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
117063 ** and a new root interior node is generated (which should always fit
117064 ** within ROOT_MAX because it only needs space for 2 varints, the
117065 ** height and the blockid of the previous root).
117066 **
117067 ** The meta-information in the segment directory is:
117068 **   level               - segment level (see below)
117069 **   idx                 - index within level
117070 **                       - (level,idx uniquely identify a segment)
117071 **   start_block         - first leaf node
117072 **   leaves_end_block    - last leaf node
117073 **   end_block           - last block (including interior nodes)
117074 **   root                - contents of root node
117075 **
117076 ** If the root node is a leaf node, then start_block,
117077 ** leaves_end_block, and end_block are all 0.
117078 **
117079 **
117080 **** Segment merging ****
117081 ** To amortize update costs, segments are grouped into levels and
117082 ** merged in batches.  Each increase in level represents exponentially
117083 ** more documents.
117084 **
117085 ** New documents (actually, document updates) are tokenized and
117086 ** written individually (using LeafWriter) to a level 0 segment, with
117087 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
117088 ** level 0 segments are merged into a single level 1 segment.  Level 1
117089 ** is populated like level 0, and eventually MERGE_COUNT level 1
117090 ** segments are merged to a single level 2 segment (representing
117091 ** MERGE_COUNT^2 updates), and so on.
117092 **
117093 ** A segment merge traverses all segments at a given level in
117094 ** parallel, performing a straightforward sorted merge.  Since segment
117095 ** leaf nodes are written in to the %_segments table in order, this
117096 ** merge traverses the underlying sqlite disk structures efficiently.
117097 ** After the merge, all segment blocks from the merged level are
117098 ** deleted.
117099 **
117100 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
117101 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
117102 ** very similar performance numbers to 16 on insertion, though they're
117103 ** a tiny bit slower (perhaps due to more overhead in merge-time
117104 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
117105 ** 16, 2 about 66% slower than 16.
117106 **
117107 ** At query time, high MERGE_COUNT increases the number of segments
117108 ** which need to be scanned and merged.  For instance, with 100k docs
117109 ** inserted:
117110 **
117111 **    MERGE_COUNT   segments
117112 **       16           25
117113 **        8           12
117114 **        4           10
117115 **        2            6
117116 **
117117 ** This appears to have only a moderate impact on queries for very
117118 ** frequent terms (which are somewhat dominated by segment merge
117119 ** costs), and infrequent and non-existent terms still seem to be fast
117120 ** even with many segments.
117121 **
117122 ** TODO(shess) That said, it would be nice to have a better query-side
117123 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
117124 ** optimizations to things like doclist merging will swing the sweet
117125 ** spot around.
117126 **
117127 **
117128 **
117129 **** Handling of deletions and updates ****
117130 ** Since we're using a segmented structure, with no docid-oriented
117131 ** index into the term index, we clearly cannot simply update the term
117132 ** index when a document is deleted or updated.  For deletions, we
117133 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
117134 ** we simply write the new doclist.  Segment merges overwrite older
117135 ** data for a particular docid with newer data, so deletes or updates
117136 ** will eventually overtake the earlier data and knock it out.  The
117137 ** query logic likewise merges doclists so that newer data knocks out
117138 ** older data.
117139 */
117140 
117141 /************** Include fts3Int.h in the middle of fts3.c ********************/
117142 /************** Begin file fts3Int.h *****************************************/
117143 /*
117144 ** 2009 Nov 12
117145 **
117146 ** The author disclaims copyright to this source code.  In place of
117147 ** a legal notice, here is a blessing:
117148 **
117149 **    May you do good and not evil.
117150 **    May you find forgiveness for yourself and forgive others.
117151 **    May you share freely, never taking more than you give.
117152 **
117153 ******************************************************************************
117154 **
117155 */
117156 #ifndef _FTSINT_H
117157 #define _FTSINT_H
117158 
117159 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
117160 # define NDEBUG 1
117161 #endif
117162 
117163 /*
117164 ** FTS4 is really an extension for FTS3.  It is enabled using the
117165 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
117166 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
117167 */
117168 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
117169 # define SQLITE_ENABLE_FTS3
117170 #endif
117171 
117172 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117173 
117174 /* If not building as part of the core, include sqlite3ext.h. */
117175 #ifndef SQLITE_CORE
117176 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
117177 #endif
117178 
117179 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
117180 /************** Begin file fts3_tokenizer.h **********************************/
117181 /*
117182 ** 2006 July 10
117183 **
117184 ** The author disclaims copyright to this source code.
117185 **
117186 *************************************************************************
117187 ** Defines the interface to tokenizers used by fulltext-search.  There
117188 ** are three basic components:
117189 **
117190 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
117191 ** interface functions.  This is essentially the class structure for
117192 ** tokenizers.
117193 **
117194 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
117195 ** including customization information defined at creation time.
117196 **
117197 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
117198 ** tokens from a particular input.
117199 */
117200 #ifndef _FTS3_TOKENIZER_H_
117201 #define _FTS3_TOKENIZER_H_
117202 
117203 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
117204 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
117205 ** we will need a way to register the API consistently.
117206 */
117207 
117208 /*
117209 ** Structures used by the tokenizer interface. When a new tokenizer
117210 ** implementation is registered, the caller provides a pointer to
117211 ** an sqlite3_tokenizer_module containing pointers to the callback
117212 ** functions that make up an implementation.
117213 **
117214 ** When an fts3 table is created, it passes any arguments passed to
117215 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
117216 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
117217 ** implementation. The xCreate() function in turn returns an
117218 ** sqlite3_tokenizer structure representing the specific tokenizer to
117219 ** be used for the fts3 table (customized by the tokenizer clause arguments).
117220 **
117221 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
117222 ** method is called. It returns an sqlite3_tokenizer_cursor object
117223 ** that may be used to tokenize a specific input buffer based on
117224 ** the tokenization rules supplied by a specific sqlite3_tokenizer
117225 ** object.
117226 */
117227 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
117228 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
117229 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
117230 
117231 struct sqlite3_tokenizer_module {
117232 
117233   /*
117234   ** Structure version. Should always be set to 0 or 1.
117235   */
117236   int iVersion;
117237 
117238   /*
117239   ** Create a new tokenizer. The values in the argv[] array are the
117240   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
117241   ** TABLE statement that created the fts3 table. For example, if
117242   ** the following SQL is executed:
117243   **
117244   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
117245   **
117246   ** then argc is set to 2, and the argv[] array contains pointers
117247   ** to the strings "arg1" and "arg2".
117248   **
117249   ** This method should return either SQLITE_OK (0), or an SQLite error
117250   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
117251   ** to point at the newly created tokenizer structure. The generic
117252   ** sqlite3_tokenizer.pModule variable should not be initialized by
117253   ** this callback. The caller will do so.
117254   */
117255   int (*xCreate)(
117256     int argc,                           /* Size of argv array */
117257     const char *const*argv,             /* Tokenizer argument strings */
117258     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
117259   );
117260 
117261   /*
117262   ** Destroy an existing tokenizer. The fts3 module calls this method
117263   ** exactly once for each successful call to xCreate().
117264   */
117265   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
117266 
117267   /*
117268   ** Create a tokenizer cursor to tokenize an input buffer. The caller
117269   ** is responsible for ensuring that the input buffer remains valid
117270   ** until the cursor is closed (using the xClose() method).
117271   */
117272   int (*xOpen)(
117273     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
117274     const char *pInput, int nBytes,      /* Input buffer */
117275     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
117276   );
117277 
117278   /*
117279   ** Destroy an existing tokenizer cursor. The fts3 module calls this
117280   ** method exactly once for each successful call to xOpen().
117281   */
117282   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
117283 
117284   /*
117285   ** Retrieve the next token from the tokenizer cursor pCursor. This
117286   ** method should either return SQLITE_OK and set the values of the
117287   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
117288   ** the end of the buffer has been reached, or an SQLite error code.
117289   **
117290   ** *ppToken should be set to point at a buffer containing the
117291   ** normalized version of the token (i.e. after any case-folding and/or
117292   ** stemming has been performed). *pnBytes should be set to the length
117293   ** of this buffer in bytes. The input text that generated the token is
117294   ** identified by the byte offsets returned in *piStartOffset and
117295   ** *piEndOffset. *piStartOffset should be set to the index of the first
117296   ** byte of the token in the input buffer. *piEndOffset should be set
117297   ** to the index of the first byte just past the end of the token in
117298   ** the input buffer.
117299   **
117300   ** The buffer *ppToken is set to point at is managed by the tokenizer
117301   ** implementation. It is only required to be valid until the next call
117302   ** to xNext() or xClose().
117303   */
117304   /* TODO(shess) current implementation requires pInput to be
117305   ** nul-terminated.  This should either be fixed, or pInput/nBytes
117306   ** should be converted to zInput.
117307   */
117308   int (*xNext)(
117309     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
117310     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
117311     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
117312     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
117313     int *piPosition      /* OUT: Number of tokens returned before this one */
117314   );
117315 
117316   /***********************************************************************
117317   ** Methods below this point are only available if iVersion>=1.
117318   */
117319 
117320   /*
117321   ** Configure the language id of a tokenizer cursor.
117322   */
117323   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
117324 };
117325 
117326 struct sqlite3_tokenizer {
117327   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
117328   /* Tokenizer implementations will typically add additional fields */
117329 };
117330 
117331 struct sqlite3_tokenizer_cursor {
117332   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
117333   /* Tokenizer implementations will typically add additional fields */
117334 };
117335 
117336 int fts3_global_term_cnt(int iTerm, int iCol);
117337 int fts3_term_cnt(int iTerm, int iCol);
117338 
117339 
117340 #endif /* _FTS3_TOKENIZER_H_ */
117341 
117342 /************** End of fts3_tokenizer.h **************************************/
117343 /************** Continuing where we left off in fts3Int.h ********************/
117344 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
117345 /************** Begin file fts3_hash.h ***************************************/
117346 /*
117347 ** 2001 September 22
117348 **
117349 ** The author disclaims copyright to this source code.  In place of
117350 ** a legal notice, here is a blessing:
117351 **
117352 **    May you do good and not evil.
117353 **    May you find forgiveness for yourself and forgive others.
117354 **    May you share freely, never taking more than you give.
117355 **
117356 *************************************************************************
117357 ** This is the header file for the generic hash-table implementation
117358 ** used in SQLite.  We've modified it slightly to serve as a standalone
117359 ** hash table implementation for the full-text indexing module.
117360 **
117361 */
117362 #ifndef _FTS3_HASH_H_
117363 #define _FTS3_HASH_H_
117364 
117365 /* Forward declarations of structures. */
117366 typedef struct Fts3Hash Fts3Hash;
117367 typedef struct Fts3HashElem Fts3HashElem;
117368 
117369 /* A complete hash table is an instance of the following structure.
117370 ** The internals of this structure are intended to be opaque -- client
117371 ** code should not attempt to access or modify the fields of this structure
117372 ** directly.  Change this structure only by using the routines below.
117373 ** However, many of the "procedures" and "functions" for modifying and
117374 ** accessing this structure are really macros, so we can't really make
117375 ** this structure opaque.
117376 */
117377 struct Fts3Hash {
117378   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
117379   char copyKey;           /* True if copy of key made on insert */
117380   int count;              /* Number of entries in this table */
117381   Fts3HashElem *first;    /* The first element of the array */
117382   int htsize;             /* Number of buckets in the hash table */
117383   struct _fts3ht {        /* the hash table */
117384     int count;               /* Number of entries with this hash */
117385     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
117386   } *ht;
117387 };
117388 
117389 /* Each element in the hash table is an instance of the following
117390 ** structure.  All elements are stored on a single doubly-linked list.
117391 **
117392 ** Again, this structure is intended to be opaque, but it can't really
117393 ** be opaque because it is used by macros.
117394 */
117395 struct Fts3HashElem {
117396   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
117397   void *data;                /* Data associated with this element */
117398   void *pKey; int nKey;      /* Key associated with this element */
117399 };
117400 
117401 /*
117402 ** There are 2 different modes of operation for a hash table:
117403 **
117404 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
117405 **                           (including the null-terminator, if any).  Case
117406 **                           is respected in comparisons.
117407 **
117408 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
117409 **                           memcmp() is used to compare keys.
117410 **
117411 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
117412 */
117413 #define FTS3_HASH_STRING    1
117414 #define FTS3_HASH_BINARY    2
117415 
117416 /*
117417 ** Access routines.  To delete, insert a NULL pointer.
117418 */
117419 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
117420 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
117421 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
117422 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
117423 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
117424 
117425 /*
117426 ** Shorthand for the functions above
117427 */
117428 #define fts3HashInit     sqlite3Fts3HashInit
117429 #define fts3HashInsert   sqlite3Fts3HashInsert
117430 #define fts3HashFind     sqlite3Fts3HashFind
117431 #define fts3HashClear    sqlite3Fts3HashClear
117432 #define fts3HashFindElem sqlite3Fts3HashFindElem
117433 
117434 /*
117435 ** Macros for looping over all elements of a hash table.  The idiom is
117436 ** like this:
117437 **
117438 **   Fts3Hash h;
117439 **   Fts3HashElem *p;
117440 **   ...
117441 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
117442 **     SomeStructure *pData = fts3HashData(p);
117443 **     // do something with pData
117444 **   }
117445 */
117446 #define fts3HashFirst(H)  ((H)->first)
117447 #define fts3HashNext(E)   ((E)->next)
117448 #define fts3HashData(E)   ((E)->data)
117449 #define fts3HashKey(E)    ((E)->pKey)
117450 #define fts3HashKeysize(E) ((E)->nKey)
117451 
117452 /*
117453 ** Number of entries in a hash table
117454 */
117455 #define fts3HashCount(H)  ((H)->count)
117456 
117457 #endif /* _FTS3_HASH_H_ */
117458 
117459 /************** End of fts3_hash.h *******************************************/
117460 /************** Continuing where we left off in fts3Int.h ********************/
117461 
117462 /*
117463 ** This constant controls how often segments are merged. Once there are
117464 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
117465 ** segment of level N+1.
117466 */
117467 #define FTS3_MERGE_COUNT 16
117468 
117469 /*
117470 ** This is the maximum amount of data (in bytes) to store in the
117471 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
117472 ** populated as documents are inserted/updated/deleted in a transaction
117473 ** and used to create a new segment when the transaction is committed.
117474 ** However if this limit is reached midway through a transaction, a new
117475 ** segment is created and the hash table cleared immediately.
117476 */
117477 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
117478 
117479 /*
117480 ** Macro to return the number of elements in an array. SQLite has a
117481 ** similar macro called ArraySize(). Use a different name to avoid
117482 ** a collision when building an amalgamation with built-in FTS3.
117483 */
117484 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
117485 
117486 
117487 #ifndef MIN
117488 # define MIN(x,y) ((x)<(y)?(x):(y))
117489 #endif
117490 #ifndef MAX
117491 # define MAX(x,y) ((x)>(y)?(x):(y))
117492 #endif
117493 
117494 /*
117495 ** Maximum length of a varint encoded integer. The varint format is different
117496 ** from that used by SQLite, so the maximum length is 10, not 9.
117497 */
117498 #define FTS3_VARINT_MAX 10
117499 
117500 /*
117501 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
117502 ** in the document set and zero or more prefix indexes. All indexes are stored
117503 ** as one or more b+-trees in the %_segments and %_segdir tables.
117504 **
117505 ** It is possible to determine which index a b+-tree belongs to based on the
117506 ** value stored in the "%_segdir.level" column. Given this value L, the index
117507 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
117508 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
117509 ** between 1024 and 2047 to index 1, and so on.
117510 **
117511 ** It is considered impossible for an index to use more than 1024 levels. In
117512 ** theory though this may happen, but only after at least
117513 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
117514 */
117515 #define FTS3_SEGDIR_MAXLEVEL      1024
117516 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
117517 
117518 /*
117519 ** The testcase() macro is only used by the amalgamation.  If undefined,
117520 ** make it a no-op.
117521 */
117522 #ifndef testcase
117523 # define testcase(X)
117524 #endif
117525 
117526 /*
117527 ** Terminator values for position-lists and column-lists.
117528 */
117529 #define POS_COLUMN  (1)     /* Column-list terminator */
117530 #define POS_END     (0)     /* Position-list terminator */
117531 
117532 /*
117533 ** This section provides definitions to allow the
117534 ** FTS3 extension to be compiled outside of the
117535 ** amalgamation.
117536 */
117537 #ifndef SQLITE_AMALGAMATION
117538 /*
117539 ** Macros indicating that conditional expressions are always true or
117540 ** false.
117541 */
117542 #ifdef SQLITE_COVERAGE_TEST
117543 # define ALWAYS(x) (1)
117544 # define NEVER(X)  (0)
117545 #else
117546 # define ALWAYS(x) (x)
117547 # define NEVER(x)  (x)
117548 #endif
117549 
117550 /*
117551 ** Internal types used by SQLite.
117552 */
117553 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
117554 typedef short int i16;            /* 2-byte (or larger) signed integer */
117555 typedef unsigned int u32;         /* 4-byte unsigned integer */
117556 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
117557 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
117558 
117559 /*
117560 ** Macro used to suppress compiler warnings for unused parameters.
117561 */
117562 #define UNUSED_PARAMETER(x) (void)(x)
117563 
117564 /*
117565 ** Activate assert() only if SQLITE_TEST is enabled.
117566 */
117567 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
117568 # define NDEBUG 1
117569 #endif
117570 
117571 /*
117572 ** The TESTONLY macro is used to enclose variable declarations or
117573 ** other bits of code that are needed to support the arguments
117574 ** within testcase() and assert() macros.
117575 */
117576 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
117577 # define TESTONLY(X)  X
117578 #else
117579 # define TESTONLY(X)
117580 #endif
117581 
117582 #endif /* SQLITE_AMALGAMATION */
117583 
117584 #ifdef SQLITE_DEBUG
117585 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
117586 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
117587 #else
117588 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
117589 #endif
117590 
117591 typedef struct Fts3Table Fts3Table;
117592 typedef struct Fts3Cursor Fts3Cursor;
117593 typedef struct Fts3Expr Fts3Expr;
117594 typedef struct Fts3Phrase Fts3Phrase;
117595 typedef struct Fts3PhraseToken Fts3PhraseToken;
117596 
117597 typedef struct Fts3Doclist Fts3Doclist;
117598 typedef struct Fts3SegFilter Fts3SegFilter;
117599 typedef struct Fts3DeferredToken Fts3DeferredToken;
117600 typedef struct Fts3SegReader Fts3SegReader;
117601 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
117602 
117603 /*
117604 ** A connection to a fulltext index is an instance of the following
117605 ** structure. The xCreate and xConnect methods create an instance
117606 ** of this structure and xDestroy and xDisconnect free that instance.
117607 ** All other methods receive a pointer to the structure as one of their
117608 ** arguments.
117609 */
117610 struct Fts3Table {
117611   sqlite3_vtab base;              /* Base class used by SQLite core */
117612   sqlite3 *db;                    /* The database connection */
117613   const char *zDb;                /* logical database name */
117614   const char *zName;              /* virtual table name */
117615   int nColumn;                    /* number of named columns in virtual table */
117616   char **azColumn;                /* column names.  malloced */
117617   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
117618   char *zContentTbl;              /* content=xxx option, or NULL */
117619   char *zLanguageid;              /* languageid=xxx option, or NULL */
117620   u8 bAutoincrmerge;              /* True if automerge=1 */
117621   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
117622 
117623   /* Precompiled statements used by the implementation. Each of these
117624   ** statements is run and reset within a single virtual table API call.
117625   */
117626   sqlite3_stmt *aStmt[37];
117627 
117628   char *zReadExprlist;
117629   char *zWriteExprlist;
117630 
117631   int nNodeSize;                  /* Soft limit for node size */
117632   u8 bFts4;                       /* True for FTS4, false for FTS3 */
117633   u8 bHasStat;                    /* True if %_stat table exists */
117634   u8 bHasDocsize;                 /* True if %_docsize table exists */
117635   u8 bDescIdx;                    /* True if doclists are in reverse order */
117636   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
117637   int nPgsz;                      /* Page size for host database */
117638   char *zSegmentsTbl;             /* Name of %_segments table */
117639   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
117640 
117641   /*
117642   ** The following array of hash tables is used to buffer pending index
117643   ** updates during transactions. All pending updates buffered at any one
117644   ** time must share a common language-id (see the FTS4 langid= feature).
117645   ** The current language id is stored in variable iPrevLangid.
117646   **
117647   ** A single FTS4 table may have multiple full-text indexes. For each index
117648   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
117649   ** terms that appear in the document set. Each subsequent index in aIndex[]
117650   ** is an index of prefixes of a specific length.
117651   **
117652   ** Variable nPendingData contains an estimate the memory consumed by the
117653   ** pending data structures, including hash table overhead, but not including
117654   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
117655   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
117656   ** recently inserted record.
117657   */
117658   int nIndex;                     /* Size of aIndex[] */
117659   struct Fts3Index {
117660     int nPrefix;                  /* Prefix length (0 for main terms index) */
117661     Fts3Hash hPending;            /* Pending terms table for this index */
117662   } *aIndex;
117663   int nMaxPendingData;            /* Max pending data before flush to disk */
117664   int nPendingData;               /* Current bytes of pending data */
117665   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
117666   int iPrevLangid;                /* Langid of recently inserted document */
117667 
117668 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
117669   /* State variables used for validating that the transaction control
117670   ** methods of the virtual table are called at appropriate times.  These
117671   ** values do not contribute to FTS functionality; they are used for
117672   ** verifying the operation of the SQLite core.
117673   */
117674   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
117675   int mxSavepoint;       /* Largest valid xSavepoint integer */
117676 #endif
117677 };
117678 
117679 /*
117680 ** When the core wants to read from the virtual table, it creates a
117681 ** virtual table cursor (an instance of the following structure) using
117682 ** the xOpen method. Cursors are destroyed using the xClose method.
117683 */
117684 struct Fts3Cursor {
117685   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
117686   i16 eSearch;                    /* Search strategy (see below) */
117687   u8 isEof;                       /* True if at End Of Results */
117688   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
117689   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
117690   Fts3Expr *pExpr;                /* Parsed MATCH query string */
117691   int iLangid;                    /* Language being queried for */
117692   int nPhrase;                    /* Number of matchable phrases in query */
117693   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
117694   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
117695   char *pNextId;                  /* Pointer into the body of aDoclist */
117696   char *aDoclist;                 /* List of docids for full-text queries */
117697   int nDoclist;                   /* Size of buffer at aDoclist */
117698   u8 bDesc;                       /* True to sort in descending order */
117699   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
117700   int nRowAvg;                    /* Average size of database rows, in pages */
117701   sqlite3_int64 nDoc;             /* Documents in table */
117702 
117703   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
117704   u32 *aMatchinfo;                /* Information about most recent match */
117705   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
117706   char *zMatchinfo;               /* Matchinfo specification */
117707 };
117708 
117709 #define FTS3_EVAL_FILTER    0
117710 #define FTS3_EVAL_NEXT      1
117711 #define FTS3_EVAL_MATCHINFO 2
117712 
117713 /*
117714 ** The Fts3Cursor.eSearch member is always set to one of the following.
117715 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
117716 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
117717 ** of the column to be searched.  For example, in
117718 **
117719 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
117720 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
117721 **
117722 ** Because the LHS of the MATCH operator is 2nd column "b",
117723 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
117724 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
117725 ** indicating that all columns should be searched,
117726 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
117727 */
117728 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
117729 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
117730 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
117731 
117732 
117733 struct Fts3Doclist {
117734   char *aAll;                    /* Array containing doclist (or NULL) */
117735   int nAll;                      /* Size of a[] in bytes */
117736   char *pNextDocid;              /* Pointer to next docid */
117737 
117738   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
117739   int bFreeList;                 /* True if pList should be sqlite3_free()d */
117740   char *pList;                   /* Pointer to position list following iDocid */
117741   int nList;                     /* Length of position list */
117742 };
117743 
117744 /*
117745 ** A "phrase" is a sequence of one or more tokens that must match in
117746 ** sequence.  A single token is the base case and the most common case.
117747 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
117748 ** nToken will be the number of tokens in the string.
117749 */
117750 struct Fts3PhraseToken {
117751   char *z;                        /* Text of the token */
117752   int n;                          /* Number of bytes in buffer z */
117753   int isPrefix;                   /* True if token ends with a "*" character */
117754   int bFirst;                     /* True if token must appear at position 0 */
117755 
117756   /* Variables above this point are populated when the expression is
117757   ** parsed (by code in fts3_expr.c). Below this point the variables are
117758   ** used when evaluating the expression. */
117759   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
117760   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
117761 };
117762 
117763 struct Fts3Phrase {
117764   /* Cache of doclist for this phrase. */
117765   Fts3Doclist doclist;
117766   int bIncr;                 /* True if doclist is loaded incrementally */
117767   int iDoclistToken;
117768 
117769   /* Variables below this point are populated by fts3_expr.c when parsing
117770   ** a MATCH expression. Everything above is part of the evaluation phase.
117771   */
117772   int nToken;                /* Number of tokens in the phrase */
117773   int iColumn;               /* Index of column this phrase must match */
117774   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
117775 };
117776 
117777 /*
117778 ** A tree of these objects forms the RHS of a MATCH operator.
117779 **
117780 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
117781 ** points to a malloced buffer, size nDoclist bytes, containing the results
117782 ** of this phrase query in FTS3 doclist format. As usual, the initial
117783 ** "Length" field found in doclists stored on disk is omitted from this
117784 ** buffer.
117785 **
117786 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
117787 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
117788 ** where nCol is the number of columns in the queried FTS table. The array
117789 ** is populated as follows:
117790 **
117791 **   aMI[iCol*3 + 0] = Undefined
117792 **   aMI[iCol*3 + 1] = Number of occurrences
117793 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
117794 **
117795 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
117796 ** when the expression node is.
117797 */
117798 struct Fts3Expr {
117799   int eType;                 /* One of the FTSQUERY_XXX values defined below */
117800   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
117801   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
117802   Fts3Expr *pLeft;           /* Left operand */
117803   Fts3Expr *pRight;          /* Right operand */
117804   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
117805 
117806   /* The following are used by the fts3_eval.c module. */
117807   sqlite3_int64 iDocid;      /* Current docid */
117808   u8 bEof;                   /* True this expression is at EOF already */
117809   u8 bStart;                 /* True if iDocid is valid */
117810   u8 bDeferred;              /* True if this expression is entirely deferred */
117811 
117812   u32 *aMI;
117813 };
117814 
117815 /*
117816 ** Candidate values for Fts3Query.eType. Note that the order of the first
117817 ** four values is in order of precedence when parsing expressions. For
117818 ** example, the following:
117819 **
117820 **   "a OR b AND c NOT d NEAR e"
117821 **
117822 ** is equivalent to:
117823 **
117824 **   "a OR (b AND (c NOT (d NEAR e)))"
117825 */
117826 #define FTSQUERY_NEAR   1
117827 #define FTSQUERY_NOT    2
117828 #define FTSQUERY_AND    3
117829 #define FTSQUERY_OR     4
117830 #define FTSQUERY_PHRASE 5
117831 
117832 
117833 /* fts3_write.c */
117834 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
117835 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
117836 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
117837 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
117838 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
117839   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
117840 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
117841   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
117842 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
117843 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
117844 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
117845 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
117846 
117847 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
117848 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
117849 
117850 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
117851 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
117852 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
117853 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
117854 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
117855 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
117856 #else
117857 # define sqlite3Fts3FreeDeferredTokens(x)
117858 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
117859 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
117860 # define sqlite3Fts3FreeDeferredDoclists(x)
117861 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
117862 #endif
117863 
117864 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
117865 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
117866 
117867 /* Special values interpreted by sqlite3SegReaderCursor() */
117868 #define FTS3_SEGCURSOR_PENDING        -1
117869 #define FTS3_SEGCURSOR_ALL            -2
117870 
117871 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
117872 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
117873 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
117874 
117875 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
117876     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
117877 
117878 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
117879 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
117880 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
117881 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
117882 #define FTS3_SEGMENT_PREFIX        0x00000008
117883 #define FTS3_SEGMENT_SCAN          0x00000010
117884 #define FTS3_SEGMENT_FIRST         0x00000020
117885 
117886 /* Type passed as 4th argument to SegmentReaderIterate() */
117887 struct Fts3SegFilter {
117888   const char *zTerm;
117889   int nTerm;
117890   int iCol;
117891   int flags;
117892 };
117893 
117894 struct Fts3MultiSegReader {
117895   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
117896   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
117897   int nSegment;                   /* Size of apSegment array */
117898   int nAdvance;                   /* How many seg-readers to advance */
117899   Fts3SegFilter *pFilter;         /* Pointer to filter object */
117900   char *aBuffer;                  /* Buffer to merge doclists in */
117901   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
117902 
117903   int iColFilter;                 /* If >=0, filter for this column */
117904   int bRestart;
117905 
117906   /* Used by fts3.c only. */
117907   int nCost;                      /* Cost of running iterator */
117908   int bLookup;                    /* True if a lookup of a single entry. */
117909 
117910   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
117911   char *zTerm;                    /* Pointer to term buffer */
117912   int nTerm;                      /* Size of zTerm in bytes */
117913   char *aDoclist;                 /* Pointer to doclist buffer */
117914   int nDoclist;                   /* Size of aDoclist[] in bytes */
117915 };
117916 
117917 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
117918 
117919 /* fts3.c */
117920 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
117921 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
117922 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
117923 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
117924 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
117925 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
117926 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
117927 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
117928 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
117929 
117930 /* fts3_tokenizer.c */
117931 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
117932 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
117933 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
117934     sqlite3_tokenizer **, char **
117935 );
117936 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
117937 
117938 /* fts3_snippet.c */
117939 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
117940 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
117941   const char *, const char *, int, int
117942 );
117943 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
117944 
117945 /* fts3_expr.c */
117946 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
117947   char **, int, int, int, const char *, int, Fts3Expr **
117948 );
117949 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
117950 #ifdef SQLITE_TEST
117951 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
117952 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
117953 #endif
117954 
117955 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
117956   sqlite3_tokenizer_cursor **
117957 );
117958 
117959 /* fts3_aux.c */
117960 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
117961 
117962 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
117963 
117964 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
117965     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
117966 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
117967     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
117968 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
117969 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
117970 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
117971 
117972 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
117973 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
117974 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
117975 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
117976 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
117977 #endif
117978 
117979 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
117980 #endif /* _FTSINT_H */
117981 
117982 /************** End of fts3Int.h *********************************************/
117983 /************** Continuing where we left off in fts3.c ***********************/
117984 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117985 
117986 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
117987 # define SQLITE_CORE 1
117988 #endif
117989 
117990 /* #include <assert.h> */
117991 /* #include <stdlib.h> */
117992 /* #include <stddef.h> */
117993 /* #include <stdio.h> */
117994 /* #include <string.h> */
117995 /* #include <stdarg.h> */
117996 
117997 #ifndef SQLITE_CORE
117998   SQLITE_EXTENSION_INIT1
117999 #endif
118000 
118001 static int fts3EvalNext(Fts3Cursor *pCsr);
118002 static int fts3EvalStart(Fts3Cursor *pCsr);
118003 static int fts3TermSegReaderCursor(
118004     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
118005 
118006 /*
118007 ** Write a 64-bit variable-length integer to memory starting at p[0].
118008 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
118009 ** The number of bytes written is returned.
118010 */
118011 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
118012   unsigned char *q = (unsigned char *) p;
118013   sqlite_uint64 vu = v;
118014   do{
118015     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
118016     vu >>= 7;
118017   }while( vu!=0 );
118018   q[-1] &= 0x7f;  /* turn off high bit in final byte */
118019   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
118020   return (int) (q - (unsigned char *)p);
118021 }
118022 
118023 /*
118024 ** Read a 64-bit variable-length integer from memory starting at p[0].
118025 ** Return the number of bytes read, or 0 on error.
118026 ** The value is stored in *v.
118027 */
118028 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
118029   const unsigned char *q = (const unsigned char *) p;
118030   sqlite_uint64 x = 0, y = 1;
118031   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
118032     x += y * (*q++ & 0x7f);
118033     y <<= 7;
118034   }
118035   x += y * (*q++);
118036   *v = (sqlite_int64) x;
118037   return (int) (q - (unsigned char *)p);
118038 }
118039 
118040 /*
118041 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
118042 ** 32-bit integer before it is returned.
118043 */
118044 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
118045  sqlite_int64 i;
118046  int ret = sqlite3Fts3GetVarint(p, &i);
118047  *pi = (int) i;
118048  return ret;
118049 }
118050 
118051 /*
118052 ** Return the number of bytes required to encode v as a varint
118053 */
118054 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
118055   int i = 0;
118056   do{
118057     i++;
118058     v >>= 7;
118059   }while( v!=0 );
118060   return i;
118061 }
118062 
118063 /*
118064 ** Convert an SQL-style quoted string into a normal string by removing
118065 ** the quote characters.  The conversion is done in-place.  If the
118066 ** input does not begin with a quote character, then this routine
118067 ** is a no-op.
118068 **
118069 ** Examples:
118070 **
118071 **     "abc"   becomes   abc
118072 **     'xyz'   becomes   xyz
118073 **     [pqr]   becomes   pqr
118074 **     `mno`   becomes   mno
118075 **
118076 */
118077 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
118078   char quote;                     /* Quote character (if any ) */
118079 
118080   quote = z[0];
118081   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
118082     int iIn = 1;                  /* Index of next byte to read from input */
118083     int iOut = 0;                 /* Index of next byte to write to output */
118084 
118085     /* If the first byte was a '[', then the close-quote character is a ']' */
118086     if( quote=='[' ) quote = ']';
118087 
118088     while( ALWAYS(z[iIn]) ){
118089       if( z[iIn]==quote ){
118090         if( z[iIn+1]!=quote ) break;
118091         z[iOut++] = quote;
118092         iIn += 2;
118093       }else{
118094         z[iOut++] = z[iIn++];
118095       }
118096     }
118097     z[iOut] = '\0';
118098   }
118099 }
118100 
118101 /*
118102 ** Read a single varint from the doclist at *pp and advance *pp to point
118103 ** to the first byte past the end of the varint.  Add the value of the varint
118104 ** to *pVal.
118105 */
118106 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
118107   sqlite3_int64 iVal;
118108   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
118109   *pVal += iVal;
118110 }
118111 
118112 /*
118113 ** When this function is called, *pp points to the first byte following a
118114 ** varint that is part of a doclist (or position-list, or any other list
118115 ** of varints). This function moves *pp to point to the start of that varint,
118116 ** and sets *pVal by the varint value.
118117 **
118118 ** Argument pStart points to the first byte of the doclist that the
118119 ** varint is part of.
118120 */
118121 static void fts3GetReverseVarint(
118122   char **pp,
118123   char *pStart,
118124   sqlite3_int64 *pVal
118125 ){
118126   sqlite3_int64 iVal;
118127   char *p;
118128 
118129   /* Pointer p now points at the first byte past the varint we are
118130   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
118131   ** clear on character p[-1]. */
118132   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
118133   p++;
118134   *pp = p;
118135 
118136   sqlite3Fts3GetVarint(p, &iVal);
118137   *pVal = iVal;
118138 }
118139 
118140 /*
118141 ** The xDisconnect() virtual table method.
118142 */
118143 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
118144   Fts3Table *p = (Fts3Table *)pVtab;
118145   int i;
118146 
118147   assert( p->nPendingData==0 );
118148   assert( p->pSegments==0 );
118149 
118150   /* Free any prepared statements held */
118151   for(i=0; i<SizeofArray(p->aStmt); i++){
118152     sqlite3_finalize(p->aStmt[i]);
118153   }
118154   sqlite3_free(p->zSegmentsTbl);
118155   sqlite3_free(p->zReadExprlist);
118156   sqlite3_free(p->zWriteExprlist);
118157   sqlite3_free(p->zContentTbl);
118158   sqlite3_free(p->zLanguageid);
118159 
118160   /* Invoke the tokenizer destructor to free the tokenizer. */
118161   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
118162 
118163   sqlite3_free(p);
118164   return SQLITE_OK;
118165 }
118166 
118167 /*
118168 ** Construct one or more SQL statements from the format string given
118169 ** and then evaluate those statements. The success code is written
118170 ** into *pRc.
118171 **
118172 ** If *pRc is initially non-zero then this routine is a no-op.
118173 */
118174 static void fts3DbExec(
118175   int *pRc,              /* Success code */
118176   sqlite3 *db,           /* Database in which to run SQL */
118177   const char *zFormat,   /* Format string for SQL */
118178   ...                    /* Arguments to the format string */
118179 ){
118180   va_list ap;
118181   char *zSql;
118182   if( *pRc ) return;
118183   va_start(ap, zFormat);
118184   zSql = sqlite3_vmprintf(zFormat, ap);
118185   va_end(ap);
118186   if( zSql==0 ){
118187     *pRc = SQLITE_NOMEM;
118188   }else{
118189     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
118190     sqlite3_free(zSql);
118191   }
118192 }
118193 
118194 /*
118195 ** The xDestroy() virtual table method.
118196 */
118197 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
118198   Fts3Table *p = (Fts3Table *)pVtab;
118199   int rc = SQLITE_OK;              /* Return code */
118200   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
118201   sqlite3 *db = p->db;             /* Database handle */
118202 
118203   /* Drop the shadow tables */
118204   if( p->zContentTbl==0 ){
118205     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
118206   }
118207   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
118208   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
118209   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
118210   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
118211 
118212   /* If everything has worked, invoke fts3DisconnectMethod() to free the
118213   ** memory associated with the Fts3Table structure and return SQLITE_OK.
118214   ** Otherwise, return an SQLite error code.
118215   */
118216   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
118217 }
118218 
118219 
118220 /*
118221 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
118222 ** passed as the first argument. This is done as part of the xConnect()
118223 ** and xCreate() methods.
118224 **
118225 ** If *pRc is non-zero when this function is called, it is a no-op.
118226 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
118227 ** before returning.
118228 */
118229 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
118230   if( *pRc==SQLITE_OK ){
118231     int i;                        /* Iterator variable */
118232     int rc;                       /* Return code */
118233     char *zSql;                   /* SQL statement passed to declare_vtab() */
118234     char *zCols;                  /* List of user defined columns */
118235     const char *zLanguageid;
118236 
118237     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
118238     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
118239 
118240     /* Create a list of user columns for the virtual table */
118241     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
118242     for(i=1; zCols && i<p->nColumn; i++){
118243       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
118244     }
118245 
118246     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
118247     zSql = sqlite3_mprintf(
118248         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
118249         zCols, p->zName, zLanguageid
118250     );
118251     if( !zCols || !zSql ){
118252       rc = SQLITE_NOMEM;
118253     }else{
118254       rc = sqlite3_declare_vtab(p->db, zSql);
118255     }
118256 
118257     sqlite3_free(zSql);
118258     sqlite3_free(zCols);
118259     *pRc = rc;
118260   }
118261 }
118262 
118263 /*
118264 ** Create the %_stat table if it does not already exist.
118265 */
118266 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
118267   fts3DbExec(pRc, p->db,
118268       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
118269           "(id INTEGER PRIMARY KEY, value BLOB);",
118270       p->zDb, p->zName
118271   );
118272   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
118273 }
118274 
118275 /*
118276 ** Create the backing store tables (%_content, %_segments and %_segdir)
118277 ** required by the FTS3 table passed as the only argument. This is done
118278 ** as part of the vtab xCreate() method.
118279 **
118280 ** If the p->bHasDocsize boolean is true (indicating that this is an
118281 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
118282 ** %_stat tables required by FTS4.
118283 */
118284 static int fts3CreateTables(Fts3Table *p){
118285   int rc = SQLITE_OK;             /* Return code */
118286   int i;                          /* Iterator variable */
118287   sqlite3 *db = p->db;            /* The database connection */
118288 
118289   if( p->zContentTbl==0 ){
118290     const char *zLanguageid = p->zLanguageid;
118291     char *zContentCols;           /* Columns of %_content table */
118292 
118293     /* Create a list of user columns for the content table */
118294     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
118295     for(i=0; zContentCols && i<p->nColumn; i++){
118296       char *z = p->azColumn[i];
118297       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
118298     }
118299     if( zLanguageid && zContentCols ){
118300       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
118301     }
118302     if( zContentCols==0 ) rc = SQLITE_NOMEM;
118303 
118304     /* Create the content table */
118305     fts3DbExec(&rc, db,
118306        "CREATE TABLE %Q.'%q_content'(%s)",
118307        p->zDb, p->zName, zContentCols
118308     );
118309     sqlite3_free(zContentCols);
118310   }
118311 
118312   /* Create other tables */
118313   fts3DbExec(&rc, db,
118314       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
118315       p->zDb, p->zName
118316   );
118317   fts3DbExec(&rc, db,
118318       "CREATE TABLE %Q.'%q_segdir'("
118319         "level INTEGER,"
118320         "idx INTEGER,"
118321         "start_block INTEGER,"
118322         "leaves_end_block INTEGER,"
118323         "end_block INTEGER,"
118324         "root BLOB,"
118325         "PRIMARY KEY(level, idx)"
118326       ");",
118327       p->zDb, p->zName
118328   );
118329   if( p->bHasDocsize ){
118330     fts3DbExec(&rc, db,
118331         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
118332         p->zDb, p->zName
118333     );
118334   }
118335   assert( p->bHasStat==p->bFts4 );
118336   if( p->bHasStat ){
118337     sqlite3Fts3CreateStatTable(&rc, p);
118338   }
118339   return rc;
118340 }
118341 
118342 /*
118343 ** Store the current database page-size in bytes in p->nPgsz.
118344 **
118345 ** If *pRc is non-zero when this function is called, it is a no-op.
118346 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
118347 ** before returning.
118348 */
118349 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
118350   if( *pRc==SQLITE_OK ){
118351     int rc;                       /* Return code */
118352     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
118353     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
118354 
118355     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
118356     if( !zSql ){
118357       rc = SQLITE_NOMEM;
118358     }else{
118359       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
118360       if( rc==SQLITE_OK ){
118361         sqlite3_step(pStmt);
118362         p->nPgsz = sqlite3_column_int(pStmt, 0);
118363         rc = sqlite3_finalize(pStmt);
118364       }else if( rc==SQLITE_AUTH ){
118365         p->nPgsz = 1024;
118366         rc = SQLITE_OK;
118367       }
118368     }
118369     assert( p->nPgsz>0 || rc!=SQLITE_OK );
118370     sqlite3_free(zSql);
118371     *pRc = rc;
118372   }
118373 }
118374 
118375 /*
118376 ** "Special" FTS4 arguments are column specifications of the following form:
118377 **
118378 **   <key> = <value>
118379 **
118380 ** There may not be whitespace surrounding the "=" character. The <value>
118381 ** term may be quoted, but the <key> may not.
118382 */
118383 static int fts3IsSpecialColumn(
118384   const char *z,
118385   int *pnKey,
118386   char **pzValue
118387 ){
118388   char *zValue;
118389   const char *zCsr = z;
118390 
118391   while( *zCsr!='=' ){
118392     if( *zCsr=='\0' ) return 0;
118393     zCsr++;
118394   }
118395 
118396   *pnKey = (int)(zCsr-z);
118397   zValue = sqlite3_mprintf("%s", &zCsr[1]);
118398   if( zValue ){
118399     sqlite3Fts3Dequote(zValue);
118400   }
118401   *pzValue = zValue;
118402   return 1;
118403 }
118404 
118405 /*
118406 ** Append the output of a printf() style formatting to an existing string.
118407 */
118408 static void fts3Appendf(
118409   int *pRc,                       /* IN/OUT: Error code */
118410   char **pz,                      /* IN/OUT: Pointer to string buffer */
118411   const char *zFormat,            /* Printf format string to append */
118412   ...                             /* Arguments for printf format string */
118413 ){
118414   if( *pRc==SQLITE_OK ){
118415     va_list ap;
118416     char *z;
118417     va_start(ap, zFormat);
118418     z = sqlite3_vmprintf(zFormat, ap);
118419     va_end(ap);
118420     if( z && *pz ){
118421       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
118422       sqlite3_free(z);
118423       z = z2;
118424     }
118425     if( z==0 ) *pRc = SQLITE_NOMEM;
118426     sqlite3_free(*pz);
118427     *pz = z;
118428   }
118429 }
118430 
118431 /*
118432 ** Return a copy of input string zInput enclosed in double-quotes (") and
118433 ** with all double quote characters escaped. For example:
118434 **
118435 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
118436 **
118437 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
118438 ** is the callers responsibility to call sqlite3_free() to release this
118439 ** memory.
118440 */
118441 static char *fts3QuoteId(char const *zInput){
118442   int nRet;
118443   char *zRet;
118444   nRet = 2 + (int)strlen(zInput)*2 + 1;
118445   zRet = sqlite3_malloc(nRet);
118446   if( zRet ){
118447     int i;
118448     char *z = zRet;
118449     *(z++) = '"';
118450     for(i=0; zInput[i]; i++){
118451       if( zInput[i]=='"' ) *(z++) = '"';
118452       *(z++) = zInput[i];
118453     }
118454     *(z++) = '"';
118455     *(z++) = '\0';
118456   }
118457   return zRet;
118458 }
118459 
118460 /*
118461 ** Return a list of comma separated SQL expressions and a FROM clause that
118462 ** could be used in a SELECT statement such as the following:
118463 **
118464 **     SELECT <list of expressions> FROM %_content AS x ...
118465 **
118466 ** to return the docid, followed by each column of text data in order
118467 ** from left to write. If parameter zFunc is not NULL, then instead of
118468 ** being returned directly each column of text data is passed to an SQL
118469 ** function named zFunc first. For example, if zFunc is "unzip" and the
118470 ** table has the three user-defined columns "a", "b", and "c", the following
118471 ** string is returned:
118472 **
118473 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
118474 **
118475 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
118476 ** is the responsibility of the caller to eventually free it.
118477 **
118478 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
118479 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
118480 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
118481 ** no error occurs, *pRc is left unmodified.
118482 */
118483 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
118484   char *zRet = 0;
118485   char *zFree = 0;
118486   char *zFunction;
118487   int i;
118488 
118489   if( p->zContentTbl==0 ){
118490     if( !zFunc ){
118491       zFunction = "";
118492     }else{
118493       zFree = zFunction = fts3QuoteId(zFunc);
118494     }
118495     fts3Appendf(pRc, &zRet, "docid");
118496     for(i=0; i<p->nColumn; i++){
118497       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
118498     }
118499     if( p->zLanguageid ){
118500       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
118501     }
118502     sqlite3_free(zFree);
118503   }else{
118504     fts3Appendf(pRc, &zRet, "rowid");
118505     for(i=0; i<p->nColumn; i++){
118506       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
118507     }
118508     if( p->zLanguageid ){
118509       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
118510     }
118511   }
118512   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
118513       p->zDb,
118514       (p->zContentTbl ? p->zContentTbl : p->zName),
118515       (p->zContentTbl ? "" : "_content")
118516   );
118517   return zRet;
118518 }
118519 
118520 /*
118521 ** Return a list of N comma separated question marks, where N is the number
118522 ** of columns in the %_content table (one for the docid plus one for each
118523 ** user-defined text column).
118524 **
118525 ** If argument zFunc is not NULL, then all but the first question mark
118526 ** is preceded by zFunc and an open bracket, and followed by a closed
118527 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
118528 ** user-defined text columns, the following string is returned:
118529 **
118530 **     "?, zip(?), zip(?), zip(?)"
118531 **
118532 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
118533 ** is the responsibility of the caller to eventually free it.
118534 **
118535 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
118536 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
118537 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
118538 ** no error occurs, *pRc is left unmodified.
118539 */
118540 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
118541   char *zRet = 0;
118542   char *zFree = 0;
118543   char *zFunction;
118544   int i;
118545 
118546   if( !zFunc ){
118547     zFunction = "";
118548   }else{
118549     zFree = zFunction = fts3QuoteId(zFunc);
118550   }
118551   fts3Appendf(pRc, &zRet, "?");
118552   for(i=0; i<p->nColumn; i++){
118553     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
118554   }
118555   if( p->zLanguageid ){
118556     fts3Appendf(pRc, &zRet, ", ?");
118557   }
118558   sqlite3_free(zFree);
118559   return zRet;
118560 }
118561 
118562 /*
118563 ** This function interprets the string at (*pp) as a non-negative integer
118564 ** value. It reads the integer and sets *pnOut to the value read, then
118565 ** sets *pp to point to the byte immediately following the last byte of
118566 ** the integer value.
118567 **
118568 ** Only decimal digits ('0'..'9') may be part of an integer value.
118569 **
118570 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
118571 ** the output value undefined. Otherwise SQLITE_OK is returned.
118572 **
118573 ** This function is used when parsing the "prefix=" FTS4 parameter.
118574 */
118575 static int fts3GobbleInt(const char **pp, int *pnOut){
118576   const char *p;                  /* Iterator pointer */
118577   int nInt = 0;                   /* Output value */
118578 
118579   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
118580     nInt = nInt * 10 + (p[0] - '0');
118581   }
118582   if( p==*pp ) return SQLITE_ERROR;
118583   *pnOut = nInt;
118584   *pp = p;
118585   return SQLITE_OK;
118586 }
118587 
118588 /*
118589 ** This function is called to allocate an array of Fts3Index structures
118590 ** representing the indexes maintained by the current FTS table. FTS tables
118591 ** always maintain the main "terms" index, but may also maintain one or
118592 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
118593 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
118594 **
118595 ** Argument zParam is passed the value of the "prefix=" option if one was
118596 ** specified, or NULL otherwise.
118597 **
118598 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
118599 ** the allocated array. *pnIndex is set to the number of elements in the
118600 ** array. If an error does occur, an SQLite error code is returned.
118601 **
118602 ** Regardless of whether or not an error is returned, it is the responsibility
118603 ** of the caller to call sqlite3_free() on the output array to free it.
118604 */
118605 static int fts3PrefixParameter(
118606   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
118607   int *pnIndex,                   /* OUT: size of *apIndex[] array */
118608   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
118609 ){
118610   struct Fts3Index *aIndex;       /* Allocated array */
118611   int nIndex = 1;                 /* Number of entries in array */
118612 
118613   if( zParam && zParam[0] ){
118614     const char *p;
118615     nIndex++;
118616     for(p=zParam; *p; p++){
118617       if( *p==',' ) nIndex++;
118618     }
118619   }
118620 
118621   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
118622   *apIndex = aIndex;
118623   *pnIndex = nIndex;
118624   if( !aIndex ){
118625     return SQLITE_NOMEM;
118626   }
118627 
118628   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
118629   if( zParam ){
118630     const char *p = zParam;
118631     int i;
118632     for(i=1; i<nIndex; i++){
118633       int nPrefix;
118634       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
118635       aIndex[i].nPrefix = nPrefix;
118636       p++;
118637     }
118638   }
118639 
118640   return SQLITE_OK;
118641 }
118642 
118643 /*
118644 ** This function is called when initializing an FTS4 table that uses the
118645 ** content=xxx option. It determines the number of and names of the columns
118646 ** of the new FTS4 table.
118647 **
118648 ** The third argument passed to this function is the value passed to the
118649 ** config=xxx option (i.e. "xxx"). This function queries the database for
118650 ** a table of that name. If found, the output variables are populated
118651 ** as follows:
118652 **
118653 **   *pnCol:   Set to the number of columns table xxx has,
118654 **
118655 **   *pnStr:   Set to the total amount of space required to store a copy
118656 **             of each columns name, including the nul-terminator.
118657 **
118658 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
118659 **             the name of the corresponding column in table xxx. The array
118660 **             and its contents are allocated using a single allocation. It
118661 **             is the responsibility of the caller to free this allocation
118662 **             by eventually passing the *pazCol value to sqlite3_free().
118663 **
118664 ** If the table cannot be found, an error code is returned and the output
118665 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
118666 ** returned (and the output variables are undefined).
118667 */
118668 static int fts3ContentColumns(
118669   sqlite3 *db,                    /* Database handle */
118670   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
118671   const char *zTbl,               /* Name of content table */
118672   const char ***pazCol,           /* OUT: Malloc'd array of column names */
118673   int *pnCol,                     /* OUT: Size of array *pazCol */
118674   int *pnStr                      /* OUT: Bytes of string content */
118675 ){
118676   int rc = SQLITE_OK;             /* Return code */
118677   char *zSql;                     /* "SELECT *" statement on zTbl */
118678   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
118679 
118680   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
118681   if( !zSql ){
118682     rc = SQLITE_NOMEM;
118683   }else{
118684     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
118685   }
118686   sqlite3_free(zSql);
118687 
118688   if( rc==SQLITE_OK ){
118689     const char **azCol;           /* Output array */
118690     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
118691     int nCol;                     /* Number of table columns */
118692     int i;                        /* Used to iterate through columns */
118693 
118694     /* Loop through the returned columns. Set nStr to the number of bytes of
118695     ** space required to store a copy of each column name, including the
118696     ** nul-terminator byte.  */
118697     nCol = sqlite3_column_count(pStmt);
118698     for(i=0; i<nCol; i++){
118699       const char *zCol = sqlite3_column_name(pStmt, i);
118700       nStr += (int)strlen(zCol) + 1;
118701     }
118702 
118703     /* Allocate and populate the array to return. */
118704     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
118705     if( azCol==0 ){
118706       rc = SQLITE_NOMEM;
118707     }else{
118708       char *p = (char *)&azCol[nCol];
118709       for(i=0; i<nCol; i++){
118710         const char *zCol = sqlite3_column_name(pStmt, i);
118711         int n = (int)strlen(zCol)+1;
118712         memcpy(p, zCol, n);
118713         azCol[i] = p;
118714         p += n;
118715       }
118716     }
118717     sqlite3_finalize(pStmt);
118718 
118719     /* Set the output variables. */
118720     *pnCol = nCol;
118721     *pnStr = nStr;
118722     *pazCol = azCol;
118723   }
118724 
118725   return rc;
118726 }
118727 
118728 /*
118729 ** This function is the implementation of both the xConnect and xCreate
118730 ** methods of the FTS3 virtual table.
118731 **
118732 ** The argv[] array contains the following:
118733 **
118734 **   argv[0]   -> module name  ("fts3" or "fts4")
118735 **   argv[1]   -> database name
118736 **   argv[2]   -> table name
118737 **   argv[...] -> "column name" and other module argument fields.
118738 */
118739 static int fts3InitVtab(
118740   int isCreate,                   /* True for xCreate, false for xConnect */
118741   sqlite3 *db,                    /* The SQLite database connection */
118742   void *pAux,                     /* Hash table containing tokenizers */
118743   int argc,                       /* Number of elements in argv array */
118744   const char * const *argv,       /* xCreate/xConnect argument array */
118745   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
118746   char **pzErr                    /* Write any error message here */
118747 ){
118748   Fts3Hash *pHash = (Fts3Hash *)pAux;
118749   Fts3Table *p = 0;               /* Pointer to allocated vtab */
118750   int rc = SQLITE_OK;             /* Return code */
118751   int i;                          /* Iterator variable */
118752   int nByte;                      /* Size of allocation used for *p */
118753   int iCol;                       /* Column index */
118754   int nString = 0;                /* Bytes required to hold all column names */
118755   int nCol = 0;                   /* Number of columns in the FTS table */
118756   char *zCsr;                     /* Space for holding column names */
118757   int nDb;                        /* Bytes required to hold database name */
118758   int nName;                      /* Bytes required to hold table name */
118759   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
118760   const char **aCol;              /* Array of column names */
118761   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
118762 
118763   int nIndex;                     /* Size of aIndex[] array */
118764   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
118765 
118766   /* The results of parsing supported FTS4 key=value options: */
118767   int bNoDocsize = 0;             /* True to omit %_docsize table */
118768   int bDescIdx = 0;               /* True to store descending indexes */
118769   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
118770   char *zCompress = 0;            /* compress=? parameter (or NULL) */
118771   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
118772   char *zContent = 0;             /* content=? parameter (or NULL) */
118773   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
118774 
118775   assert( strlen(argv[0])==4 );
118776   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
118777        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
118778   );
118779 
118780   nDb = (int)strlen(argv[1]) + 1;
118781   nName = (int)strlen(argv[2]) + 1;
118782 
118783   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
118784   if( !aCol ) return SQLITE_NOMEM;
118785   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
118786 
118787   /* Loop through all of the arguments passed by the user to the FTS3/4
118788   ** module (i.e. all the column names and special arguments). This loop
118789   ** does the following:
118790   **
118791   **   + Figures out the number of columns the FTSX table will have, and
118792   **     the number of bytes of space that must be allocated to store copies
118793   **     of the column names.
118794   **
118795   **   + If there is a tokenizer specification included in the arguments,
118796   **     initializes the tokenizer pTokenizer.
118797   */
118798   for(i=3; rc==SQLITE_OK && i<argc; i++){
118799     char const *z = argv[i];
118800     int nKey;
118801     char *zVal;
118802 
118803     /* Check if this is a tokenizer specification */
118804     if( !pTokenizer
118805      && strlen(z)>8
118806      && 0==sqlite3_strnicmp(z, "tokenize", 8)
118807      && 0==sqlite3Fts3IsIdChar(z[8])
118808     ){
118809       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
118810     }
118811 
118812     /* Check if it is an FTS4 special argument. */
118813     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
118814       struct Fts4Option {
118815         const char *zOpt;
118816         int nOpt;
118817       } aFts4Opt[] = {
118818         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
118819         { "prefix",      6 },     /* 1 -> PREFIX */
118820         { "compress",    8 },     /* 2 -> COMPRESS */
118821         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
118822         { "order",       5 },     /* 4 -> ORDER */
118823         { "content",     7 },     /* 5 -> CONTENT */
118824         { "languageid", 10 }      /* 6 -> LANGUAGEID */
118825       };
118826 
118827       int iOpt;
118828       if( !zVal ){
118829         rc = SQLITE_NOMEM;
118830       }else{
118831         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
118832           struct Fts4Option *pOp = &aFts4Opt[iOpt];
118833           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
118834             break;
118835           }
118836         }
118837         if( iOpt==SizeofArray(aFts4Opt) ){
118838           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
118839           rc = SQLITE_ERROR;
118840         }else{
118841           switch( iOpt ){
118842             case 0:               /* MATCHINFO */
118843               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
118844                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
118845                 rc = SQLITE_ERROR;
118846               }
118847               bNoDocsize = 1;
118848               break;
118849 
118850             case 1:               /* PREFIX */
118851               sqlite3_free(zPrefix);
118852               zPrefix = zVal;
118853               zVal = 0;
118854               break;
118855 
118856             case 2:               /* COMPRESS */
118857               sqlite3_free(zCompress);
118858               zCompress = zVal;
118859               zVal = 0;
118860               break;
118861 
118862             case 3:               /* UNCOMPRESS */
118863               sqlite3_free(zUncompress);
118864               zUncompress = zVal;
118865               zVal = 0;
118866               break;
118867 
118868             case 4:               /* ORDER */
118869               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
118870                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
118871               ){
118872                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
118873                 rc = SQLITE_ERROR;
118874               }
118875               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
118876               break;
118877 
118878             case 5:              /* CONTENT */
118879               sqlite3_free(zContent);
118880               zContent = zVal;
118881               zVal = 0;
118882               break;
118883 
118884             case 6:              /* LANGUAGEID */
118885               assert( iOpt==6 );
118886               sqlite3_free(zLanguageid);
118887               zLanguageid = zVal;
118888               zVal = 0;
118889               break;
118890           }
118891         }
118892         sqlite3_free(zVal);
118893       }
118894     }
118895 
118896     /* Otherwise, the argument is a column name. */
118897     else {
118898       nString += (int)(strlen(z) + 1);
118899       aCol[nCol++] = z;
118900     }
118901   }
118902 
118903   /* If a content=xxx option was specified, the following:
118904   **
118905   **   1. Ignore any compress= and uncompress= options.
118906   **
118907   **   2. If no column names were specified as part of the CREATE VIRTUAL
118908   **      TABLE statement, use all columns from the content table.
118909   */
118910   if( rc==SQLITE_OK && zContent ){
118911     sqlite3_free(zCompress);
118912     sqlite3_free(zUncompress);
118913     zCompress = 0;
118914     zUncompress = 0;
118915     if( nCol==0 ){
118916       sqlite3_free((void*)aCol);
118917       aCol = 0;
118918       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
118919 
118920       /* If a languageid= option was specified, remove the language id
118921       ** column from the aCol[] array. */
118922       if( rc==SQLITE_OK && zLanguageid ){
118923         int j;
118924         for(j=0; j<nCol; j++){
118925           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
118926             int k;
118927             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
118928             nCol--;
118929             break;
118930           }
118931         }
118932       }
118933     }
118934   }
118935   if( rc!=SQLITE_OK ) goto fts3_init_out;
118936 
118937   if( nCol==0 ){
118938     assert( nString==0 );
118939     aCol[0] = "content";
118940     nString = 8;
118941     nCol = 1;
118942   }
118943 
118944   if( pTokenizer==0 ){
118945     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
118946     if( rc!=SQLITE_OK ) goto fts3_init_out;
118947   }
118948   assert( pTokenizer );
118949 
118950   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
118951   if( rc==SQLITE_ERROR ){
118952     assert( zPrefix );
118953     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
118954   }
118955   if( rc!=SQLITE_OK ) goto fts3_init_out;
118956 
118957   /* Allocate and populate the Fts3Table structure. */
118958   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
118959           nCol * sizeof(char *) +              /* azColumn */
118960           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
118961           nName +                              /* zName */
118962           nDb +                                /* zDb */
118963           nString;                             /* Space for azColumn strings */
118964   p = (Fts3Table*)sqlite3_malloc(nByte);
118965   if( p==0 ){
118966     rc = SQLITE_NOMEM;
118967     goto fts3_init_out;
118968   }
118969   memset(p, 0, nByte);
118970   p->db = db;
118971   p->nColumn = nCol;
118972   p->nPendingData = 0;
118973   p->azColumn = (char **)&p[1];
118974   p->pTokenizer = pTokenizer;
118975   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
118976   p->bHasDocsize = (isFts4 && bNoDocsize==0);
118977   p->bHasStat = isFts4;
118978   p->bFts4 = isFts4;
118979   p->bDescIdx = bDescIdx;
118980   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
118981   p->zContentTbl = zContent;
118982   p->zLanguageid = zLanguageid;
118983   zContent = 0;
118984   zLanguageid = 0;
118985   TESTONLY( p->inTransaction = -1 );
118986   TESTONLY( p->mxSavepoint = -1 );
118987 
118988   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
118989   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
118990   p->nIndex = nIndex;
118991   for(i=0; i<nIndex; i++){
118992     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
118993   }
118994 
118995   /* Fill in the zName and zDb fields of the vtab structure. */
118996   zCsr = (char *)&p->aIndex[nIndex];
118997   p->zName = zCsr;
118998   memcpy(zCsr, argv[2], nName);
118999   zCsr += nName;
119000   p->zDb = zCsr;
119001   memcpy(zCsr, argv[1], nDb);
119002   zCsr += nDb;
119003 
119004   /* Fill in the azColumn array */
119005   for(iCol=0; iCol<nCol; iCol++){
119006     char *z;
119007     int n = 0;
119008     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
119009     memcpy(zCsr, z, n);
119010     zCsr[n] = '\0';
119011     sqlite3Fts3Dequote(zCsr);
119012     p->azColumn[iCol] = zCsr;
119013     zCsr += n+1;
119014     assert( zCsr <= &((char *)p)[nByte] );
119015   }
119016 
119017   if( (zCompress==0)!=(zUncompress==0) ){
119018     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
119019     rc = SQLITE_ERROR;
119020     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
119021   }
119022   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
119023   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
119024   if( rc!=SQLITE_OK ) goto fts3_init_out;
119025 
119026   /* If this is an xCreate call, create the underlying tables in the
119027   ** database. TODO: For xConnect(), it could verify that said tables exist.
119028   */
119029   if( isCreate ){
119030     rc = fts3CreateTables(p);
119031   }
119032 
119033   /* Check to see if a legacy fts3 table has been "upgraded" by the
119034   ** addition of a %_stat table so that it can use incremental merge.
119035   */
119036   if( !isFts4 && !isCreate ){
119037     int rc2 = SQLITE_OK;
119038     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
119039                p->zDb, p->zName);
119040     if( rc2==SQLITE_OK ) p->bHasStat = 1;
119041   }
119042 
119043   /* Figure out the page-size for the database. This is required in order to
119044   ** estimate the cost of loading large doclists from the database.  */
119045   fts3DatabasePageSize(&rc, p);
119046   p->nNodeSize = p->nPgsz-35;
119047 
119048   /* Declare the table schema to SQLite. */
119049   fts3DeclareVtab(&rc, p);
119050 
119051 fts3_init_out:
119052   sqlite3_free(zPrefix);
119053   sqlite3_free(aIndex);
119054   sqlite3_free(zCompress);
119055   sqlite3_free(zUncompress);
119056   sqlite3_free(zContent);
119057   sqlite3_free(zLanguageid);
119058   sqlite3_free((void *)aCol);
119059   if( rc!=SQLITE_OK ){
119060     if( p ){
119061       fts3DisconnectMethod((sqlite3_vtab *)p);
119062     }else if( pTokenizer ){
119063       pTokenizer->pModule->xDestroy(pTokenizer);
119064     }
119065   }else{
119066     assert( p->pSegments==0 );
119067     *ppVTab = &p->base;
119068   }
119069   return rc;
119070 }
119071 
119072 /*
119073 ** The xConnect() and xCreate() methods for the virtual table. All the
119074 ** work is done in function fts3InitVtab().
119075 */
119076 static int fts3ConnectMethod(
119077   sqlite3 *db,                    /* Database connection */
119078   void *pAux,                     /* Pointer to tokenizer hash table */
119079   int argc,                       /* Number of elements in argv array */
119080   const char * const *argv,       /* xCreate/xConnect argument array */
119081   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119082   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119083 ){
119084   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
119085 }
119086 static int fts3CreateMethod(
119087   sqlite3 *db,                    /* Database connection */
119088   void *pAux,                     /* Pointer to tokenizer hash table */
119089   int argc,                       /* Number of elements in argv array */
119090   const char * const *argv,       /* xCreate/xConnect argument array */
119091   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119092   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119093 ){
119094   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
119095 }
119096 
119097 /*
119098 ** Implementation of the xBestIndex method for FTS3 tables. There
119099 ** are three possible strategies, in order of preference:
119100 **
119101 **   1. Direct lookup by rowid or docid.
119102 **   2. Full-text search using a MATCH operator on a non-docid column.
119103 **   3. Linear scan of %_content table.
119104 */
119105 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
119106   Fts3Table *p = (Fts3Table *)pVTab;
119107   int i;                          /* Iterator variable */
119108   int iCons = -1;                 /* Index of constraint to use */
119109   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
119110 
119111   /* By default use a full table scan. This is an expensive option,
119112   ** so search through the constraints to see if a more efficient
119113   ** strategy is possible.
119114   */
119115   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
119116   pInfo->estimatedCost = 500000;
119117   for(i=0; i<pInfo->nConstraint; i++){
119118     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
119119     if( pCons->usable==0 ) continue;
119120 
119121     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
119122     if( iCons<0
119123      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
119124      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
119125     ){
119126       pInfo->idxNum = FTS3_DOCID_SEARCH;
119127       pInfo->estimatedCost = 1.0;
119128       iCons = i;
119129     }
119130 
119131     /* A MATCH constraint. Use a full-text search.
119132     **
119133     ** If there is more than one MATCH constraint available, use the first
119134     ** one encountered. If there is both a MATCH constraint and a direct
119135     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
119136     ** though the rowid/docid lookup is faster than a MATCH query, selecting
119137     ** it would lead to an "unable to use function MATCH in the requested
119138     ** context" error.
119139     */
119140     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
119141      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
119142     ){
119143       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
119144       pInfo->estimatedCost = 2.0;
119145       iCons = i;
119146     }
119147 
119148     /* Equality constraint on the langid column */
119149     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
119150      && pCons->iColumn==p->nColumn + 2
119151     ){
119152       iLangidCons = i;
119153     }
119154   }
119155 
119156   if( iCons>=0 ){
119157     pInfo->aConstraintUsage[iCons].argvIndex = 1;
119158     pInfo->aConstraintUsage[iCons].omit = 1;
119159   }
119160   if( iLangidCons>=0 ){
119161     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
119162   }
119163 
119164   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
119165   ** docid) order. Both ascending and descending are possible.
119166   */
119167   if( pInfo->nOrderBy==1 ){
119168     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
119169     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
119170       if( pOrder->desc ){
119171         pInfo->idxStr = "DESC";
119172       }else{
119173         pInfo->idxStr = "ASC";
119174       }
119175       pInfo->orderByConsumed = 1;
119176     }
119177   }
119178 
119179   assert( p->pSegments==0 );
119180   return SQLITE_OK;
119181 }
119182 
119183 /*
119184 ** Implementation of xOpen method.
119185 */
119186 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
119187   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
119188 
119189   UNUSED_PARAMETER(pVTab);
119190 
119191   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
119192   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
119193   ** if the allocation fails, return SQLITE_NOMEM.
119194   */
119195   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
119196   if( !pCsr ){
119197     return SQLITE_NOMEM;
119198   }
119199   memset(pCsr, 0, sizeof(Fts3Cursor));
119200   return SQLITE_OK;
119201 }
119202 
119203 /*
119204 ** Close the cursor.  For additional information see the documentation
119205 ** on the xClose method of the virtual table interface.
119206 */
119207 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
119208   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119209   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119210   sqlite3_finalize(pCsr->pStmt);
119211   sqlite3Fts3ExprFree(pCsr->pExpr);
119212   sqlite3Fts3FreeDeferredTokens(pCsr);
119213   sqlite3_free(pCsr->aDoclist);
119214   sqlite3_free(pCsr->aMatchinfo);
119215   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119216   sqlite3_free(pCsr);
119217   return SQLITE_OK;
119218 }
119219 
119220 /*
119221 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
119222 ** compose and prepare an SQL statement of the form:
119223 **
119224 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
119225 **
119226 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
119227 ** it. If an error occurs, return an SQLite error code.
119228 **
119229 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
119230 */
119231 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
119232   int rc = SQLITE_OK;
119233   if( pCsr->pStmt==0 ){
119234     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
119235     char *zSql;
119236     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
119237     if( !zSql ) return SQLITE_NOMEM;
119238     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
119239     sqlite3_free(zSql);
119240   }
119241   *ppStmt = pCsr->pStmt;
119242   return rc;
119243 }
119244 
119245 /*
119246 ** Position the pCsr->pStmt statement so that it is on the row
119247 ** of the %_content table that contains the last match.  Return
119248 ** SQLITE_OK on success.
119249 */
119250 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
119251   int rc = SQLITE_OK;
119252   if( pCsr->isRequireSeek ){
119253     sqlite3_stmt *pStmt = 0;
119254 
119255     rc = fts3CursorSeekStmt(pCsr, &pStmt);
119256     if( rc==SQLITE_OK ){
119257       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
119258       pCsr->isRequireSeek = 0;
119259       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
119260         return SQLITE_OK;
119261       }else{
119262         rc = sqlite3_reset(pCsr->pStmt);
119263         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
119264           /* If no row was found and no error has occurred, then the %_content
119265           ** table is missing a row that is present in the full-text index.
119266           ** The data structures are corrupt.  */
119267           rc = FTS_CORRUPT_VTAB;
119268           pCsr->isEof = 1;
119269         }
119270       }
119271     }
119272   }
119273 
119274   if( rc!=SQLITE_OK && pContext ){
119275     sqlite3_result_error_code(pContext, rc);
119276   }
119277   return rc;
119278 }
119279 
119280 /*
119281 ** This function is used to process a single interior node when searching
119282 ** a b-tree for a term or term prefix. The node data is passed to this
119283 ** function via the zNode/nNode parameters. The term to search for is
119284 ** passed in zTerm/nTerm.
119285 **
119286 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
119287 ** of the child node that heads the sub-tree that may contain the term.
119288 **
119289 ** If piLast is not NULL, then *piLast is set to the right-most child node
119290 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
119291 ** a prefix.
119292 **
119293 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
119294 */
119295 static int fts3ScanInteriorNode(
119296   const char *zTerm,              /* Term to select leaves for */
119297   int nTerm,                      /* Size of term zTerm in bytes */
119298   const char *zNode,              /* Buffer containing segment interior node */
119299   int nNode,                      /* Size of buffer at zNode */
119300   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
119301   sqlite3_int64 *piLast           /* OUT: Selected child node */
119302 ){
119303   int rc = SQLITE_OK;             /* Return code */
119304   const char *zCsr = zNode;       /* Cursor to iterate through node */
119305   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
119306   char *zBuffer = 0;              /* Buffer to load terms into */
119307   int nAlloc = 0;                 /* Size of allocated buffer */
119308   int isFirstTerm = 1;            /* True when processing first term on page */
119309   sqlite3_int64 iChild;           /* Block id of child node to descend to */
119310 
119311   /* Skip over the 'height' varint that occurs at the start of every
119312   ** interior node. Then load the blockid of the left-child of the b-tree
119313   ** node into variable iChild.
119314   **
119315   ** Even if the data structure on disk is corrupted, this (reading two
119316   ** varints from the buffer) does not risk an overread. If zNode is a
119317   ** root node, then the buffer comes from a SELECT statement. SQLite does
119318   ** not make this guarantee explicitly, but in practice there are always
119319   ** either more than 20 bytes of allocated space following the nNode bytes of
119320   ** contents, or two zero bytes. Or, if the node is read from the %_segments
119321   ** table, then there are always 20 bytes of zeroed padding following the
119322   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
119323   */
119324   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
119325   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
119326   if( zCsr>zEnd ){
119327     return FTS_CORRUPT_VTAB;
119328   }
119329 
119330   while( zCsr<zEnd && (piFirst || piLast) ){
119331     int cmp;                      /* memcmp() result */
119332     int nSuffix;                  /* Size of term suffix */
119333     int nPrefix = 0;              /* Size of term prefix */
119334     int nBuffer;                  /* Total term size */
119335 
119336     /* Load the next term on the node into zBuffer. Use realloc() to expand
119337     ** the size of zBuffer if required.  */
119338     if( !isFirstTerm ){
119339       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
119340     }
119341     isFirstTerm = 0;
119342     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
119343 
119344     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
119345       rc = FTS_CORRUPT_VTAB;
119346       goto finish_scan;
119347     }
119348     if( nPrefix+nSuffix>nAlloc ){
119349       char *zNew;
119350       nAlloc = (nPrefix+nSuffix) * 2;
119351       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
119352       if( !zNew ){
119353         rc = SQLITE_NOMEM;
119354         goto finish_scan;
119355       }
119356       zBuffer = zNew;
119357     }
119358     assert( zBuffer );
119359     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
119360     nBuffer = nPrefix + nSuffix;
119361     zCsr += nSuffix;
119362 
119363     /* Compare the term we are searching for with the term just loaded from
119364     ** the interior node. If the specified term is greater than or equal
119365     ** to the term from the interior node, then all terms on the sub-tree
119366     ** headed by node iChild are smaller than zTerm. No need to search
119367     ** iChild.
119368     **
119369     ** If the interior node term is larger than the specified term, then
119370     ** the tree headed by iChild may contain the specified term.
119371     */
119372     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
119373     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
119374       *piFirst = iChild;
119375       piFirst = 0;
119376     }
119377 
119378     if( piLast && cmp<0 ){
119379       *piLast = iChild;
119380       piLast = 0;
119381     }
119382 
119383     iChild++;
119384   };
119385 
119386   if( piFirst ) *piFirst = iChild;
119387   if( piLast ) *piLast = iChild;
119388 
119389  finish_scan:
119390   sqlite3_free(zBuffer);
119391   return rc;
119392 }
119393 
119394 
119395 /*
119396 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
119397 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
119398 ** contains a term. This function searches the sub-tree headed by the zNode
119399 ** node for the range of leaf nodes that may contain the specified term
119400 ** or terms for which the specified term is a prefix.
119401 **
119402 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
119403 ** left-most leaf node in the tree that may contain the specified term.
119404 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
119405 ** right-most leaf node that may contain a term for which the specified
119406 ** term is a prefix.
119407 **
119408 ** It is possible that the range of returned leaf nodes does not contain
119409 ** the specified term or any terms for which it is a prefix. However, if the
119410 ** segment does contain any such terms, they are stored within the identified
119411 ** range. Because this function only inspects interior segment nodes (and
119412 ** never loads leaf nodes into memory), it is not possible to be sure.
119413 **
119414 ** If an error occurs, an error code other than SQLITE_OK is returned.
119415 */
119416 static int fts3SelectLeaf(
119417   Fts3Table *p,                   /* Virtual table handle */
119418   const char *zTerm,              /* Term to select leaves for */
119419   int nTerm,                      /* Size of term zTerm in bytes */
119420   const char *zNode,              /* Buffer containing segment interior node */
119421   int nNode,                      /* Size of buffer at zNode */
119422   sqlite3_int64 *piLeaf,          /* Selected leaf node */
119423   sqlite3_int64 *piLeaf2          /* Selected leaf node */
119424 ){
119425   int rc;                         /* Return code */
119426   int iHeight;                    /* Height of this node in tree */
119427 
119428   assert( piLeaf || piLeaf2 );
119429 
119430   sqlite3Fts3GetVarint32(zNode, &iHeight);
119431   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
119432   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
119433 
119434   if( rc==SQLITE_OK && iHeight>1 ){
119435     char *zBlob = 0;              /* Blob read from %_segments table */
119436     int nBlob;                    /* Size of zBlob in bytes */
119437 
119438     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
119439       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
119440       if( rc==SQLITE_OK ){
119441         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
119442       }
119443       sqlite3_free(zBlob);
119444       piLeaf = 0;
119445       zBlob = 0;
119446     }
119447 
119448     if( rc==SQLITE_OK ){
119449       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
119450     }
119451     if( rc==SQLITE_OK ){
119452       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
119453     }
119454     sqlite3_free(zBlob);
119455   }
119456 
119457   return rc;
119458 }
119459 
119460 /*
119461 ** This function is used to create delta-encoded serialized lists of FTS3
119462 ** varints. Each call to this function appends a single varint to a list.
119463 */
119464 static void fts3PutDeltaVarint(
119465   char **pp,                      /* IN/OUT: Output pointer */
119466   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
119467   sqlite3_int64 iVal              /* Write this value to the list */
119468 ){
119469   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
119470   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
119471   *piPrev = iVal;
119472 }
119473 
119474 /*
119475 ** When this function is called, *ppPoslist is assumed to point to the
119476 ** start of a position-list. After it returns, *ppPoslist points to the
119477 ** first byte after the position-list.
119478 **
119479 ** A position list is list of positions (delta encoded) and columns for
119480 ** a single document record of a doclist.  So, in other words, this
119481 ** routine advances *ppPoslist so that it points to the next docid in
119482 ** the doclist, or to the first byte past the end of the doclist.
119483 **
119484 ** If pp is not NULL, then the contents of the position list are copied
119485 ** to *pp. *pp is set to point to the first byte past the last byte copied
119486 ** before this function returns.
119487 */
119488 static void fts3PoslistCopy(char **pp, char **ppPoslist){
119489   char *pEnd = *ppPoslist;
119490   char c = 0;
119491 
119492   /* The end of a position list is marked by a zero encoded as an FTS3
119493   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
119494   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
119495   ** of some other, multi-byte, value.
119496   **
119497   ** The following while-loop moves pEnd to point to the first byte that is not
119498   ** immediately preceded by a byte with the 0x80 bit set. Then increments
119499   ** pEnd once more so that it points to the byte immediately following the
119500   ** last byte in the position-list.
119501   */
119502   while( *pEnd | c ){
119503     c = *pEnd++ & 0x80;
119504     testcase( c!=0 && (*pEnd)==0 );
119505   }
119506   pEnd++;  /* Advance past the POS_END terminator byte */
119507 
119508   if( pp ){
119509     int n = (int)(pEnd - *ppPoslist);
119510     char *p = *pp;
119511     memcpy(p, *ppPoslist, n);
119512     p += n;
119513     *pp = p;
119514   }
119515   *ppPoslist = pEnd;
119516 }
119517 
119518 /*
119519 ** When this function is called, *ppPoslist is assumed to point to the
119520 ** start of a column-list. After it returns, *ppPoslist points to the
119521 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
119522 **
119523 ** A column-list is list of delta-encoded positions for a single column
119524 ** within a single document within a doclist.
119525 **
119526 ** The column-list is terminated either by a POS_COLUMN varint (1) or
119527 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
119528 ** the POS_COLUMN or POS_END that terminates the column-list.
119529 **
119530 ** If pp is not NULL, then the contents of the column-list are copied
119531 ** to *pp. *pp is set to point to the first byte past the last byte copied
119532 ** before this function returns.  The POS_COLUMN or POS_END terminator
119533 ** is not copied into *pp.
119534 */
119535 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
119536   char *pEnd = *ppPoslist;
119537   char c = 0;
119538 
119539   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
119540   ** not part of a multi-byte varint.
119541   */
119542   while( 0xFE & (*pEnd | c) ){
119543     c = *pEnd++ & 0x80;
119544     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
119545   }
119546   if( pp ){
119547     int n = (int)(pEnd - *ppPoslist);
119548     char *p = *pp;
119549     memcpy(p, *ppPoslist, n);
119550     p += n;
119551     *pp = p;
119552   }
119553   *ppPoslist = pEnd;
119554 }
119555 
119556 /*
119557 ** Value used to signify the end of an position-list. This is safe because
119558 ** it is not possible to have a document with 2^31 terms.
119559 */
119560 #define POSITION_LIST_END 0x7fffffff
119561 
119562 /*
119563 ** This function is used to help parse position-lists. When this function is
119564 ** called, *pp may point to the start of the next varint in the position-list
119565 ** being parsed, or it may point to 1 byte past the end of the position-list
119566 ** (in which case **pp will be a terminator bytes POS_END (0) or
119567 ** (1)).
119568 **
119569 ** If *pp points past the end of the current position-list, set *pi to
119570 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
119571 ** increment the current value of *pi by the value read, and set *pp to
119572 ** point to the next value before returning.
119573 **
119574 ** Before calling this routine *pi must be initialized to the value of
119575 ** the previous position, or zero if we are reading the first position
119576 ** in the position-list.  Because positions are delta-encoded, the value
119577 ** of the previous position is needed in order to compute the value of
119578 ** the next position.
119579 */
119580 static void fts3ReadNextPos(
119581   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
119582   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
119583 ){
119584   if( (**pp)&0xFE ){
119585     fts3GetDeltaVarint(pp, pi);
119586     *pi -= 2;
119587   }else{
119588     *pi = POSITION_LIST_END;
119589   }
119590 }
119591 
119592 /*
119593 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
119594 ** the value of iCol encoded as a varint to *pp.   This will start a new
119595 ** column list.
119596 **
119597 ** Set *pp to point to the byte just after the last byte written before
119598 ** returning (do not modify it if iCol==0). Return the total number of bytes
119599 ** written (0 if iCol==0).
119600 */
119601 static int fts3PutColNumber(char **pp, int iCol){
119602   int n = 0;                      /* Number of bytes written */
119603   if( iCol ){
119604     char *p = *pp;                /* Output pointer */
119605     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
119606     *p = 0x01;
119607     *pp = &p[n];
119608   }
119609   return n;
119610 }
119611 
119612 /*
119613 ** Compute the union of two position lists.  The output written
119614 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
119615 ** order and with any duplicates removed.  All pointers are
119616 ** updated appropriately.   The caller is responsible for insuring
119617 ** that there is enough space in *pp to hold the complete output.
119618 */
119619 static void fts3PoslistMerge(
119620   char **pp,                      /* Output buffer */
119621   char **pp1,                     /* Left input list */
119622   char **pp2                      /* Right input list */
119623 ){
119624   char *p = *pp;
119625   char *p1 = *pp1;
119626   char *p2 = *pp2;
119627 
119628   while( *p1 || *p2 ){
119629     int iCol1;         /* The current column index in pp1 */
119630     int iCol2;         /* The current column index in pp2 */
119631 
119632     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
119633     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
119634     else iCol1 = 0;
119635 
119636     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
119637     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
119638     else iCol2 = 0;
119639 
119640     if( iCol1==iCol2 ){
119641       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
119642       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
119643       sqlite3_int64 iPrev = 0;
119644       int n = fts3PutColNumber(&p, iCol1);
119645       p1 += n;
119646       p2 += n;
119647 
119648       /* At this point, both p1 and p2 point to the start of column-lists
119649       ** for the same column (the column with index iCol1 and iCol2).
119650       ** A column-list is a list of non-negative delta-encoded varints, each
119651       ** incremented by 2 before being stored. Each list is terminated by a
119652       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
119653       ** and writes the results to buffer p. p is left pointing to the byte
119654       ** after the list written. No terminator (POS_END or POS_COLUMN) is
119655       ** written to the output.
119656       */
119657       fts3GetDeltaVarint(&p1, &i1);
119658       fts3GetDeltaVarint(&p2, &i2);
119659       do {
119660         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
119661         iPrev -= 2;
119662         if( i1==i2 ){
119663           fts3ReadNextPos(&p1, &i1);
119664           fts3ReadNextPos(&p2, &i2);
119665         }else if( i1<i2 ){
119666           fts3ReadNextPos(&p1, &i1);
119667         }else{
119668           fts3ReadNextPos(&p2, &i2);
119669         }
119670       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
119671     }else if( iCol1<iCol2 ){
119672       p1 += fts3PutColNumber(&p, iCol1);
119673       fts3ColumnlistCopy(&p, &p1);
119674     }else{
119675       p2 += fts3PutColNumber(&p, iCol2);
119676       fts3ColumnlistCopy(&p, &p2);
119677     }
119678   }
119679 
119680   *p++ = POS_END;
119681   *pp = p;
119682   *pp1 = p1 + 1;
119683   *pp2 = p2 + 1;
119684 }
119685 
119686 /*
119687 ** This function is used to merge two position lists into one. When it is
119688 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
119689 ** the part of a doclist that follows each document id. For example, if a row
119690 ** contains:
119691 **
119692 **     'a b c'|'x y z'|'a b b a'
119693 **
119694 ** Then the position list for this row for token 'b' would consist of:
119695 **
119696 **     0x02 0x01 0x02 0x03 0x03 0x00
119697 **
119698 ** When this function returns, both *pp1 and *pp2 are left pointing to the
119699 ** byte following the 0x00 terminator of their respective position lists.
119700 **
119701 ** If isSaveLeft is 0, an entry is added to the output position list for
119702 ** each position in *pp2 for which there exists one or more positions in
119703 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
119704 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
119705 ** slots before it.
119706 **
119707 ** e.g. nToken==1 searches for adjacent positions.
119708 */
119709 static int fts3PoslistPhraseMerge(
119710   char **pp,                      /* IN/OUT: Preallocated output buffer */
119711   int nToken,                     /* Maximum difference in token positions */
119712   int isSaveLeft,                 /* Save the left position */
119713   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
119714   char **pp1,                     /* IN/OUT: Left input list */
119715   char **pp2                      /* IN/OUT: Right input list */
119716 ){
119717   char *p = *pp;
119718   char *p1 = *pp1;
119719   char *p2 = *pp2;
119720   int iCol1 = 0;
119721   int iCol2 = 0;
119722 
119723   /* Never set both isSaveLeft and isExact for the same invocation. */
119724   assert( isSaveLeft==0 || isExact==0 );
119725 
119726   assert( p!=0 && *p1!=0 && *p2!=0 );
119727   if( *p1==POS_COLUMN ){
119728     p1++;
119729     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119730   }
119731   if( *p2==POS_COLUMN ){
119732     p2++;
119733     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119734   }
119735 
119736   while( 1 ){
119737     if( iCol1==iCol2 ){
119738       char *pSave = p;
119739       sqlite3_int64 iPrev = 0;
119740       sqlite3_int64 iPos1 = 0;
119741       sqlite3_int64 iPos2 = 0;
119742 
119743       if( iCol1 ){
119744         *p++ = POS_COLUMN;
119745         p += sqlite3Fts3PutVarint(p, iCol1);
119746       }
119747 
119748       assert( *p1!=POS_END && *p1!=POS_COLUMN );
119749       assert( *p2!=POS_END && *p2!=POS_COLUMN );
119750       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119751       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119752 
119753       while( 1 ){
119754         if( iPos2==iPos1+nToken
119755          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
119756         ){
119757           sqlite3_int64 iSave;
119758           iSave = isSaveLeft ? iPos1 : iPos2;
119759           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
119760           pSave = 0;
119761           assert( p );
119762         }
119763         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
119764           if( (*p2&0xFE)==0 ) break;
119765           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
119766         }else{
119767           if( (*p1&0xFE)==0 ) break;
119768           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
119769         }
119770       }
119771 
119772       if( pSave ){
119773         assert( pp && p );
119774         p = pSave;
119775       }
119776 
119777       fts3ColumnlistCopy(0, &p1);
119778       fts3ColumnlistCopy(0, &p2);
119779       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
119780       if( 0==*p1 || 0==*p2 ) break;
119781 
119782       p1++;
119783       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119784       p2++;
119785       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119786     }
119787 
119788     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
119789     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
119790     ** end of the position list, or the 0x01 that precedes the next
119791     ** column-number in the position list.
119792     */
119793     else if( iCol1<iCol2 ){
119794       fts3ColumnlistCopy(0, &p1);
119795       if( 0==*p1 ) break;
119796       p1++;
119797       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
119798     }else{
119799       fts3ColumnlistCopy(0, &p2);
119800       if( 0==*p2 ) break;
119801       p2++;
119802       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
119803     }
119804   }
119805 
119806   fts3PoslistCopy(0, &p2);
119807   fts3PoslistCopy(0, &p1);
119808   *pp1 = p1;
119809   *pp2 = p2;
119810   if( *pp==p ){
119811     return 0;
119812   }
119813   *p++ = 0x00;
119814   *pp = p;
119815   return 1;
119816 }
119817 
119818 /*
119819 ** Merge two position-lists as required by the NEAR operator. The argument
119820 ** position lists correspond to the left and right phrases of an expression
119821 ** like:
119822 **
119823 **     "phrase 1" NEAR "phrase number 2"
119824 **
119825 ** Position list *pp1 corresponds to the left-hand side of the NEAR
119826 ** expression and *pp2 to the right. As usual, the indexes in the position
119827 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
119828 ** in the example above).
119829 **
119830 ** The output position list - written to *pp - is a copy of *pp2 with those
119831 ** entries that are not sufficiently NEAR entries in *pp1 removed.
119832 */
119833 static int fts3PoslistNearMerge(
119834   char **pp,                      /* Output buffer */
119835   char *aTmp,                     /* Temporary buffer space */
119836   int nRight,                     /* Maximum difference in token positions */
119837   int nLeft,                      /* Maximum difference in token positions */
119838   char **pp1,                     /* IN/OUT: Left input list */
119839   char **pp2                      /* IN/OUT: Right input list */
119840 ){
119841   char *p1 = *pp1;
119842   char *p2 = *pp2;
119843 
119844   char *pTmp1 = aTmp;
119845   char *pTmp2;
119846   char *aTmp2;
119847   int res = 1;
119848 
119849   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
119850   aTmp2 = pTmp2 = pTmp1;
119851   *pp1 = p1;
119852   *pp2 = p2;
119853   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
119854   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
119855     fts3PoslistMerge(pp, &aTmp, &aTmp2);
119856   }else if( pTmp1!=aTmp ){
119857     fts3PoslistCopy(pp, &aTmp);
119858   }else if( pTmp2!=aTmp2 ){
119859     fts3PoslistCopy(pp, &aTmp2);
119860   }else{
119861     res = 0;
119862   }
119863 
119864   return res;
119865 }
119866 
119867 /*
119868 ** An instance of this function is used to merge together the (potentially
119869 ** large number of) doclists for each term that matches a prefix query.
119870 ** See function fts3TermSelectMerge() for details.
119871 */
119872 typedef struct TermSelect TermSelect;
119873 struct TermSelect {
119874   char *aaOutput[16];             /* Malloc'd output buffers */
119875   int anOutput[16];               /* Size each output buffer in bytes */
119876 };
119877 
119878 /*
119879 ** This function is used to read a single varint from a buffer. Parameter
119880 ** pEnd points 1 byte past the end of the buffer. When this function is
119881 ** called, if *pp points to pEnd or greater, then the end of the buffer
119882 ** has been reached. In this case *pp is set to 0 and the function returns.
119883 **
119884 ** If *pp does not point to or past pEnd, then a single varint is read
119885 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
119886 **
119887 ** If bDescIdx is false, the value read is added to *pVal before returning.
119888 ** If it is true, the value read is subtracted from *pVal before this
119889 ** function returns.
119890 */
119891 static void fts3GetDeltaVarint3(
119892   char **pp,                      /* IN/OUT: Point to read varint from */
119893   char *pEnd,                     /* End of buffer */
119894   int bDescIdx,                   /* True if docids are descending */
119895   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
119896 ){
119897   if( *pp>=pEnd ){
119898     *pp = 0;
119899   }else{
119900     sqlite3_int64 iVal;
119901     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
119902     if( bDescIdx ){
119903       *pVal -= iVal;
119904     }else{
119905       *pVal += iVal;
119906     }
119907   }
119908 }
119909 
119910 /*
119911 ** This function is used to write a single varint to a buffer. The varint
119912 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
119913 ** end of the value written.
119914 **
119915 ** If *pbFirst is zero when this function is called, the value written to
119916 ** the buffer is that of parameter iVal.
119917 **
119918 ** If *pbFirst is non-zero when this function is called, then the value
119919 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
119920 ** (if bDescIdx is non-zero).
119921 **
119922 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
119923 ** to the value of parameter iVal.
119924 */
119925 static void fts3PutDeltaVarint3(
119926   char **pp,                      /* IN/OUT: Output pointer */
119927   int bDescIdx,                   /* True for descending docids */
119928   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
119929   int *pbFirst,                   /* IN/OUT: True after first int written */
119930   sqlite3_int64 iVal              /* Write this value to the list */
119931 ){
119932   sqlite3_int64 iWrite;
119933   if( bDescIdx==0 || *pbFirst==0 ){
119934     iWrite = iVal - *piPrev;
119935   }else{
119936     iWrite = *piPrev - iVal;
119937   }
119938   assert( *pbFirst || *piPrev==0 );
119939   assert( *pbFirst==0 || iWrite>0 );
119940   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
119941   *piPrev = iVal;
119942   *pbFirst = 1;
119943 }
119944 
119945 
119946 /*
119947 ** This macro is used by various functions that merge doclists. The two
119948 ** arguments are 64-bit docid values. If the value of the stack variable
119949 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
119950 ** Otherwise, (i2-i1).
119951 **
119952 ** Using this makes it easier to write code that can merge doclists that are
119953 ** sorted in either ascending or descending order.
119954 */
119955 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
119956 
119957 /*
119958 ** This function does an "OR" merge of two doclists (output contains all
119959 ** positions contained in either argument doclist). If the docids in the
119960 ** input doclists are sorted in ascending order, parameter bDescDoclist
119961 ** should be false. If they are sorted in ascending order, it should be
119962 ** passed a non-zero value.
119963 **
119964 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
119965 ** containing the output doclist and SQLITE_OK is returned. In this case
119966 ** *pnOut is set to the number of bytes in the output doclist.
119967 **
119968 ** If an error occurs, an SQLite error code is returned. The output values
119969 ** are undefined in this case.
119970 */
119971 static int fts3DoclistOrMerge(
119972   int bDescDoclist,               /* True if arguments are desc */
119973   char *a1, int n1,               /* First doclist */
119974   char *a2, int n2,               /* Second doclist */
119975   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
119976 ){
119977   sqlite3_int64 i1 = 0;
119978   sqlite3_int64 i2 = 0;
119979   sqlite3_int64 iPrev = 0;
119980   char *pEnd1 = &a1[n1];
119981   char *pEnd2 = &a2[n2];
119982   char *p1 = a1;
119983   char *p2 = a2;
119984   char *p;
119985   char *aOut;
119986   int bFirstOut = 0;
119987 
119988   *paOut = 0;
119989   *pnOut = 0;
119990 
119991   /* Allocate space for the output. Both the input and output doclists
119992   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
119993   ** then the first docid in each list is simply encoded as a varint. For
119994   ** each subsequent docid, the varint stored is the difference between the
119995   ** current and previous docid (a positive number - since the list is in
119996   ** ascending order).
119997   **
119998   ** The first docid written to the output is therefore encoded using the
119999   ** same number of bytes as it is in whichever of the input lists it is
120000   ** read from. And each subsequent docid read from the same input list
120001   ** consumes either the same or less bytes as it did in the input (since
120002   ** the difference between it and the previous value in the output must
120003   ** be a positive value less than or equal to the delta value read from
120004   ** the input list). The same argument applies to all but the first docid
120005   ** read from the 'other' list. And to the contents of all position lists
120006   ** that will be copied and merged from the input to the output.
120007   **
120008   ** However, if the first docid copied to the output is a negative number,
120009   ** then the encoding of the first docid from the 'other' input list may
120010   ** be larger in the output than it was in the input (since the delta value
120011   ** may be a larger positive integer than the actual docid).
120012   **
120013   ** The space required to store the output is therefore the sum of the
120014   ** sizes of the two inputs, plus enough space for exactly one of the input
120015   ** docids to grow.
120016   **
120017   ** A symetric argument may be made if the doclists are in descending
120018   ** order.
120019   */
120020   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
120021   if( !aOut ) return SQLITE_NOMEM;
120022 
120023   p = aOut;
120024   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
120025   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
120026   while( p1 || p2 ){
120027     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
120028 
120029     if( p2 && p1 && iDiff==0 ){
120030       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120031       fts3PoslistMerge(&p, &p1, &p2);
120032       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120033       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120034     }else if( !p2 || (p1 && iDiff<0) ){
120035       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120036       fts3PoslistCopy(&p, &p1);
120037       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120038     }else{
120039       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
120040       fts3PoslistCopy(&p, &p2);
120041       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120042     }
120043   }
120044 
120045   *paOut = aOut;
120046   *pnOut = (int)(p-aOut);
120047   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
120048   return SQLITE_OK;
120049 }
120050 
120051 /*
120052 ** This function does a "phrase" merge of two doclists. In a phrase merge,
120053 ** the output contains a copy of each position from the right-hand input
120054 ** doclist for which there is a position in the left-hand input doclist
120055 ** exactly nDist tokens before it.
120056 **
120057 ** If the docids in the input doclists are sorted in ascending order,
120058 ** parameter bDescDoclist should be false. If they are sorted in ascending
120059 ** order, it should be passed a non-zero value.
120060 **
120061 ** The right-hand input doclist is overwritten by this function.
120062 */
120063 static void fts3DoclistPhraseMerge(
120064   int bDescDoclist,               /* True if arguments are desc */
120065   int nDist,                      /* Distance from left to right (1=adjacent) */
120066   char *aLeft, int nLeft,         /* Left doclist */
120067   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
120068 ){
120069   sqlite3_int64 i1 = 0;
120070   sqlite3_int64 i2 = 0;
120071   sqlite3_int64 iPrev = 0;
120072   char *pEnd1 = &aLeft[nLeft];
120073   char *pEnd2 = &aRight[*pnRight];
120074   char *p1 = aLeft;
120075   char *p2 = aRight;
120076   char *p;
120077   int bFirstOut = 0;
120078   char *aOut = aRight;
120079 
120080   assert( nDist>0 );
120081 
120082   p = aOut;
120083   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
120084   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
120085 
120086   while( p1 && p2 ){
120087     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
120088     if( iDiff==0 ){
120089       char *pSave = p;
120090       sqlite3_int64 iPrevSave = iPrev;
120091       int bFirstOutSave = bFirstOut;
120092 
120093       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
120094       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
120095         p = pSave;
120096         iPrev = iPrevSave;
120097         bFirstOut = bFirstOutSave;
120098       }
120099       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120100       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120101     }else if( iDiff<0 ){
120102       fts3PoslistCopy(0, &p1);
120103       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
120104     }else{
120105       fts3PoslistCopy(0, &p2);
120106       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
120107     }
120108   }
120109 
120110   *pnRight = (int)(p - aOut);
120111 }
120112 
120113 /*
120114 ** Argument pList points to a position list nList bytes in size. This
120115 ** function checks to see if the position list contains any entries for
120116 ** a token in position 0 (of any column). If so, it writes argument iDelta
120117 ** to the output buffer pOut, followed by a position list consisting only
120118 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
120119 ** The value returned is the number of bytes written to pOut (if any).
120120 */
120121 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
120122   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
120123   char *pList,                    /* Position list (no 0x00 term) */
120124   int nList,                      /* Size of pList in bytes */
120125   char *pOut                      /* Write output here */
120126 ){
120127   int nOut = 0;
120128   int bWritten = 0;               /* True once iDelta has been written */
120129   char *p = pList;
120130   char *pEnd = &pList[nList];
120131 
120132   if( *p!=0x01 ){
120133     if( *p==0x02 ){
120134       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
120135       pOut[nOut++] = 0x02;
120136       bWritten = 1;
120137     }
120138     fts3ColumnlistCopy(0, &p);
120139   }
120140 
120141   while( p<pEnd && *p==0x01 ){
120142     sqlite3_int64 iCol;
120143     p++;
120144     p += sqlite3Fts3GetVarint(p, &iCol);
120145     if( *p==0x02 ){
120146       if( bWritten==0 ){
120147         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
120148         bWritten = 1;
120149       }
120150       pOut[nOut++] = 0x01;
120151       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
120152       pOut[nOut++] = 0x02;
120153     }
120154     fts3ColumnlistCopy(0, &p);
120155   }
120156   if( bWritten ){
120157     pOut[nOut++] = 0x00;
120158   }
120159 
120160   return nOut;
120161 }
120162 
120163 
120164 /*
120165 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
120166 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
120167 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
120168 **
120169 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
120170 ** the responsibility of the caller to free any doclists left in the
120171 ** TermSelect.aaOutput[] array.
120172 */
120173 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
120174   char *aOut = 0;
120175   int nOut = 0;
120176   int i;
120177 
120178   /* Loop through the doclists in the aaOutput[] array. Merge them all
120179   ** into a single doclist.
120180   */
120181   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
120182     if( pTS->aaOutput[i] ){
120183       if( !aOut ){
120184         aOut = pTS->aaOutput[i];
120185         nOut = pTS->anOutput[i];
120186         pTS->aaOutput[i] = 0;
120187       }else{
120188         int nNew;
120189         char *aNew;
120190 
120191         int rc = fts3DoclistOrMerge(p->bDescIdx,
120192             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
120193         );
120194         if( rc!=SQLITE_OK ){
120195           sqlite3_free(aOut);
120196           return rc;
120197         }
120198 
120199         sqlite3_free(pTS->aaOutput[i]);
120200         sqlite3_free(aOut);
120201         pTS->aaOutput[i] = 0;
120202         aOut = aNew;
120203         nOut = nNew;
120204       }
120205     }
120206   }
120207 
120208   pTS->aaOutput[0] = aOut;
120209   pTS->anOutput[0] = nOut;
120210   return SQLITE_OK;
120211 }
120212 
120213 /*
120214 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
120215 ** as the first argument. The merge is an "OR" merge (see function
120216 ** fts3DoclistOrMerge() for details).
120217 **
120218 ** This function is called with the doclist for each term that matches
120219 ** a queried prefix. It merges all these doclists into one, the doclist
120220 ** for the specified prefix. Since there can be a very large number of
120221 ** doclists to merge, the merging is done pair-wise using the TermSelect
120222 ** object.
120223 **
120224 ** This function returns SQLITE_OK if the merge is successful, or an
120225 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
120226 */
120227 static int fts3TermSelectMerge(
120228   Fts3Table *p,                   /* FTS table handle */
120229   TermSelect *pTS,                /* TermSelect object to merge into */
120230   char *aDoclist,                 /* Pointer to doclist */
120231   int nDoclist                    /* Size of aDoclist in bytes */
120232 ){
120233   if( pTS->aaOutput[0]==0 ){
120234     /* If this is the first term selected, copy the doclist to the output
120235     ** buffer using memcpy(). */
120236     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
120237     pTS->anOutput[0] = nDoclist;
120238     if( pTS->aaOutput[0] ){
120239       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
120240     }else{
120241       return SQLITE_NOMEM;
120242     }
120243   }else{
120244     char *aMerge = aDoclist;
120245     int nMerge = nDoclist;
120246     int iOut;
120247 
120248     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
120249       if( pTS->aaOutput[iOut]==0 ){
120250         assert( iOut>0 );
120251         pTS->aaOutput[iOut] = aMerge;
120252         pTS->anOutput[iOut] = nMerge;
120253         break;
120254       }else{
120255         char *aNew;
120256         int nNew;
120257 
120258         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
120259             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
120260         );
120261         if( rc!=SQLITE_OK ){
120262           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
120263           return rc;
120264         }
120265 
120266         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
120267         sqlite3_free(pTS->aaOutput[iOut]);
120268         pTS->aaOutput[iOut] = 0;
120269 
120270         aMerge = aNew;
120271         nMerge = nNew;
120272         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
120273           pTS->aaOutput[iOut] = aMerge;
120274           pTS->anOutput[iOut] = nMerge;
120275         }
120276       }
120277     }
120278   }
120279   return SQLITE_OK;
120280 }
120281 
120282 /*
120283 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
120284 */
120285 static int fts3SegReaderCursorAppend(
120286   Fts3MultiSegReader *pCsr,
120287   Fts3SegReader *pNew
120288 ){
120289   if( (pCsr->nSegment%16)==0 ){
120290     Fts3SegReader **apNew;
120291     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
120292     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
120293     if( !apNew ){
120294       sqlite3Fts3SegReaderFree(pNew);
120295       return SQLITE_NOMEM;
120296     }
120297     pCsr->apSegment = apNew;
120298   }
120299   pCsr->apSegment[pCsr->nSegment++] = pNew;
120300   return SQLITE_OK;
120301 }
120302 
120303 /*
120304 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
120305 ** 8th argument.
120306 **
120307 ** This function returns SQLITE_OK if successful, or an SQLite error code
120308 ** otherwise.
120309 */
120310 static int fts3SegReaderCursor(
120311   Fts3Table *p,                   /* FTS3 table handle */
120312   int iLangid,                    /* Language id */
120313   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
120314   int iLevel,                     /* Level of segments to scan */
120315   const char *zTerm,              /* Term to query for */
120316   int nTerm,                      /* Size of zTerm in bytes */
120317   int isPrefix,                   /* True for a prefix search */
120318   int isScan,                     /* True to scan from zTerm to EOF */
120319   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
120320 ){
120321   int rc = SQLITE_OK;             /* Error code */
120322   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
120323   int rc2;                        /* Result of sqlite3_reset() */
120324 
120325   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
120326   ** for the pending-terms. If this is a scan, then this call must be being
120327   ** made by an fts4aux module, not an FTS table. In this case calling
120328   ** Fts3SegReaderPending might segfault, as the data structures used by
120329   ** fts4aux are not completely populated. So it's easiest to filter these
120330   ** calls out here.  */
120331   if( iLevel<0 && p->aIndex ){
120332     Fts3SegReader *pSeg = 0;
120333     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
120334     if( rc==SQLITE_OK && pSeg ){
120335       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
120336     }
120337   }
120338 
120339   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
120340     if( rc==SQLITE_OK ){
120341       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
120342     }
120343 
120344     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
120345       Fts3SegReader *pSeg = 0;
120346 
120347       /* Read the values returned by the SELECT into local variables. */
120348       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
120349       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
120350       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
120351       int nRoot = sqlite3_column_bytes(pStmt, 4);
120352       char const *zRoot = sqlite3_column_blob(pStmt, 4);
120353 
120354       /* If zTerm is not NULL, and this segment is not stored entirely on its
120355       ** root node, the range of leaves scanned can be reduced. Do this. */
120356       if( iStartBlock && zTerm ){
120357         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
120358         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
120359         if( rc!=SQLITE_OK ) goto finished;
120360         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
120361       }
120362 
120363       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
120364           (isPrefix==0 && isScan==0),
120365           iStartBlock, iLeavesEndBlock,
120366           iEndBlock, zRoot, nRoot, &pSeg
120367       );
120368       if( rc!=SQLITE_OK ) goto finished;
120369       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
120370     }
120371   }
120372 
120373  finished:
120374   rc2 = sqlite3_reset(pStmt);
120375   if( rc==SQLITE_DONE ) rc = rc2;
120376 
120377   return rc;
120378 }
120379 
120380 /*
120381 ** Set up a cursor object for iterating through a full-text index or a
120382 ** single level therein.
120383 */
120384 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
120385   Fts3Table *p,                   /* FTS3 table handle */
120386   int iLangid,                    /* Language-id to search */
120387   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
120388   int iLevel,                     /* Level of segments to scan */
120389   const char *zTerm,              /* Term to query for */
120390   int nTerm,                      /* Size of zTerm in bytes */
120391   int isPrefix,                   /* True for a prefix search */
120392   int isScan,                     /* True to scan from zTerm to EOF */
120393   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
120394 ){
120395   assert( iIndex>=0 && iIndex<p->nIndex );
120396   assert( iLevel==FTS3_SEGCURSOR_ALL
120397       ||  iLevel==FTS3_SEGCURSOR_PENDING
120398       ||  iLevel>=0
120399   );
120400   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
120401   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
120402   assert( isPrefix==0 || isScan==0 );
120403 
120404   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
120405   return fts3SegReaderCursor(
120406       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
120407   );
120408 }
120409 
120410 /*
120411 ** In addition to its current configuration, have the Fts3MultiSegReader
120412 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
120413 **
120414 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120415 */
120416 static int fts3SegReaderCursorAddZero(
120417   Fts3Table *p,                   /* FTS virtual table handle */
120418   int iLangid,
120419   const char *zTerm,              /* Term to scan doclist of */
120420   int nTerm,                      /* Number of bytes in zTerm */
120421   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
120422 ){
120423   return fts3SegReaderCursor(p,
120424       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
120425   );
120426 }
120427 
120428 /*
120429 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
120430 ** if isPrefix is true, to scan the doclist for all terms for which
120431 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
120432 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
120433 ** an SQLite error code.
120434 **
120435 ** It is the responsibility of the caller to free this object by eventually
120436 ** passing it to fts3SegReaderCursorFree()
120437 **
120438 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120439 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
120440 */
120441 static int fts3TermSegReaderCursor(
120442   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
120443   const char *zTerm,              /* Term to query for */
120444   int nTerm,                      /* Size of zTerm in bytes */
120445   int isPrefix,                   /* True for a prefix search */
120446   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
120447 ){
120448   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
120449   int rc = SQLITE_NOMEM;          /* Return code */
120450 
120451   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
120452   if( pSegcsr ){
120453     int i;
120454     int bFound = 0;               /* True once an index has been found */
120455     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120456 
120457     if( isPrefix ){
120458       for(i=1; bFound==0 && i<p->nIndex; i++){
120459         if( p->aIndex[i].nPrefix==nTerm ){
120460           bFound = 1;
120461           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
120462               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
120463           );
120464           pSegcsr->bLookup = 1;
120465         }
120466       }
120467 
120468       for(i=1; bFound==0 && i<p->nIndex; i++){
120469         if( p->aIndex[i].nPrefix==nTerm+1 ){
120470           bFound = 1;
120471           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
120472               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
120473           );
120474           if( rc==SQLITE_OK ){
120475             rc = fts3SegReaderCursorAddZero(
120476                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
120477             );
120478           }
120479         }
120480       }
120481     }
120482 
120483     if( bFound==0 ){
120484       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
120485           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
120486       );
120487       pSegcsr->bLookup = !isPrefix;
120488     }
120489   }
120490 
120491   *ppSegcsr = pSegcsr;
120492   return rc;
120493 }
120494 
120495 /*
120496 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
120497 */
120498 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
120499   sqlite3Fts3SegReaderFinish(pSegcsr);
120500   sqlite3_free(pSegcsr);
120501 }
120502 
120503 /*
120504 ** This function retrieves the doclist for the specified term (or term
120505 ** prefix) from the database.
120506 */
120507 static int fts3TermSelect(
120508   Fts3Table *p,                   /* Virtual table handle */
120509   Fts3PhraseToken *pTok,          /* Token to query for */
120510   int iColumn,                    /* Column to query (or -ve for all columns) */
120511   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
120512   char **ppOut                    /* OUT: Malloced result buffer */
120513 ){
120514   int rc;                         /* Return code */
120515   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
120516   TermSelect tsc;                 /* Object for pair-wise doclist merging */
120517   Fts3SegFilter filter;           /* Segment term filter configuration */
120518 
120519   pSegcsr = pTok->pSegcsr;
120520   memset(&tsc, 0, sizeof(TermSelect));
120521 
120522   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
120523         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
120524         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
120525         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
120526   filter.iCol = iColumn;
120527   filter.zTerm = pTok->z;
120528   filter.nTerm = pTok->n;
120529 
120530   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
120531   while( SQLITE_OK==rc
120532       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
120533   ){
120534     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
120535   }
120536 
120537   if( rc==SQLITE_OK ){
120538     rc = fts3TermSelectFinishMerge(p, &tsc);
120539   }
120540   if( rc==SQLITE_OK ){
120541     *ppOut = tsc.aaOutput[0];
120542     *pnOut = tsc.anOutput[0];
120543   }else{
120544     int i;
120545     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
120546       sqlite3_free(tsc.aaOutput[i]);
120547     }
120548   }
120549 
120550   fts3SegReaderCursorFree(pSegcsr);
120551   pTok->pSegcsr = 0;
120552   return rc;
120553 }
120554 
120555 /*
120556 ** This function counts the total number of docids in the doclist stored
120557 ** in buffer aList[], size nList bytes.
120558 **
120559 ** If the isPoslist argument is true, then it is assumed that the doclist
120560 ** contains a position-list following each docid. Otherwise, it is assumed
120561 ** that the doclist is simply a list of docids stored as delta encoded
120562 ** varints.
120563 */
120564 static int fts3DoclistCountDocids(char *aList, int nList){
120565   int nDoc = 0;                   /* Return value */
120566   if( aList ){
120567     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
120568     char *p = aList;              /* Cursor */
120569     while( p<aEnd ){
120570       nDoc++;
120571       while( (*p++)&0x80 );     /* Skip docid varint */
120572       fts3PoslistCopy(0, &p);   /* Skip over position list */
120573     }
120574   }
120575 
120576   return nDoc;
120577 }
120578 
120579 /*
120580 ** Advance the cursor to the next row in the %_content table that
120581 ** matches the search criteria.  For a MATCH search, this will be
120582 ** the next row that matches. For a full-table scan, this will be
120583 ** simply the next row in the %_content table.  For a docid lookup,
120584 ** this routine simply sets the EOF flag.
120585 **
120586 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
120587 ** even if we reach end-of-file.  The fts3EofMethod() will be called
120588 ** subsequently to determine whether or not an EOF was hit.
120589 */
120590 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
120591   int rc;
120592   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120593   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
120594     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
120595       pCsr->isEof = 1;
120596       rc = sqlite3_reset(pCsr->pStmt);
120597     }else{
120598       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
120599       rc = SQLITE_OK;
120600     }
120601   }else{
120602     rc = fts3EvalNext((Fts3Cursor *)pCursor);
120603   }
120604   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120605   return rc;
120606 }
120607 
120608 /*
120609 ** This is the xFilter interface for the virtual table.  See
120610 ** the virtual table xFilter method documentation for additional
120611 ** information.
120612 **
120613 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
120614 ** the %_content table.
120615 **
120616 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
120617 ** in the %_content table.
120618 **
120619 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
120620 ** column on the left-hand side of the MATCH operator is column
120621 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
120622 ** side of the MATCH operator.
120623 */
120624 static int fts3FilterMethod(
120625   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
120626   int idxNum,                     /* Strategy index */
120627   const char *idxStr,             /* Unused */
120628   int nVal,                       /* Number of elements in apVal */
120629   sqlite3_value **apVal           /* Arguments for the indexing scheme */
120630 ){
120631   int rc;
120632   char *zSql;                     /* SQL statement used to access %_content */
120633   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120634   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120635 
120636   UNUSED_PARAMETER(idxStr);
120637   UNUSED_PARAMETER(nVal);
120638 
120639   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
120640   assert( nVal==0 || nVal==1 || nVal==2 );
120641   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
120642   assert( p->pSegments==0 );
120643 
120644   /* In case the cursor has been used before, clear it now. */
120645   sqlite3_finalize(pCsr->pStmt);
120646   sqlite3_free(pCsr->aDoclist);
120647   sqlite3Fts3ExprFree(pCsr->pExpr);
120648   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
120649 
120650   if( idxStr ){
120651     pCsr->bDesc = (idxStr[0]=='D');
120652   }else{
120653     pCsr->bDesc = p->bDescIdx;
120654   }
120655   pCsr->eSearch = (i16)idxNum;
120656 
120657   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
120658     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
120659     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
120660 
120661     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
120662       return SQLITE_NOMEM;
120663     }
120664 
120665     pCsr->iLangid = 0;
120666     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
120667 
120668     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
120669         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
120670     );
120671     if( rc!=SQLITE_OK ){
120672       if( rc==SQLITE_ERROR ){
120673         static const char *zErr = "malformed MATCH expression: [%s]";
120674         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
120675       }
120676       return rc;
120677     }
120678 
120679     rc = sqlite3Fts3ReadLock(p);
120680     if( rc!=SQLITE_OK ) return rc;
120681 
120682     rc = fts3EvalStart(pCsr);
120683 
120684     sqlite3Fts3SegmentsClose(p);
120685     if( rc!=SQLITE_OK ) return rc;
120686     pCsr->pNextId = pCsr->aDoclist;
120687     pCsr->iPrevId = 0;
120688   }
120689 
120690   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
120691   ** statement loops through all rows of the %_content table. For a
120692   ** full-text query or docid lookup, the statement retrieves a single
120693   ** row by docid.
120694   */
120695   if( idxNum==FTS3_FULLSCAN_SEARCH ){
120696     zSql = sqlite3_mprintf(
120697         "SELECT %s ORDER BY rowid %s",
120698         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
120699     );
120700     if( zSql ){
120701       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120702       sqlite3_free(zSql);
120703     }else{
120704       rc = SQLITE_NOMEM;
120705     }
120706   }else if( idxNum==FTS3_DOCID_SEARCH ){
120707     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
120708     if( rc==SQLITE_OK ){
120709       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
120710     }
120711   }
120712   if( rc!=SQLITE_OK ) return rc;
120713 
120714   return fts3NextMethod(pCursor);
120715 }
120716 
120717 /*
120718 ** This is the xEof method of the virtual table. SQLite calls this
120719 ** routine to find out if it has reached the end of a result set.
120720 */
120721 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
120722   return ((Fts3Cursor *)pCursor)->isEof;
120723 }
120724 
120725 /*
120726 ** This is the xRowid method. The SQLite core calls this routine to
120727 ** retrieve the rowid for the current row of the result set. fts3
120728 ** exposes %_content.docid as the rowid for the virtual table. The
120729 ** rowid should be written to *pRowid.
120730 */
120731 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
120732   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120733   *pRowid = pCsr->iPrevId;
120734   return SQLITE_OK;
120735 }
120736 
120737 /*
120738 ** This is the xColumn method, called by SQLite to request a value from
120739 ** the row that the supplied cursor currently points to.
120740 **
120741 ** If:
120742 **
120743 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
120744 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
120745 **   (iCol == p->nColumn+1) -> Docid column
120746 **   (iCol == p->nColumn+2) -> Langid column
120747 */
120748 static int fts3ColumnMethod(
120749   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
120750   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
120751   int iCol                        /* Index of column to read value from */
120752 ){
120753   int rc = SQLITE_OK;             /* Return Code */
120754   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
120755   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
120756 
120757   /* The column value supplied by SQLite must be in range. */
120758   assert( iCol>=0 && iCol<=p->nColumn+2 );
120759 
120760   if( iCol==p->nColumn+1 ){
120761     /* This call is a request for the "docid" column. Since "docid" is an
120762     ** alias for "rowid", use the xRowid() method to obtain the value.
120763     */
120764     sqlite3_result_int64(pCtx, pCsr->iPrevId);
120765   }else if( iCol==p->nColumn ){
120766     /* The extra column whose name is the same as the table.
120767     ** Return a blob which is a pointer to the cursor.  */
120768     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
120769   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
120770     sqlite3_result_int64(pCtx, pCsr->iLangid);
120771   }else{
120772     /* The requested column is either a user column (one that contains
120773     ** indexed data), or the language-id column.  */
120774     rc = fts3CursorSeek(0, pCsr);
120775 
120776     if( rc==SQLITE_OK ){
120777       if( iCol==p->nColumn+2 ){
120778         int iLangid = 0;
120779         if( p->zLanguageid ){
120780           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
120781         }
120782         sqlite3_result_int(pCtx, iLangid);
120783       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
120784         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
120785       }
120786     }
120787   }
120788 
120789   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120790   return rc;
120791 }
120792 
120793 /*
120794 ** This function is the implementation of the xUpdate callback used by
120795 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
120796 ** inserted, updated or deleted.
120797 */
120798 static int fts3UpdateMethod(
120799   sqlite3_vtab *pVtab,            /* Virtual table handle */
120800   int nArg,                       /* Size of argument array */
120801   sqlite3_value **apVal,          /* Array of arguments */
120802   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
120803 ){
120804   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
120805 }
120806 
120807 /*
120808 ** Implementation of xSync() method. Flush the contents of the pending-terms
120809 ** hash-table to the database.
120810 */
120811 static int fts3SyncMethod(sqlite3_vtab *pVtab){
120812 
120813   /* Following an incremental-merge operation, assuming that the input
120814   ** segments are not completely consumed (the usual case), they are updated
120815   ** in place to remove the entries that have already been merged. This
120816   ** involves updating the leaf block that contains the smallest unmerged
120817   ** entry and each block (if any) between the leaf and the root node. So
120818   ** if the height of the input segment b-trees is N, and input segments
120819   ** are merged eight at a time, updating the input segments at the end
120820   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
120821   ** small - often between 0 and 2. So the overhead of the incremental
120822   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
120823   ** dwarfing the actual productive work accomplished, the incremental merge
120824   ** is only attempted if it will write at least 64 leaf blocks. Hence
120825   ** nMinMerge.
120826   **
120827   ** Of course, updating the input segments also involves deleting a bunch
120828   ** of blocks from the segments table. But this is not considered overhead
120829   ** as it would also be required by a crisis-merge that used the same input
120830   ** segments.
120831   */
120832   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
120833 
120834   Fts3Table *p = (Fts3Table*)pVtab;
120835   int rc = sqlite3Fts3PendingTermsFlush(p);
120836 
120837   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
120838     int mxLevel = 0;              /* Maximum relative level value in db */
120839     int A;                        /* Incr-merge parameter A */
120840 
120841     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
120842     assert( rc==SQLITE_OK || mxLevel==0 );
120843     A = p->nLeafAdd * mxLevel;
120844     A += (A/2);
120845     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
120846   }
120847   sqlite3Fts3SegmentsClose(p);
120848   return rc;
120849 }
120850 
120851 /*
120852 ** Implementation of xBegin() method. This is a no-op.
120853 */
120854 static int fts3BeginMethod(sqlite3_vtab *pVtab){
120855   Fts3Table *p = (Fts3Table*)pVtab;
120856   UNUSED_PARAMETER(pVtab);
120857   assert( p->pSegments==0 );
120858   assert( p->nPendingData==0 );
120859   assert( p->inTransaction!=1 );
120860   TESTONLY( p->inTransaction = 1 );
120861   TESTONLY( p->mxSavepoint = -1; );
120862   p->nLeafAdd = 0;
120863   return SQLITE_OK;
120864 }
120865 
120866 /*
120867 ** Implementation of xCommit() method. This is a no-op. The contents of
120868 ** the pending-terms hash-table have already been flushed into the database
120869 ** by fts3SyncMethod().
120870 */
120871 static int fts3CommitMethod(sqlite3_vtab *pVtab){
120872   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
120873   UNUSED_PARAMETER(pVtab);
120874   assert( p->nPendingData==0 );
120875   assert( p->inTransaction!=0 );
120876   assert( p->pSegments==0 );
120877   TESTONLY( p->inTransaction = 0 );
120878   TESTONLY( p->mxSavepoint = -1; );
120879   return SQLITE_OK;
120880 }
120881 
120882 /*
120883 ** Implementation of xRollback(). Discard the contents of the pending-terms
120884 ** hash-table. Any changes made to the database are reverted by SQLite.
120885 */
120886 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
120887   Fts3Table *p = (Fts3Table*)pVtab;
120888   sqlite3Fts3PendingTermsClear(p);
120889   assert( p->inTransaction!=0 );
120890   TESTONLY( p->inTransaction = 0 );
120891   TESTONLY( p->mxSavepoint = -1; );
120892   return SQLITE_OK;
120893 }
120894 
120895 /*
120896 ** When called, *ppPoslist must point to the byte immediately following the
120897 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
120898 ** moves *ppPoslist so that it instead points to the first byte of the
120899 ** same position list.
120900 */
120901 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
120902   char *p = &(*ppPoslist)[-2];
120903   char c = 0;
120904 
120905   while( p>pStart && (c=*p--)==0 );
120906   while( p>pStart && (*p & 0x80) | c ){
120907     c = *p--;
120908   }
120909   if( p>pStart ){ p = &p[2]; }
120910   while( *p++&0x80 );
120911   *ppPoslist = p;
120912 }
120913 
120914 /*
120915 ** Helper function used by the implementation of the overloaded snippet(),
120916 ** offsets() and optimize() SQL functions.
120917 **
120918 ** If the value passed as the third argument is a blob of size
120919 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
120920 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
120921 ** message is written to context pContext and SQLITE_ERROR returned. The
120922 ** string passed via zFunc is used as part of the error message.
120923 */
120924 static int fts3FunctionArg(
120925   sqlite3_context *pContext,      /* SQL function call context */
120926   const char *zFunc,              /* Function name */
120927   sqlite3_value *pVal,            /* argv[0] passed to function */
120928   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
120929 ){
120930   Fts3Cursor *pRet;
120931   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
120932    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
120933   ){
120934     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
120935     sqlite3_result_error(pContext, zErr, -1);
120936     sqlite3_free(zErr);
120937     return SQLITE_ERROR;
120938   }
120939   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
120940   *ppCsr = pRet;
120941   return SQLITE_OK;
120942 }
120943 
120944 /*
120945 ** Implementation of the snippet() function for FTS3
120946 */
120947 static void fts3SnippetFunc(
120948   sqlite3_context *pContext,      /* SQLite function call context */
120949   int nVal,                       /* Size of apVal[] array */
120950   sqlite3_value **apVal           /* Array of arguments */
120951 ){
120952   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120953   const char *zStart = "<b>";
120954   const char *zEnd = "</b>";
120955   const char *zEllipsis = "<b>...</b>";
120956   int iCol = -1;
120957   int nToken = 15;                /* Default number of tokens in snippet */
120958 
120959   /* There must be at least one argument passed to this function (otherwise
120960   ** the non-overloaded version would have been called instead of this one).
120961   */
120962   assert( nVal>=1 );
120963 
120964   if( nVal>6 ){
120965     sqlite3_result_error(pContext,
120966         "wrong number of arguments to function snippet()", -1);
120967     return;
120968   }
120969   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
120970 
120971   switch( nVal ){
120972     case 6: nToken = sqlite3_value_int(apVal[5]);
120973     case 5: iCol = sqlite3_value_int(apVal[4]);
120974     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
120975     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
120976     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
120977   }
120978   if( !zEllipsis || !zEnd || !zStart ){
120979     sqlite3_result_error_nomem(pContext);
120980   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
120981     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
120982   }
120983 }
120984 
120985 /*
120986 ** Implementation of the offsets() function for FTS3
120987 */
120988 static void fts3OffsetsFunc(
120989   sqlite3_context *pContext,      /* SQLite function call context */
120990   int nVal,                       /* Size of argument array */
120991   sqlite3_value **apVal           /* Array of arguments */
120992 ){
120993   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
120994 
120995   UNUSED_PARAMETER(nVal);
120996 
120997   assert( nVal==1 );
120998   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
120999   assert( pCsr );
121000   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
121001     sqlite3Fts3Offsets(pContext, pCsr);
121002   }
121003 }
121004 
121005 /*
121006 ** Implementation of the special optimize() function for FTS3. This
121007 ** function merges all segments in the database to a single segment.
121008 ** Example usage is:
121009 **
121010 **   SELECT optimize(t) FROM t LIMIT 1;
121011 **
121012 ** where 't' is the name of an FTS3 table.
121013 */
121014 static void fts3OptimizeFunc(
121015   sqlite3_context *pContext,      /* SQLite function call context */
121016   int nVal,                       /* Size of argument array */
121017   sqlite3_value **apVal           /* Array of arguments */
121018 ){
121019   int rc;                         /* Return code */
121020   Fts3Table *p;                   /* Virtual table handle */
121021   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
121022 
121023   UNUSED_PARAMETER(nVal);
121024 
121025   assert( nVal==1 );
121026   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
121027   p = (Fts3Table *)pCursor->base.pVtab;
121028   assert( p );
121029 
121030   rc = sqlite3Fts3Optimize(p);
121031 
121032   switch( rc ){
121033     case SQLITE_OK:
121034       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
121035       break;
121036     case SQLITE_DONE:
121037       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
121038       break;
121039     default:
121040       sqlite3_result_error_code(pContext, rc);
121041       break;
121042   }
121043 }
121044 
121045 /*
121046 ** Implementation of the matchinfo() function for FTS3
121047 */
121048 static void fts3MatchinfoFunc(
121049   sqlite3_context *pContext,      /* SQLite function call context */
121050   int nVal,                       /* Size of argument array */
121051   sqlite3_value **apVal           /* Array of arguments */
121052 ){
121053   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
121054   assert( nVal==1 || nVal==2 );
121055   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
121056     const char *zArg = 0;
121057     if( nVal>1 ){
121058       zArg = (const char *)sqlite3_value_text(apVal[1]);
121059     }
121060     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
121061   }
121062 }
121063 
121064 /*
121065 ** This routine implements the xFindFunction method for the FTS3
121066 ** virtual table.
121067 */
121068 static int fts3FindFunctionMethod(
121069   sqlite3_vtab *pVtab,            /* Virtual table handle */
121070   int nArg,                       /* Number of SQL function arguments */
121071   const char *zName,              /* Name of SQL function */
121072   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
121073   void **ppArg                    /* Unused */
121074 ){
121075   struct Overloaded {
121076     const char *zName;
121077     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
121078   } aOverload[] = {
121079     { "snippet", fts3SnippetFunc },
121080     { "offsets", fts3OffsetsFunc },
121081     { "optimize", fts3OptimizeFunc },
121082     { "matchinfo", fts3MatchinfoFunc },
121083   };
121084   int i;                          /* Iterator variable */
121085 
121086   UNUSED_PARAMETER(pVtab);
121087   UNUSED_PARAMETER(nArg);
121088   UNUSED_PARAMETER(ppArg);
121089 
121090   for(i=0; i<SizeofArray(aOverload); i++){
121091     if( strcmp(zName, aOverload[i].zName)==0 ){
121092       *pxFunc = aOverload[i].xFunc;
121093       return 1;
121094     }
121095   }
121096 
121097   /* No function of the specified name was found. Return 0. */
121098   return 0;
121099 }
121100 
121101 /*
121102 ** Implementation of FTS3 xRename method. Rename an fts3 table.
121103 */
121104 static int fts3RenameMethod(
121105   sqlite3_vtab *pVtab,            /* Virtual table handle */
121106   const char *zName               /* New name of table */
121107 ){
121108   Fts3Table *p = (Fts3Table *)pVtab;
121109   sqlite3 *db = p->db;            /* Database connection */
121110   int rc;                         /* Return Code */
121111 
121112   /* As it happens, the pending terms table is always empty here. This is
121113   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
121114   ** always opens a savepoint transaction. And the xSavepoint() method
121115   ** flushes the pending terms table. But leave the (no-op) call to
121116   ** PendingTermsFlush() in in case that changes.
121117   */
121118   assert( p->nPendingData==0 );
121119   rc = sqlite3Fts3PendingTermsFlush(p);
121120 
121121   if( p->zContentTbl==0 ){
121122     fts3DbExec(&rc, db,
121123       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
121124       p->zDb, p->zName, zName
121125     );
121126   }
121127 
121128   if( p->bHasDocsize ){
121129     fts3DbExec(&rc, db,
121130       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
121131       p->zDb, p->zName, zName
121132     );
121133   }
121134   if( p->bHasStat ){
121135     fts3DbExec(&rc, db,
121136       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
121137       p->zDb, p->zName, zName
121138     );
121139   }
121140   fts3DbExec(&rc, db,
121141     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
121142     p->zDb, p->zName, zName
121143   );
121144   fts3DbExec(&rc, db,
121145     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
121146     p->zDb, p->zName, zName
121147   );
121148   return rc;
121149 }
121150 
121151 /*
121152 ** The xSavepoint() method.
121153 **
121154 ** Flush the contents of the pending-terms table to disk.
121155 */
121156 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
121157   int rc = SQLITE_OK;
121158   UNUSED_PARAMETER(iSavepoint);
121159   assert( ((Fts3Table *)pVtab)->inTransaction );
121160   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
121161   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
121162   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
121163     rc = fts3SyncMethod(pVtab);
121164   }
121165   return rc;
121166 }
121167 
121168 /*
121169 ** The xRelease() method.
121170 **
121171 ** This is a no-op.
121172 */
121173 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
121174   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
121175   UNUSED_PARAMETER(iSavepoint);
121176   UNUSED_PARAMETER(pVtab);
121177   assert( p->inTransaction );
121178   assert( p->mxSavepoint >= iSavepoint );
121179   TESTONLY( p->mxSavepoint = iSavepoint-1 );
121180   return SQLITE_OK;
121181 }
121182 
121183 /*
121184 ** The xRollbackTo() method.
121185 **
121186 ** Discard the contents of the pending terms table.
121187 */
121188 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
121189   Fts3Table *p = (Fts3Table*)pVtab;
121190   UNUSED_PARAMETER(iSavepoint);
121191   assert( p->inTransaction );
121192   assert( p->mxSavepoint >= iSavepoint );
121193   TESTONLY( p->mxSavepoint = iSavepoint );
121194   sqlite3Fts3PendingTermsClear(p);
121195   return SQLITE_OK;
121196 }
121197 
121198 static const sqlite3_module fts3Module = {
121199   /* iVersion      */ 2,
121200   /* xCreate       */ fts3CreateMethod,
121201   /* xConnect      */ fts3ConnectMethod,
121202   /* xBestIndex    */ fts3BestIndexMethod,
121203   /* xDisconnect   */ fts3DisconnectMethod,
121204   /* xDestroy      */ fts3DestroyMethod,
121205   /* xOpen         */ fts3OpenMethod,
121206   /* xClose        */ fts3CloseMethod,
121207   /* xFilter       */ fts3FilterMethod,
121208   /* xNext         */ fts3NextMethod,
121209   /* xEof          */ fts3EofMethod,
121210   /* xColumn       */ fts3ColumnMethod,
121211   /* xRowid        */ fts3RowidMethod,
121212   /* xUpdate       */ fts3UpdateMethod,
121213   /* xBegin        */ fts3BeginMethod,
121214   /* xSync         */ fts3SyncMethod,
121215   /* xCommit       */ fts3CommitMethod,
121216   /* xRollback     */ fts3RollbackMethod,
121217   /* xFindFunction */ fts3FindFunctionMethod,
121218   /* xRename */       fts3RenameMethod,
121219   /* xSavepoint    */ fts3SavepointMethod,
121220   /* xRelease      */ fts3ReleaseMethod,
121221   /* xRollbackTo   */ fts3RollbackToMethod,
121222 };
121223 
121224 /*
121225 ** This function is registered as the module destructor (called when an
121226 ** FTS3 enabled database connection is closed). It frees the memory
121227 ** allocated for the tokenizer hash table.
121228 */
121229 static void hashDestroy(void *p){
121230   Fts3Hash *pHash = (Fts3Hash *)p;
121231   sqlite3Fts3HashClear(pHash);
121232   sqlite3_free(pHash);
121233 }
121234 
121235 /*
121236 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
121237 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
121238 ** respectively. The following three forward declarations are for functions
121239 ** declared in these files used to retrieve the respective implementations.
121240 **
121241 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
121242 ** to by the argument to point to the "simple" tokenizer implementation.
121243 ** And so on.
121244 */
121245 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121246 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121247 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121248 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
121249 #endif
121250 #ifdef SQLITE_ENABLE_ICU
121251 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121252 #endif
121253 
121254 /*
121255 ** Initialize the fts3 extension. If this extension is built as part
121256 ** of the sqlite library, then this function is called directly by
121257 ** SQLite. If fts3 is built as a dynamically loadable extension, this
121258 ** function is called by the sqlite3_extension_init() entry point.
121259 */
121260 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
121261   int rc = SQLITE_OK;
121262   Fts3Hash *pHash = 0;
121263   const sqlite3_tokenizer_module *pSimple = 0;
121264   const sqlite3_tokenizer_module *pPorter = 0;
121265 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121266   const sqlite3_tokenizer_module *pUnicode = 0;
121267 #endif
121268 
121269 #ifdef SQLITE_ENABLE_ICU
121270   const sqlite3_tokenizer_module *pIcu = 0;
121271   sqlite3Fts3IcuTokenizerModule(&pIcu);
121272 #endif
121273 
121274 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121275   sqlite3Fts3UnicodeTokenizer(&pUnicode);
121276 #endif
121277 
121278 #ifdef SQLITE_TEST
121279   rc = sqlite3Fts3InitTerm(db);
121280   if( rc!=SQLITE_OK ) return rc;
121281 #endif
121282 
121283   rc = sqlite3Fts3InitAux(db);
121284   if( rc!=SQLITE_OK ) return rc;
121285 
121286   sqlite3Fts3SimpleTokenizerModule(&pSimple);
121287   sqlite3Fts3PorterTokenizerModule(&pPorter);
121288 
121289   /* Allocate and initialize the hash-table used to store tokenizers. */
121290   pHash = sqlite3_malloc(sizeof(Fts3Hash));
121291   if( !pHash ){
121292     rc = SQLITE_NOMEM;
121293   }else{
121294     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
121295   }
121296 
121297   /* Load the built-in tokenizers into the hash table */
121298   if( rc==SQLITE_OK ){
121299     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
121300      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
121301 
121302 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
121303      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
121304 #endif
121305 #ifdef SQLITE_ENABLE_ICU
121306      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
121307 #endif
121308     ){
121309       rc = SQLITE_NOMEM;
121310     }
121311   }
121312 
121313 #ifdef SQLITE_TEST
121314   if( rc==SQLITE_OK ){
121315     rc = sqlite3Fts3ExprInitTestInterface(db);
121316   }
121317 #endif
121318 
121319   /* Create the virtual table wrapper around the hash-table and overload
121320   ** the two scalar functions. If this is successful, register the
121321   ** module with sqlite.
121322   */
121323   if( SQLITE_OK==rc
121324    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
121325    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
121326    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
121327    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
121328    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
121329    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
121330   ){
121331     rc = sqlite3_create_module_v2(
121332         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
121333     );
121334     if( rc==SQLITE_OK ){
121335       rc = sqlite3_create_module_v2(
121336           db, "fts4", &fts3Module, (void *)pHash, 0
121337       );
121338     }
121339     return rc;
121340   }
121341 
121342   /* An error has occurred. Delete the hash table and return the error code. */
121343   assert( rc!=SQLITE_OK );
121344   if( pHash ){
121345     sqlite3Fts3HashClear(pHash);
121346     sqlite3_free(pHash);
121347   }
121348   return rc;
121349 }
121350 
121351 /*
121352 ** Allocate an Fts3MultiSegReader for each token in the expression headed
121353 ** by pExpr.
121354 **
121355 ** An Fts3SegReader object is a cursor that can seek or scan a range of
121356 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
121357 ** Fts3SegReader objects internally to provide an interface to seek or scan
121358 ** within the union of all segments of a b-tree. Hence the name.
121359 **
121360 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
121361 ** segment b-tree (if the term is not a prefix or it is a prefix for which
121362 ** there exists prefix b-tree of the right length) then it may be traversed
121363 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
121364 ** doclist and then traversed.
121365 */
121366 static void fts3EvalAllocateReaders(
121367   Fts3Cursor *pCsr,               /* FTS cursor handle */
121368   Fts3Expr *pExpr,                /* Allocate readers for this expression */
121369   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
121370   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
121371   int *pRc                        /* IN/OUT: Error code */
121372 ){
121373   if( pExpr && SQLITE_OK==*pRc ){
121374     if( pExpr->eType==FTSQUERY_PHRASE ){
121375       int i;
121376       int nToken = pExpr->pPhrase->nToken;
121377       *pnToken += nToken;
121378       for(i=0; i<nToken; i++){
121379         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
121380         int rc = fts3TermSegReaderCursor(pCsr,
121381             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
121382         );
121383         if( rc!=SQLITE_OK ){
121384           *pRc = rc;
121385           return;
121386         }
121387       }
121388       assert( pExpr->pPhrase->iDoclistToken==0 );
121389       pExpr->pPhrase->iDoclistToken = -1;
121390     }else{
121391       *pnOr += (pExpr->eType==FTSQUERY_OR);
121392       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
121393       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
121394     }
121395   }
121396 }
121397 
121398 /*
121399 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
121400 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
121401 **
121402 ** This function assumes that pList points to a buffer allocated using
121403 ** sqlite3_malloc(). This function takes responsibility for eventually
121404 ** freeing the buffer.
121405 */
121406 static void fts3EvalPhraseMergeToken(
121407   Fts3Table *pTab,                /* FTS Table pointer */
121408   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
121409   int iToken,                     /* Token pList/nList corresponds to */
121410   char *pList,                    /* Pointer to doclist */
121411   int nList                       /* Number of bytes in pList */
121412 ){
121413   assert( iToken!=p->iDoclistToken );
121414 
121415   if( pList==0 ){
121416     sqlite3_free(p->doclist.aAll);
121417     p->doclist.aAll = 0;
121418     p->doclist.nAll = 0;
121419   }
121420 
121421   else if( p->iDoclistToken<0 ){
121422     p->doclist.aAll = pList;
121423     p->doclist.nAll = nList;
121424   }
121425 
121426   else if( p->doclist.aAll==0 ){
121427     sqlite3_free(pList);
121428   }
121429 
121430   else {
121431     char *pLeft;
121432     char *pRight;
121433     int nLeft;
121434     int nRight;
121435     int nDiff;
121436 
121437     if( p->iDoclistToken<iToken ){
121438       pLeft = p->doclist.aAll;
121439       nLeft = p->doclist.nAll;
121440       pRight = pList;
121441       nRight = nList;
121442       nDiff = iToken - p->iDoclistToken;
121443     }else{
121444       pRight = p->doclist.aAll;
121445       nRight = p->doclist.nAll;
121446       pLeft = pList;
121447       nLeft = nList;
121448       nDiff = p->iDoclistToken - iToken;
121449     }
121450 
121451     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
121452     sqlite3_free(pLeft);
121453     p->doclist.aAll = pRight;
121454     p->doclist.nAll = nRight;
121455   }
121456 
121457   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
121458 }
121459 
121460 /*
121461 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
121462 ** does not take deferred tokens into account.
121463 **
121464 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121465 */
121466 static int fts3EvalPhraseLoad(
121467   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121468   Fts3Phrase *p                   /* Phrase object */
121469 ){
121470   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121471   int iToken;
121472   int rc = SQLITE_OK;
121473 
121474   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
121475     Fts3PhraseToken *pToken = &p->aToken[iToken];
121476     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
121477 
121478     if( pToken->pSegcsr ){
121479       int nThis = 0;
121480       char *pThis = 0;
121481       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
121482       if( rc==SQLITE_OK ){
121483         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
121484       }
121485     }
121486     assert( pToken->pSegcsr==0 );
121487   }
121488 
121489   return rc;
121490 }
121491 
121492 /*
121493 ** This function is called on each phrase after the position lists for
121494 ** any deferred tokens have been loaded into memory. It updates the phrases
121495 ** current position list to include only those positions that are really
121496 ** instances of the phrase (after considering deferred tokens). If this
121497 ** means that the phrase does not appear in the current row, doclist.pList
121498 ** and doclist.nList are both zeroed.
121499 **
121500 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121501 */
121502 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
121503   int iToken;                     /* Used to iterate through phrase tokens */
121504   char *aPoslist = 0;             /* Position list for deferred tokens */
121505   int nPoslist = 0;               /* Number of bytes in aPoslist */
121506   int iPrev = -1;                 /* Token number of previous deferred token */
121507 
121508   assert( pPhrase->doclist.bFreeList==0 );
121509 
121510   for(iToken=0; iToken<pPhrase->nToken; iToken++){
121511     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
121512     Fts3DeferredToken *pDeferred = pToken->pDeferred;
121513 
121514     if( pDeferred ){
121515       char *pList;
121516       int nList;
121517       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
121518       if( rc!=SQLITE_OK ) return rc;
121519 
121520       if( pList==0 ){
121521         sqlite3_free(aPoslist);
121522         pPhrase->doclist.pList = 0;
121523         pPhrase->doclist.nList = 0;
121524         return SQLITE_OK;
121525 
121526       }else if( aPoslist==0 ){
121527         aPoslist = pList;
121528         nPoslist = nList;
121529 
121530       }else{
121531         char *aOut = pList;
121532         char *p1 = aPoslist;
121533         char *p2 = aOut;
121534 
121535         assert( iPrev>=0 );
121536         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
121537         sqlite3_free(aPoslist);
121538         aPoslist = pList;
121539         nPoslist = (int)(aOut - aPoslist);
121540         if( nPoslist==0 ){
121541           sqlite3_free(aPoslist);
121542           pPhrase->doclist.pList = 0;
121543           pPhrase->doclist.nList = 0;
121544           return SQLITE_OK;
121545         }
121546       }
121547       iPrev = iToken;
121548     }
121549   }
121550 
121551   if( iPrev>=0 ){
121552     int nMaxUndeferred = pPhrase->iDoclistToken;
121553     if( nMaxUndeferred<0 ){
121554       pPhrase->doclist.pList = aPoslist;
121555       pPhrase->doclist.nList = nPoslist;
121556       pPhrase->doclist.iDocid = pCsr->iPrevId;
121557       pPhrase->doclist.bFreeList = 1;
121558     }else{
121559       int nDistance;
121560       char *p1;
121561       char *p2;
121562       char *aOut;
121563 
121564       if( nMaxUndeferred>iPrev ){
121565         p1 = aPoslist;
121566         p2 = pPhrase->doclist.pList;
121567         nDistance = nMaxUndeferred - iPrev;
121568       }else{
121569         p1 = pPhrase->doclist.pList;
121570         p2 = aPoslist;
121571         nDistance = iPrev - nMaxUndeferred;
121572       }
121573 
121574       aOut = (char *)sqlite3_malloc(nPoslist+8);
121575       if( !aOut ){
121576         sqlite3_free(aPoslist);
121577         return SQLITE_NOMEM;
121578       }
121579 
121580       pPhrase->doclist.pList = aOut;
121581       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
121582         pPhrase->doclist.bFreeList = 1;
121583         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
121584       }else{
121585         sqlite3_free(aOut);
121586         pPhrase->doclist.pList = 0;
121587         pPhrase->doclist.nList = 0;
121588       }
121589       sqlite3_free(aPoslist);
121590     }
121591   }
121592 
121593   return SQLITE_OK;
121594 }
121595 
121596 /*
121597 ** This function is called for each Fts3Phrase in a full-text query
121598 ** expression to initialize the mechanism for returning rows. Once this
121599 ** function has been called successfully on an Fts3Phrase, it may be
121600 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
121601 **
121602 ** If parameter bOptOk is true, then the phrase may (or may not) use the
121603 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
121604 ** memory within this call.
121605 **
121606 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121607 */
121608 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
121609   int rc;                         /* Error code */
121610   Fts3PhraseToken *pFirst = &p->aToken[0];
121611   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121612 
121613   if( pCsr->bDesc==pTab->bDescIdx
121614    && bOptOk==1
121615    && p->nToken==1
121616    && pFirst->pSegcsr
121617    && pFirst->pSegcsr->bLookup
121618    && pFirst->bFirst==0
121619   ){
121620     /* Use the incremental approach. */
121621     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
121622     rc = sqlite3Fts3MsrIncrStart(
121623         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
121624     p->bIncr = 1;
121625 
121626   }else{
121627     /* Load the full doclist for the phrase into memory. */
121628     rc = fts3EvalPhraseLoad(pCsr, p);
121629     p->bIncr = 0;
121630   }
121631 
121632   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
121633   return rc;
121634 }
121635 
121636 /*
121637 ** This function is used to iterate backwards (from the end to start)
121638 ** through doclists. It is used by this module to iterate through phrase
121639 ** doclists in reverse and by the fts3_write.c module to iterate through
121640 ** pending-terms lists when writing to databases with "order=desc".
121641 **
121642 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
121643 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
121644 ** function iterates from the end of the doclist to the beginning.
121645 */
121646 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
121647   int bDescIdx,                   /* True if the doclist is desc */
121648   char *aDoclist,                 /* Pointer to entire doclist */
121649   int nDoclist,                   /* Length of aDoclist in bytes */
121650   char **ppIter,                  /* IN/OUT: Iterator pointer */
121651   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121652   int *pnList,                    /* OUT: List length pointer */
121653   u8 *pbEof                       /* OUT: End-of-file flag */
121654 ){
121655   char *p = *ppIter;
121656 
121657   assert( nDoclist>0 );
121658   assert( *pbEof==0 );
121659   assert( p || *piDocid==0 );
121660   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
121661 
121662   if( p==0 ){
121663     sqlite3_int64 iDocid = 0;
121664     char *pNext = 0;
121665     char *pDocid = aDoclist;
121666     char *pEnd = &aDoclist[nDoclist];
121667     int iMul = 1;
121668 
121669     while( pDocid<pEnd ){
121670       sqlite3_int64 iDelta;
121671       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
121672       iDocid += (iMul * iDelta);
121673       pNext = pDocid;
121674       fts3PoslistCopy(0, &pDocid);
121675       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
121676       iMul = (bDescIdx ? -1 : 1);
121677     }
121678 
121679     *pnList = (int)(pEnd - pNext);
121680     *ppIter = pNext;
121681     *piDocid = iDocid;
121682   }else{
121683     int iMul = (bDescIdx ? -1 : 1);
121684     sqlite3_int64 iDelta;
121685     fts3GetReverseVarint(&p, aDoclist, &iDelta);
121686     *piDocid -= (iMul * iDelta);
121687 
121688     if( p==aDoclist ){
121689       *pbEof = 1;
121690     }else{
121691       char *pSave = p;
121692       fts3ReversePoslist(aDoclist, &p);
121693       *pnList = (int)(pSave - p);
121694     }
121695     *ppIter = p;
121696   }
121697 }
121698 
121699 /*
121700 ** Iterate forwards through a doclist.
121701 */
121702 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
121703   int bDescIdx,                   /* True if the doclist is desc */
121704   char *aDoclist,                 /* Pointer to entire doclist */
121705   int nDoclist,                   /* Length of aDoclist in bytes */
121706   char **ppIter,                  /* IN/OUT: Iterator pointer */
121707   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
121708   u8 *pbEof                       /* OUT: End-of-file flag */
121709 ){
121710   char *p = *ppIter;
121711 
121712   assert( nDoclist>0 );
121713   assert( *pbEof==0 );
121714   assert( p || *piDocid==0 );
121715   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
121716 
121717   if( p==0 ){
121718     p = aDoclist;
121719     p += sqlite3Fts3GetVarint(p, piDocid);
121720   }else{
121721     fts3PoslistCopy(0, &p);
121722     if( p>=&aDoclist[nDoclist] ){
121723       *pbEof = 1;
121724     }else{
121725       sqlite3_int64 iVar;
121726       p += sqlite3Fts3GetVarint(p, &iVar);
121727       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
121728     }
121729   }
121730 
121731   *ppIter = p;
121732 }
121733 
121734 /*
121735 ** Attempt to move the phrase iterator to point to the next matching docid.
121736 ** If an error occurs, return an SQLite error code. Otherwise, return
121737 ** SQLITE_OK.
121738 **
121739 ** If there is no "next" entry and no error occurs, then *pbEof is set to
121740 ** 1 before returning. Otherwise, if no error occurs and the iterator is
121741 ** successfully advanced, *pbEof is set to 0.
121742 */
121743 static int fts3EvalPhraseNext(
121744   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121745   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
121746   u8 *pbEof                       /* OUT: Set to 1 if EOF */
121747 ){
121748   int rc = SQLITE_OK;
121749   Fts3Doclist *pDL = &p->doclist;
121750   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121751 
121752   if( p->bIncr ){
121753     assert( p->nToken==1 );
121754     assert( pDL->pNextDocid==0 );
121755     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
121756         &pDL->iDocid, &pDL->pList, &pDL->nList
121757     );
121758     if( rc==SQLITE_OK && !pDL->pList ){
121759       *pbEof = 1;
121760     }
121761   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
121762     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
121763         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
121764     );
121765     pDL->pList = pDL->pNextDocid;
121766   }else{
121767     char *pIter;                            /* Used to iterate through aAll */
121768     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
121769     if( pDL->pNextDocid ){
121770       pIter = pDL->pNextDocid;
121771     }else{
121772       pIter = pDL->aAll;
121773     }
121774 
121775     if( pIter>=pEnd ){
121776       /* We have already reached the end of this doclist. EOF. */
121777       *pbEof = 1;
121778     }else{
121779       sqlite3_int64 iDelta;
121780       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
121781       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
121782         pDL->iDocid += iDelta;
121783       }else{
121784         pDL->iDocid -= iDelta;
121785       }
121786       pDL->pList = pIter;
121787       fts3PoslistCopy(0, &pIter);
121788       pDL->nList = (int)(pIter - pDL->pList);
121789 
121790       /* pIter now points just past the 0x00 that terminates the position-
121791       ** list for document pDL->iDocid. However, if this position-list was
121792       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
121793       ** point to the start of the next docid value. The following line deals
121794       ** with this case by advancing pIter past the zero-padding added by
121795       ** fts3EvalNearTrim().  */
121796       while( pIter<pEnd && *pIter==0 ) pIter++;
121797 
121798       pDL->pNextDocid = pIter;
121799       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
121800       *pbEof = 0;
121801     }
121802   }
121803 
121804   return rc;
121805 }
121806 
121807 /*
121808 **
121809 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121810 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
121811 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
121812 ** expressions for which all descendent tokens are deferred.
121813 **
121814 ** If parameter bOptOk is zero, then it is guaranteed that the
121815 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
121816 ** each phrase in the expression (subject to deferred token processing).
121817 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
121818 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
121819 **
121820 ** If an error occurs within this function, *pRc is set to an SQLite error
121821 ** code before returning.
121822 */
121823 static void fts3EvalStartReaders(
121824   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121825   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
121826   int bOptOk,                     /* True to enable incremental loading */
121827   int *pRc                        /* IN/OUT: Error code */
121828 ){
121829   if( pExpr && SQLITE_OK==*pRc ){
121830     if( pExpr->eType==FTSQUERY_PHRASE ){
121831       int i;
121832       int nToken = pExpr->pPhrase->nToken;
121833       for(i=0; i<nToken; i++){
121834         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
121835       }
121836       pExpr->bDeferred = (i==nToken);
121837       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
121838     }else{
121839       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
121840       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
121841       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
121842     }
121843   }
121844 }
121845 
121846 /*
121847 ** An array of the following structures is assembled as part of the process
121848 ** of selecting tokens to defer before the query starts executing (as part
121849 ** of the xFilter() method). There is one element in the array for each
121850 ** token in the FTS expression.
121851 **
121852 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
121853 ** to phrases that are connected only by AND and NEAR operators (not OR or
121854 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
121855 ** separately. The root of a tokens AND/NEAR cluster is stored in
121856 ** Fts3TokenAndCost.pRoot.
121857 */
121858 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
121859 struct Fts3TokenAndCost {
121860   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
121861   int iToken;                     /* Position of token in phrase */
121862   Fts3PhraseToken *pToken;        /* The token itself */
121863   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
121864   int nOvfl;                      /* Number of overflow pages to load doclist */
121865   int iCol;                       /* The column the token must match */
121866 };
121867 
121868 /*
121869 ** This function is used to populate an allocated Fts3TokenAndCost array.
121870 **
121871 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121872 ** Otherwise, if an error occurs during execution, *pRc is set to an
121873 ** SQLite error code.
121874 */
121875 static void fts3EvalTokenCosts(
121876   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121877   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
121878   Fts3Expr *pExpr,                /* Expression to consider */
121879   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
121880   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
121881   int *pRc                        /* IN/OUT: Error code */
121882 ){
121883   if( *pRc==SQLITE_OK ){
121884     if( pExpr->eType==FTSQUERY_PHRASE ){
121885       Fts3Phrase *pPhrase = pExpr->pPhrase;
121886       int i;
121887       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
121888         Fts3TokenAndCost *pTC = (*ppTC)++;
121889         pTC->pPhrase = pPhrase;
121890         pTC->iToken = i;
121891         pTC->pRoot = pRoot;
121892         pTC->pToken = &pPhrase->aToken[i];
121893         pTC->iCol = pPhrase->iColumn;
121894         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
121895       }
121896     }else if( pExpr->eType!=FTSQUERY_NOT ){
121897       assert( pExpr->eType==FTSQUERY_OR
121898            || pExpr->eType==FTSQUERY_AND
121899            || pExpr->eType==FTSQUERY_NEAR
121900       );
121901       assert( pExpr->pLeft && pExpr->pRight );
121902       if( pExpr->eType==FTSQUERY_OR ){
121903         pRoot = pExpr->pLeft;
121904         **ppOr = pRoot;
121905         (*ppOr)++;
121906       }
121907       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
121908       if( pExpr->eType==FTSQUERY_OR ){
121909         pRoot = pExpr->pRight;
121910         **ppOr = pRoot;
121911         (*ppOr)++;
121912       }
121913       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
121914     }
121915   }
121916 }
121917 
121918 /*
121919 ** Determine the average document (row) size in pages. If successful,
121920 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
121921 ** an SQLite error code.
121922 **
121923 ** The average document size in pages is calculated by first calculating
121924 ** determining the average size in bytes, B. If B is less than the amount
121925 ** of data that will fit on a single leaf page of an intkey table in
121926 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
121927 ** the number of overflow pages consumed by a record B bytes in size.
121928 */
121929 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
121930   if( pCsr->nRowAvg==0 ){
121931     /* The average document size, which is required to calculate the cost
121932     ** of each doclist, has not yet been determined. Read the required
121933     ** data from the %_stat table to calculate it.
121934     **
121935     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
121936     ** varints, where nCol is the number of columns in the FTS3 table.
121937     ** The first varint is the number of documents currently stored in
121938     ** the table. The following nCol varints contain the total amount of
121939     ** data stored in all rows of each column of the table, from left
121940     ** to right.
121941     */
121942     int rc;
121943     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
121944     sqlite3_stmt *pStmt;
121945     sqlite3_int64 nDoc = 0;
121946     sqlite3_int64 nByte = 0;
121947     const char *pEnd;
121948     const char *a;
121949 
121950     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
121951     if( rc!=SQLITE_OK ) return rc;
121952     a = sqlite3_column_blob(pStmt, 0);
121953     assert( a );
121954 
121955     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
121956     a += sqlite3Fts3GetVarint(a, &nDoc);
121957     while( a<pEnd ){
121958       a += sqlite3Fts3GetVarint(a, &nByte);
121959     }
121960     if( nDoc==0 || nByte==0 ){
121961       sqlite3_reset(pStmt);
121962       return FTS_CORRUPT_VTAB;
121963     }
121964 
121965     pCsr->nDoc = nDoc;
121966     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
121967     assert( pCsr->nRowAvg>0 );
121968     rc = sqlite3_reset(pStmt);
121969     if( rc!=SQLITE_OK ) return rc;
121970   }
121971 
121972   *pnPage = pCsr->nRowAvg;
121973   return SQLITE_OK;
121974 }
121975 
121976 /*
121977 ** This function is called to select the tokens (if any) that will be
121978 ** deferred. The array aTC[] has already been populated when this is
121979 ** called.
121980 **
121981 ** This function is called once for each AND/NEAR cluster in the
121982 ** expression. Each invocation determines which tokens to defer within
121983 ** the cluster with root node pRoot. See comments above the definition
121984 ** of struct Fts3TokenAndCost for more details.
121985 **
121986 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
121987 ** called on each token to defer. Otherwise, an SQLite error code is
121988 ** returned.
121989 */
121990 static int fts3EvalSelectDeferred(
121991   Fts3Cursor *pCsr,               /* FTS Cursor handle */
121992   Fts3Expr *pRoot,                /* Consider tokens with this root node */
121993   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
121994   int nTC                         /* Number of entries in aTC[] */
121995 ){
121996   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121997   int nDocSize = 0;               /* Number of pages per doc loaded */
121998   int rc = SQLITE_OK;             /* Return code */
121999   int ii;                         /* Iterator variable for various purposes */
122000   int nOvfl = 0;                  /* Total overflow pages used by doclists */
122001   int nToken = 0;                 /* Total number of tokens in cluster */
122002 
122003   int nMinEst = 0;                /* The minimum count for any phrase so far. */
122004   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
122005 
122006   /* Tokens are never deferred for FTS tables created using the content=xxx
122007   ** option. The reason being that it is not guaranteed that the content
122008   ** table actually contains the same data as the index. To prevent this from
122009   ** causing any problems, the deferred token optimization is completely
122010   ** disabled for content=xxx tables. */
122011   if( pTab->zContentTbl ){
122012     return SQLITE_OK;
122013   }
122014 
122015   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
122016   ** associated with the tokens spill onto overflow pages, or if there is
122017   ** only 1 token, exit early. No tokens to defer in this case. */
122018   for(ii=0; ii<nTC; ii++){
122019     if( aTC[ii].pRoot==pRoot ){
122020       nOvfl += aTC[ii].nOvfl;
122021       nToken++;
122022     }
122023   }
122024   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
122025 
122026   /* Obtain the average docsize (in pages). */
122027   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
122028   assert( rc!=SQLITE_OK || nDocSize>0 );
122029 
122030 
122031   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
122032   ** of the number of overflow pages that will be loaded by the pager layer
122033   ** to retrieve the entire doclist for the token from the full-text index.
122034   ** Load the doclists for tokens that are either:
122035   **
122036   **   a. The cheapest token in the entire query (i.e. the one visited by the
122037   **      first iteration of this loop), or
122038   **
122039   **   b. Part of a multi-token phrase.
122040   **
122041   ** After each token doclist is loaded, merge it with the others from the
122042   ** same phrase and count the number of documents that the merged doclist
122043   ** contains. Set variable "nMinEst" to the smallest number of documents in
122044   ** any phrase doclist for which 1 or more token doclists have been loaded.
122045   ** Let nOther be the number of other phrases for which it is certain that
122046   ** one or more tokens will not be deferred.
122047   **
122048   ** Then, for each token, defer it if loading the doclist would result in
122049   ** loading N or more overflow pages into memory, where N is computed as:
122050   **
122051   **    (nMinEst + 4^nOther - 1) / (4^nOther)
122052   */
122053   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
122054     int iTC;                      /* Used to iterate through aTC[] array. */
122055     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
122056 
122057     /* Set pTC to point to the cheapest remaining token. */
122058     for(iTC=0; iTC<nTC; iTC++){
122059       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
122060        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
122061       ){
122062         pTC = &aTC[iTC];
122063       }
122064     }
122065     assert( pTC );
122066 
122067     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
122068       /* The number of overflow pages to load for this (and therefore all
122069       ** subsequent) tokens is greater than the estimated number of pages
122070       ** that will be loaded if all subsequent tokens are deferred.
122071       */
122072       Fts3PhraseToken *pToken = pTC->pToken;
122073       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
122074       fts3SegReaderCursorFree(pToken->pSegcsr);
122075       pToken->pSegcsr = 0;
122076     }else{
122077       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
122078       ** for-loop. Except, limit the value to 2^24 to prevent it from
122079       ** overflowing the 32-bit integer it is stored in. */
122080       if( ii<12 ) nLoad4 = nLoad4*4;
122081 
122082       if( ii==0 || pTC->pPhrase->nToken>1 ){
122083         /* Either this is the cheapest token in the entire query, or it is
122084         ** part of a multi-token phrase. Either way, the entire doclist will
122085         ** (eventually) be loaded into memory. It may as well be now. */
122086         Fts3PhraseToken *pToken = pTC->pToken;
122087         int nList = 0;
122088         char *pList = 0;
122089         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
122090         assert( rc==SQLITE_OK || pList==0 );
122091         if( rc==SQLITE_OK ){
122092           int nCount;
122093           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
122094           nCount = fts3DoclistCountDocids(
122095               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
122096           );
122097           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
122098         }
122099       }
122100     }
122101     pTC->pToken = 0;
122102   }
122103 
122104   return rc;
122105 }
122106 
122107 /*
122108 ** This function is called from within the xFilter method. It initializes
122109 ** the full-text query currently stored in pCsr->pExpr. To iterate through
122110 ** the results of a query, the caller does:
122111 **
122112 **    fts3EvalStart(pCsr);
122113 **    while( 1 ){
122114 **      fts3EvalNext(pCsr);
122115 **      if( pCsr->bEof ) break;
122116 **      ... return row pCsr->iPrevId to the caller ...
122117 **    }
122118 */
122119 static int fts3EvalStart(Fts3Cursor *pCsr){
122120   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122121   int rc = SQLITE_OK;
122122   int nToken = 0;
122123   int nOr = 0;
122124 
122125   /* Allocate a MultiSegReader for each token in the expression. */
122126   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
122127 
122128   /* Determine which, if any, tokens in the expression should be deferred. */
122129 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
122130   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
122131     Fts3TokenAndCost *aTC;
122132     Fts3Expr **apOr;
122133     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
122134         sizeof(Fts3TokenAndCost) * nToken
122135       + sizeof(Fts3Expr *) * nOr * 2
122136     );
122137     apOr = (Fts3Expr **)&aTC[nToken];
122138 
122139     if( !aTC ){
122140       rc = SQLITE_NOMEM;
122141     }else{
122142       int ii;
122143       Fts3TokenAndCost *pTC = aTC;
122144       Fts3Expr **ppOr = apOr;
122145 
122146       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
122147       nToken = (int)(pTC-aTC);
122148       nOr = (int)(ppOr-apOr);
122149 
122150       if( rc==SQLITE_OK ){
122151         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
122152         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
122153           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
122154         }
122155       }
122156 
122157       sqlite3_free(aTC);
122158     }
122159   }
122160 #endif
122161 
122162   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
122163   return rc;
122164 }
122165 
122166 /*
122167 ** Invalidate the current position list for phrase pPhrase.
122168 */
122169 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
122170   if( pPhrase->doclist.bFreeList ){
122171     sqlite3_free(pPhrase->doclist.pList);
122172   }
122173   pPhrase->doclist.pList = 0;
122174   pPhrase->doclist.nList = 0;
122175   pPhrase->doclist.bFreeList = 0;
122176 }
122177 
122178 /*
122179 ** This function is called to edit the position list associated with
122180 ** the phrase object passed as the fifth argument according to a NEAR
122181 ** condition. For example:
122182 **
122183 **     abc NEAR/5 "def ghi"
122184 **
122185 ** Parameter nNear is passed the NEAR distance of the expression (5 in
122186 ** the example above). When this function is called, *paPoslist points to
122187 ** the position list, and *pnToken is the number of phrase tokens in, the
122188 ** phrase on the other side of the NEAR operator to pPhrase. For example,
122189 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
122190 ** the position list associated with phrase "abc".
122191 **
122192 ** All positions in the pPhrase position list that are not sufficiently
122193 ** close to a position in the *paPoslist position list are removed. If this
122194 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
122195 **
122196 ** Before returning, *paPoslist is set to point to the position lsit
122197 ** associated with pPhrase. And *pnToken is set to the number of tokens in
122198 ** pPhrase.
122199 */
122200 static int fts3EvalNearTrim(
122201   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
122202   char *aTmp,                     /* Temporary space to use */
122203   char **paPoslist,               /* IN/OUT: Position list */
122204   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
122205   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
122206 ){
122207   int nParam1 = nNear + pPhrase->nToken;
122208   int nParam2 = nNear + *pnToken;
122209   int nNew;
122210   char *p2;
122211   char *pOut;
122212   int res;
122213 
122214   assert( pPhrase->doclist.pList );
122215 
122216   p2 = pOut = pPhrase->doclist.pList;
122217   res = fts3PoslistNearMerge(
122218     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
122219   );
122220   if( res ){
122221     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
122222     assert( pPhrase->doclist.pList[nNew]=='\0' );
122223     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
122224     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
122225     pPhrase->doclist.nList = nNew;
122226     *paPoslist = pPhrase->doclist.pList;
122227     *pnToken = pPhrase->nToken;
122228   }
122229 
122230   return res;
122231 }
122232 
122233 /*
122234 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
122235 ** Otherwise, it advances the expression passed as the second argument to
122236 ** point to the next matching row in the database. Expressions iterate through
122237 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
122238 ** or descending if it is non-zero.
122239 **
122240 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
122241 ** successful, the following variables in pExpr are set:
122242 **
122243 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
122244 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
122245 **
122246 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
122247 ** at EOF, then the following variables are populated with the position list
122248 ** for the phrase for the visited row:
122249 **
122250 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
122251 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
122252 **
122253 ** It says above that this function advances the expression to the next
122254 ** matching row. This is usually true, but there are the following exceptions:
122255 **
122256 **   1. Deferred tokens are not taken into account. If a phrase consists
122257 **      entirely of deferred tokens, it is assumed to match every row in
122258 **      the db. In this case the position-list is not populated at all.
122259 **
122260 **      Or, if a phrase contains one or more deferred tokens and one or
122261 **      more non-deferred tokens, then the expression is advanced to the
122262 **      next possible match, considering only non-deferred tokens. In other
122263 **      words, if the phrase is "A B C", and "B" is deferred, the expression
122264 **      is advanced to the next row that contains an instance of "A * C",
122265 **      where "*" may match any single token. The position list in this case
122266 **      is populated as for "A * C" before returning.
122267 **
122268 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
122269 **      advanced to point to the next row that matches "x AND y".
122270 **
122271 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
122272 ** really a match, taking into account deferred tokens and NEAR operators.
122273 */
122274 static void fts3EvalNextRow(
122275   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122276   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
122277   int *pRc                        /* IN/OUT: Error code */
122278 ){
122279   if( *pRc==SQLITE_OK ){
122280     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
122281     assert( pExpr->bEof==0 );
122282     pExpr->bStart = 1;
122283 
122284     switch( pExpr->eType ){
122285       case FTSQUERY_NEAR:
122286       case FTSQUERY_AND: {
122287         Fts3Expr *pLeft = pExpr->pLeft;
122288         Fts3Expr *pRight = pExpr->pRight;
122289         assert( !pLeft->bDeferred || !pRight->bDeferred );
122290 
122291         if( pLeft->bDeferred ){
122292           /* LHS is entirely deferred. So we assume it matches every row.
122293           ** Advance the RHS iterator to find the next row visited. */
122294           fts3EvalNextRow(pCsr, pRight, pRc);
122295           pExpr->iDocid = pRight->iDocid;
122296           pExpr->bEof = pRight->bEof;
122297         }else if( pRight->bDeferred ){
122298           /* RHS is entirely deferred. So we assume it matches every row.
122299           ** Advance the LHS iterator to find the next row visited. */
122300           fts3EvalNextRow(pCsr, pLeft, pRc);
122301           pExpr->iDocid = pLeft->iDocid;
122302           pExpr->bEof = pLeft->bEof;
122303         }else{
122304           /* Neither the RHS or LHS are deferred. */
122305           fts3EvalNextRow(pCsr, pLeft, pRc);
122306           fts3EvalNextRow(pCsr, pRight, pRc);
122307           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
122308             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122309             if( iDiff==0 ) break;
122310             if( iDiff<0 ){
122311               fts3EvalNextRow(pCsr, pLeft, pRc);
122312             }else{
122313               fts3EvalNextRow(pCsr, pRight, pRc);
122314             }
122315           }
122316           pExpr->iDocid = pLeft->iDocid;
122317           pExpr->bEof = (pLeft->bEof || pRight->bEof);
122318         }
122319         break;
122320       }
122321 
122322       case FTSQUERY_OR: {
122323         Fts3Expr *pLeft = pExpr->pLeft;
122324         Fts3Expr *pRight = pExpr->pRight;
122325         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122326 
122327         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
122328         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
122329 
122330         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
122331           fts3EvalNextRow(pCsr, pLeft, pRc);
122332         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
122333           fts3EvalNextRow(pCsr, pRight, pRc);
122334         }else{
122335           fts3EvalNextRow(pCsr, pLeft, pRc);
122336           fts3EvalNextRow(pCsr, pRight, pRc);
122337         }
122338 
122339         pExpr->bEof = (pLeft->bEof && pRight->bEof);
122340         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
122341         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
122342           pExpr->iDocid = pLeft->iDocid;
122343         }else{
122344           pExpr->iDocid = pRight->iDocid;
122345         }
122346 
122347         break;
122348       }
122349 
122350       case FTSQUERY_NOT: {
122351         Fts3Expr *pLeft = pExpr->pLeft;
122352         Fts3Expr *pRight = pExpr->pRight;
122353 
122354         if( pRight->bStart==0 ){
122355           fts3EvalNextRow(pCsr, pRight, pRc);
122356           assert( *pRc!=SQLITE_OK || pRight->bStart );
122357         }
122358 
122359         fts3EvalNextRow(pCsr, pLeft, pRc);
122360         if( pLeft->bEof==0 ){
122361           while( !*pRc
122362               && !pRight->bEof
122363               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
122364           ){
122365             fts3EvalNextRow(pCsr, pRight, pRc);
122366           }
122367         }
122368         pExpr->iDocid = pLeft->iDocid;
122369         pExpr->bEof = pLeft->bEof;
122370         break;
122371       }
122372 
122373       default: {
122374         Fts3Phrase *pPhrase = pExpr->pPhrase;
122375         fts3EvalInvalidatePoslist(pPhrase);
122376         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
122377         pExpr->iDocid = pPhrase->doclist.iDocid;
122378         break;
122379       }
122380     }
122381   }
122382 }
122383 
122384 /*
122385 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
122386 ** cluster, then this function returns 1 immediately.
122387 **
122388 ** Otherwise, it checks if the current row really does match the NEAR
122389 ** expression, using the data currently stored in the position lists
122390 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
122391 **
122392 ** If the current row is a match, the position list associated with each
122393 ** phrase in the NEAR expression is edited in place to contain only those
122394 ** phrase instances sufficiently close to their peers to satisfy all NEAR
122395 ** constraints. In this case it returns 1. If the NEAR expression does not
122396 ** match the current row, 0 is returned. The position lists may or may not
122397 ** be edited if 0 is returned.
122398 */
122399 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
122400   int res = 1;
122401 
122402   /* The following block runs if pExpr is the root of a NEAR query.
122403   ** For example, the query:
122404   **
122405   **         "w" NEAR "x" NEAR "y" NEAR "z"
122406   **
122407   ** which is represented in tree form as:
122408   **
122409   **                               |
122410   **                          +--NEAR--+      <-- root of NEAR query
122411   **                          |        |
122412   **                     +--NEAR--+   "z"
122413   **                     |        |
122414   **                +--NEAR--+   "y"
122415   **                |        |
122416   **               "w"      "x"
122417   **
122418   ** The right-hand child of a NEAR node is always a phrase. The
122419   ** left-hand child may be either a phrase or a NEAR node. There are
122420   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
122421   */
122422   if( *pRc==SQLITE_OK
122423    && pExpr->eType==FTSQUERY_NEAR
122424    && pExpr->bEof==0
122425    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
122426   ){
122427     Fts3Expr *p;
122428     int nTmp = 0;                 /* Bytes of temp space */
122429     char *aTmp;                   /* Temp space for PoslistNearMerge() */
122430 
122431     /* Allocate temporary working space. */
122432     for(p=pExpr; p->pLeft; p=p->pLeft){
122433       nTmp += p->pRight->pPhrase->doclist.nList;
122434     }
122435     nTmp += p->pPhrase->doclist.nList;
122436     if( nTmp==0 ){
122437       res = 0;
122438     }else{
122439       aTmp = sqlite3_malloc(nTmp*2);
122440       if( !aTmp ){
122441         *pRc = SQLITE_NOMEM;
122442         res = 0;
122443       }else{
122444         char *aPoslist = p->pPhrase->doclist.pList;
122445         int nToken = p->pPhrase->nToken;
122446 
122447         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
122448           Fts3Phrase *pPhrase = p->pRight->pPhrase;
122449           int nNear = p->nNear;
122450           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
122451         }
122452 
122453         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
122454         nToken = pExpr->pRight->pPhrase->nToken;
122455         for(p=pExpr->pLeft; p && res; p=p->pLeft){
122456           int nNear;
122457           Fts3Phrase *pPhrase;
122458           assert( p->pParent && p->pParent->pLeft==p );
122459           nNear = p->pParent->nNear;
122460           pPhrase = (
122461               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
122462               );
122463           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
122464         }
122465       }
122466 
122467       sqlite3_free(aTmp);
122468     }
122469   }
122470 
122471   return res;
122472 }
122473 
122474 /*
122475 ** This function is a helper function for fts3EvalTestDeferredAndNear().
122476 ** Assuming no error occurs or has occurred, It returns non-zero if the
122477 ** expression passed as the second argument matches the row that pCsr
122478 ** currently points to, or zero if it does not.
122479 **
122480 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
122481 ** If an error occurs during execution of this function, *pRc is set to
122482 ** the appropriate SQLite error code. In this case the returned value is
122483 ** undefined.
122484 */
122485 static int fts3EvalTestExpr(
122486   Fts3Cursor *pCsr,               /* FTS cursor handle */
122487   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
122488   int *pRc                        /* IN/OUT: Error code */
122489 ){
122490   int bHit = 1;                   /* Return value */
122491   if( *pRc==SQLITE_OK ){
122492     switch( pExpr->eType ){
122493       case FTSQUERY_NEAR:
122494       case FTSQUERY_AND:
122495         bHit = (
122496             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
122497          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
122498          && fts3EvalNearTest(pExpr, pRc)
122499         );
122500 
122501         /* If the NEAR expression does not match any rows, zero the doclist for
122502         ** all phrases involved in the NEAR. This is because the snippet(),
122503         ** offsets() and matchinfo() functions are not supposed to recognize
122504         ** any instances of phrases that are part of unmatched NEAR queries.
122505         ** For example if this expression:
122506         **
122507         **    ... MATCH 'a OR (b NEAR c)'
122508         **
122509         ** is matched against a row containing:
122510         **
122511         **        'a b d e'
122512         **
122513         ** then any snippet() should ony highlight the "a" term, not the "b"
122514         ** (as "b" is part of a non-matching NEAR clause).
122515         */
122516         if( bHit==0
122517          && pExpr->eType==FTSQUERY_NEAR
122518          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
122519         ){
122520           Fts3Expr *p;
122521           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
122522             if( p->pRight->iDocid==pCsr->iPrevId ){
122523               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
122524             }
122525           }
122526           if( p->iDocid==pCsr->iPrevId ){
122527             fts3EvalInvalidatePoslist(p->pPhrase);
122528           }
122529         }
122530 
122531         break;
122532 
122533       case FTSQUERY_OR: {
122534         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
122535         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
122536         bHit = bHit1 || bHit2;
122537         break;
122538       }
122539 
122540       case FTSQUERY_NOT:
122541         bHit = (
122542             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
122543          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
122544         );
122545         break;
122546 
122547       default: {
122548 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
122549         if( pCsr->pDeferred
122550          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
122551         ){
122552           Fts3Phrase *pPhrase = pExpr->pPhrase;
122553           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
122554           if( pExpr->bDeferred ){
122555             fts3EvalInvalidatePoslist(pPhrase);
122556           }
122557           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
122558           bHit = (pPhrase->doclist.pList!=0);
122559           pExpr->iDocid = pCsr->iPrevId;
122560         }else
122561 #endif
122562         {
122563           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
122564         }
122565         break;
122566       }
122567     }
122568   }
122569   return bHit;
122570 }
122571 
122572 /*
122573 ** This function is called as the second part of each xNext operation when
122574 ** iterating through the results of a full-text query. At this point the
122575 ** cursor points to a row that matches the query expression, with the
122576 ** following caveats:
122577 **
122578 **   * Up until this point, "NEAR" operators in the expression have been
122579 **     treated as "AND".
122580 **
122581 **   * Deferred tokens have not yet been considered.
122582 **
122583 ** If *pRc is not SQLITE_OK when this function is called, it immediately
122584 ** returns 0. Otherwise, it tests whether or not after considering NEAR
122585 ** operators and deferred tokens the current row is still a match for the
122586 ** expression. It returns 1 if both of the following are true:
122587 **
122588 **   1. *pRc is SQLITE_OK when this function returns, and
122589 **
122590 **   2. After scanning the current FTS table row for the deferred tokens,
122591 **      it is determined that the row does *not* match the query.
122592 **
122593 ** Or, if no error occurs and it seems the current row does match the FTS
122594 ** query, return 0.
122595 */
122596 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
122597   int rc = *pRc;
122598   int bMiss = 0;
122599   if( rc==SQLITE_OK ){
122600 
122601     /* If there are one or more deferred tokens, load the current row into
122602     ** memory and scan it to determine the position list for each deferred
122603     ** token. Then, see if this row is really a match, considering deferred
122604     ** tokens and NEAR operators (neither of which were taken into account
122605     ** earlier, by fts3EvalNextRow()).
122606     */
122607     if( pCsr->pDeferred ){
122608       rc = fts3CursorSeek(0, pCsr);
122609       if( rc==SQLITE_OK ){
122610         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
122611       }
122612     }
122613     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
122614 
122615     /* Free the position-lists accumulated for each deferred token above. */
122616     sqlite3Fts3FreeDeferredDoclists(pCsr);
122617     *pRc = rc;
122618   }
122619   return (rc==SQLITE_OK && bMiss);
122620 }
122621 
122622 /*
122623 ** Advance to the next document that matches the FTS expression in
122624 ** Fts3Cursor.pExpr.
122625 */
122626 static int fts3EvalNext(Fts3Cursor *pCsr){
122627   int rc = SQLITE_OK;             /* Return Code */
122628   Fts3Expr *pExpr = pCsr->pExpr;
122629   assert( pCsr->isEof==0 );
122630   if( pExpr==0 ){
122631     pCsr->isEof = 1;
122632   }else{
122633     do {
122634       if( pCsr->isRequireSeek==0 ){
122635         sqlite3_reset(pCsr->pStmt);
122636       }
122637       assert( sqlite3_data_count(pCsr->pStmt)==0 );
122638       fts3EvalNextRow(pCsr, pExpr, &rc);
122639       pCsr->isEof = pExpr->bEof;
122640       pCsr->isRequireSeek = 1;
122641       pCsr->isMatchinfoNeeded = 1;
122642       pCsr->iPrevId = pExpr->iDocid;
122643     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
122644   }
122645   return rc;
122646 }
122647 
122648 /*
122649 ** Restart interation for expression pExpr so that the next call to
122650 ** fts3EvalNext() visits the first row. Do not allow incremental
122651 ** loading or merging of phrase doclists for this iteration.
122652 **
122653 ** If *pRc is other than SQLITE_OK when this function is called, it is
122654 ** a no-op. If an error occurs within this function, *pRc is set to an
122655 ** SQLite error code before returning.
122656 */
122657 static void fts3EvalRestart(
122658   Fts3Cursor *pCsr,
122659   Fts3Expr *pExpr,
122660   int *pRc
122661 ){
122662   if( pExpr && *pRc==SQLITE_OK ){
122663     Fts3Phrase *pPhrase = pExpr->pPhrase;
122664 
122665     if( pPhrase ){
122666       fts3EvalInvalidatePoslist(pPhrase);
122667       if( pPhrase->bIncr ){
122668         assert( pPhrase->nToken==1 );
122669         assert( pPhrase->aToken[0].pSegcsr );
122670         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
122671         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
122672       }
122673 
122674       pPhrase->doclist.pNextDocid = 0;
122675       pPhrase->doclist.iDocid = 0;
122676     }
122677 
122678     pExpr->iDocid = 0;
122679     pExpr->bEof = 0;
122680     pExpr->bStart = 0;
122681 
122682     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
122683     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
122684   }
122685 }
122686 
122687 /*
122688 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
122689 ** expression rooted at pExpr, the cursor iterates through all rows matched
122690 ** by pExpr, calling this function for each row. This function increments
122691 ** the values in Fts3Expr.aMI[] according to the position-list currently
122692 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
122693 ** expression nodes.
122694 */
122695 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
122696   if( pExpr ){
122697     Fts3Phrase *pPhrase = pExpr->pPhrase;
122698     if( pPhrase && pPhrase->doclist.pList ){
122699       int iCol = 0;
122700       char *p = pPhrase->doclist.pList;
122701 
122702       assert( *p );
122703       while( 1 ){
122704         u8 c = 0;
122705         int iCnt = 0;
122706         while( 0xFE & (*p | c) ){
122707           if( (c&0x80)==0 ) iCnt++;
122708           c = *p++ & 0x80;
122709         }
122710 
122711         /* aMI[iCol*3 + 1] = Number of occurrences
122712         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
122713         */
122714         pExpr->aMI[iCol*3 + 1] += iCnt;
122715         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
122716         if( *p==0x00 ) break;
122717         p++;
122718         p += sqlite3Fts3GetVarint32(p, &iCol);
122719       }
122720     }
122721 
122722     fts3EvalUpdateCounts(pExpr->pLeft);
122723     fts3EvalUpdateCounts(pExpr->pRight);
122724   }
122725 }
122726 
122727 /*
122728 ** Expression pExpr must be of type FTSQUERY_PHRASE.
122729 **
122730 ** If it is not already allocated and populated, this function allocates and
122731 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
122732 ** of a NEAR expression, then it also allocates and populates the same array
122733 ** for all other phrases that are part of the NEAR expression.
122734 **
122735 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
122736 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
122737 */
122738 static int fts3EvalGatherStats(
122739   Fts3Cursor *pCsr,               /* Cursor object */
122740   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
122741 ){
122742   int rc = SQLITE_OK;             /* Return code */
122743 
122744   assert( pExpr->eType==FTSQUERY_PHRASE );
122745   if( pExpr->aMI==0 ){
122746     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122747     Fts3Expr *pRoot;                /* Root of NEAR expression */
122748     Fts3Expr *p;                    /* Iterator used for several purposes */
122749 
122750     sqlite3_int64 iPrevId = pCsr->iPrevId;
122751     sqlite3_int64 iDocid;
122752     u8 bEof;
122753 
122754     /* Find the root of the NEAR expression */
122755     pRoot = pExpr;
122756     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
122757       pRoot = pRoot->pParent;
122758     }
122759     iDocid = pRoot->iDocid;
122760     bEof = pRoot->bEof;
122761     assert( pRoot->bStart );
122762 
122763     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
122764     for(p=pRoot; p; p=p->pLeft){
122765       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
122766       assert( pE->aMI==0 );
122767       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
122768       if( !pE->aMI ) return SQLITE_NOMEM;
122769       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
122770     }
122771 
122772     fts3EvalRestart(pCsr, pRoot, &rc);
122773 
122774     while( pCsr->isEof==0 && rc==SQLITE_OK ){
122775 
122776       do {
122777         /* Ensure the %_content statement is reset. */
122778         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
122779         assert( sqlite3_data_count(pCsr->pStmt)==0 );
122780 
122781         /* Advance to the next document */
122782         fts3EvalNextRow(pCsr, pRoot, &rc);
122783         pCsr->isEof = pRoot->bEof;
122784         pCsr->isRequireSeek = 1;
122785         pCsr->isMatchinfoNeeded = 1;
122786         pCsr->iPrevId = pRoot->iDocid;
122787       }while( pCsr->isEof==0
122788            && pRoot->eType==FTSQUERY_NEAR
122789            && fts3EvalTestDeferredAndNear(pCsr, &rc)
122790       );
122791 
122792       if( rc==SQLITE_OK && pCsr->isEof==0 ){
122793         fts3EvalUpdateCounts(pRoot);
122794       }
122795     }
122796 
122797     pCsr->isEof = 0;
122798     pCsr->iPrevId = iPrevId;
122799 
122800     if( bEof ){
122801       pRoot->bEof = bEof;
122802     }else{
122803       /* Caution: pRoot may iterate through docids in ascending or descending
122804       ** order. For this reason, even though it seems more defensive, the
122805       ** do loop can not be written:
122806       **
122807       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
122808       */
122809       fts3EvalRestart(pCsr, pRoot, &rc);
122810       do {
122811         fts3EvalNextRow(pCsr, pRoot, &rc);
122812         assert( pRoot->bEof==0 );
122813       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
122814       fts3EvalTestDeferredAndNear(pCsr, &rc);
122815     }
122816   }
122817   return rc;
122818 }
122819 
122820 /*
122821 ** This function is used by the matchinfo() module to query a phrase
122822 ** expression node for the following information:
122823 **
122824 **   1. The total number of occurrences of the phrase in each column of
122825 **      the FTS table (considering all rows), and
122826 **
122827 **   2. For each column, the number of rows in the table for which the
122828 **      column contains at least one instance of the phrase.
122829 **
122830 ** If no error occurs, SQLITE_OK is returned and the values for each column
122831 ** written into the array aiOut as follows:
122832 **
122833 **   aiOut[iCol*3 + 1] = Number of occurrences
122834 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
122835 **
122836 ** Caveats:
122837 **
122838 **   * If a phrase consists entirely of deferred tokens, then all output
122839 **     values are set to the number of documents in the table. In other
122840 **     words we assume that very common tokens occur exactly once in each
122841 **     column of each row of the table.
122842 **
122843 **   * If a phrase contains some deferred tokens (and some non-deferred
122844 **     tokens), count the potential occurrence identified by considering
122845 **     the non-deferred tokens instead of actual phrase occurrences.
122846 **
122847 **   * If the phrase is part of a NEAR expression, then only phrase instances
122848 **     that meet the NEAR constraint are included in the counts.
122849 */
122850 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
122851   Fts3Cursor *pCsr,               /* FTS cursor handle */
122852   Fts3Expr *pExpr,                /* Phrase expression */
122853   u32 *aiOut                      /* Array to write results into (see above) */
122854 ){
122855   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122856   int rc = SQLITE_OK;
122857   int iCol;
122858 
122859   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
122860     assert( pCsr->nDoc>0 );
122861     for(iCol=0; iCol<pTab->nColumn; iCol++){
122862       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
122863       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
122864     }
122865   }else{
122866     rc = fts3EvalGatherStats(pCsr, pExpr);
122867     if( rc==SQLITE_OK ){
122868       assert( pExpr->aMI );
122869       for(iCol=0; iCol<pTab->nColumn; iCol++){
122870         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
122871         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
122872       }
122873     }
122874   }
122875 
122876   return rc;
122877 }
122878 
122879 /*
122880 ** The expression pExpr passed as the second argument to this function
122881 ** must be of type FTSQUERY_PHRASE.
122882 **
122883 ** The returned value is either NULL or a pointer to a buffer containing
122884 ** a position-list indicating the occurrences of the phrase in column iCol
122885 ** of the current row.
122886 **
122887 ** More specifically, the returned buffer contains 1 varint for each
122888 ** occurrence of the phrase in the column, stored using the normal (delta+2)
122889 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
122890 ** if the requested column contains "a b X c d X X" and the position-list
122891 ** for 'X' is requested, the buffer returned may contain:
122892 **
122893 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
122894 **
122895 ** This function works regardless of whether or not the phrase is deferred,
122896 ** incremental, or neither.
122897 */
122898 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
122899   Fts3Cursor *pCsr,               /* FTS3 cursor object */
122900   Fts3Expr *pExpr,                /* Phrase to return doclist for */
122901   int iCol,                       /* Column to return position list for */
122902   char **ppOut                    /* OUT: Pointer to position list */
122903 ){
122904   Fts3Phrase *pPhrase = pExpr->pPhrase;
122905   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122906   char *pIter;
122907   int iThis;
122908   sqlite3_int64 iDocid;
122909 
122910   /* If this phrase is applies specifically to some column other than
122911   ** column iCol, return a NULL pointer.  */
122912   *ppOut = 0;
122913   assert( iCol>=0 && iCol<pTab->nColumn );
122914   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
122915     return SQLITE_OK;
122916   }
122917 
122918   iDocid = pExpr->iDocid;
122919   pIter = pPhrase->doclist.pList;
122920   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
122921     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
122922     int bOr = 0;
122923     u8 bEof = 0;
122924     Fts3Expr *p;
122925 
122926     /* Check if this phrase descends from an OR expression node. If not,
122927     ** return NULL. Otherwise, the entry that corresponds to docid
122928     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
122929     for(p=pExpr->pParent; p; p=p->pParent){
122930       if( p->eType==FTSQUERY_OR ) bOr = 1;
122931     }
122932     if( bOr==0 ) return SQLITE_OK;
122933 
122934     /* This is the descendent of an OR node. In this case we cannot use
122935     ** an incremental phrase. Load the entire doclist for the phrase
122936     ** into memory in this case.  */
122937     if( pPhrase->bIncr ){
122938       int rc = SQLITE_OK;
122939       int bEofSave = pExpr->bEof;
122940       fts3EvalRestart(pCsr, pExpr, &rc);
122941       while( rc==SQLITE_OK && !pExpr->bEof ){
122942         fts3EvalNextRow(pCsr, pExpr, &rc);
122943         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
122944       }
122945       pIter = pPhrase->doclist.pList;
122946       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
122947       if( rc!=SQLITE_OK ) return rc;
122948     }
122949 
122950     if( pExpr->bEof ){
122951       pIter = 0;
122952       iDocid = 0;
122953     }
122954     bEof = (pPhrase->doclist.nAll==0);
122955     assert( bDescDoclist==0 || bDescDoclist==1 );
122956     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
122957 
122958     if( pCsr->bDesc==bDescDoclist ){
122959       int dummy;
122960       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
122961         sqlite3Fts3DoclistPrev(
122962             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
122963             &pIter, &iDocid, &dummy, &bEof
122964         );
122965       }
122966     }else{
122967       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
122968         sqlite3Fts3DoclistNext(
122969             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
122970             &pIter, &iDocid, &bEof
122971         );
122972       }
122973     }
122974 
122975     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
122976   }
122977   if( pIter==0 ) return SQLITE_OK;
122978 
122979   if( *pIter==0x01 ){
122980     pIter++;
122981     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
122982   }else{
122983     iThis = 0;
122984   }
122985   while( iThis<iCol ){
122986     fts3ColumnlistCopy(0, &pIter);
122987     if( *pIter==0x00 ) return 0;
122988     pIter++;
122989     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
122990   }
122991 
122992   *ppOut = ((iCol==iThis)?pIter:0);
122993   return SQLITE_OK;
122994 }
122995 
122996 /*
122997 ** Free all components of the Fts3Phrase structure that were allocated by
122998 ** the eval module. Specifically, this means to free:
122999 **
123000 **   * the contents of pPhrase->doclist, and
123001 **   * any Fts3MultiSegReader objects held by phrase tokens.
123002 */
123003 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
123004   if( pPhrase ){
123005     int i;
123006     sqlite3_free(pPhrase->doclist.aAll);
123007     fts3EvalInvalidatePoslist(pPhrase);
123008     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
123009     for(i=0; i<pPhrase->nToken; i++){
123010       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
123011       pPhrase->aToken[i].pSegcsr = 0;
123012     }
123013   }
123014 }
123015 
123016 
123017 /*
123018 ** Return SQLITE_CORRUPT_VTAB.
123019 */
123020 #ifdef SQLITE_DEBUG
123021 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
123022   return SQLITE_CORRUPT_VTAB;
123023 }
123024 #endif
123025 
123026 #if !SQLITE_CORE
123027 /*
123028 ** Initialize API pointer table, if required.
123029 */
123030 SQLITE_API int sqlite3_extension_init(
123031   sqlite3 *db,
123032   char **pzErrMsg,
123033   const sqlite3_api_routines *pApi
123034 ){
123035   SQLITE_EXTENSION_INIT2(pApi)
123036   return sqlite3Fts3Init(db);
123037 }
123038 #endif
123039 
123040 #endif
123041 
123042 /************** End of fts3.c ************************************************/
123043 /************** Begin file fts3_aux.c ****************************************/
123044 /*
123045 ** 2011 Jan 27
123046 **
123047 ** The author disclaims copyright to this source code.  In place of
123048 ** a legal notice, here is a blessing:
123049 **
123050 **    May you do good and not evil.
123051 **    May you find forgiveness for yourself and forgive others.
123052 **    May you share freely, never taking more than you give.
123053 **
123054 ******************************************************************************
123055 **
123056 */
123057 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123058 
123059 /* #include <string.h> */
123060 /* #include <assert.h> */
123061 
123062 typedef struct Fts3auxTable Fts3auxTable;
123063 typedef struct Fts3auxCursor Fts3auxCursor;
123064 
123065 struct Fts3auxTable {
123066   sqlite3_vtab base;              /* Base class used by SQLite core */
123067   Fts3Table *pFts3Tab;
123068 };
123069 
123070 struct Fts3auxCursor {
123071   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
123072   Fts3MultiSegReader csr;        /* Must be right after "base" */
123073   Fts3SegFilter filter;
123074   char *zStop;
123075   int nStop;                      /* Byte-length of string zStop */
123076   int isEof;                      /* True if cursor is at EOF */
123077   sqlite3_int64 iRowid;           /* Current rowid */
123078 
123079   int iCol;                       /* Current value of 'col' column */
123080   int nStat;                      /* Size of aStat[] array */
123081   struct Fts3auxColstats {
123082     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
123083     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
123084   } *aStat;
123085 };
123086 
123087 /*
123088 ** Schema of the terms table.
123089 */
123090 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
123091 
123092 /*
123093 ** This function does all the work for both the xConnect and xCreate methods.
123094 ** These tables have no persistent representation of their own, so xConnect
123095 ** and xCreate are identical operations.
123096 */
123097 static int fts3auxConnectMethod(
123098   sqlite3 *db,                    /* Database connection */
123099   void *pUnused,                  /* Unused */
123100   int argc,                       /* Number of elements in argv array */
123101   const char * const *argv,       /* xCreate/xConnect argument array */
123102   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
123103   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
123104 ){
123105   char const *zDb;                /* Name of database (e.g. "main") */
123106   char const *zFts3;              /* Name of fts3 table */
123107   int nDb;                        /* Result of strlen(zDb) */
123108   int nFts3;                      /* Result of strlen(zFts3) */
123109   int nByte;                      /* Bytes of space to allocate here */
123110   int rc;                         /* value returned by declare_vtab() */
123111   Fts3auxTable *p;                /* Virtual table object to return */
123112 
123113   UNUSED_PARAMETER(pUnused);
123114 
123115   /* The user should specify a single argument - the name of an fts3 table. */
123116   if( argc!=4 ){
123117     *pzErr = sqlite3_mprintf(
123118         "wrong number of arguments to fts4aux constructor"
123119     );
123120     return SQLITE_ERROR;
123121   }
123122 
123123   zDb = argv[1];
123124   nDb = (int)strlen(zDb);
123125   zFts3 = argv[3];
123126   nFts3 = (int)strlen(zFts3);
123127 
123128   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
123129   if( rc!=SQLITE_OK ) return rc;
123130 
123131   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
123132   p = (Fts3auxTable *)sqlite3_malloc(nByte);
123133   if( !p ) return SQLITE_NOMEM;
123134   memset(p, 0, nByte);
123135 
123136   p->pFts3Tab = (Fts3Table *)&p[1];
123137   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
123138   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
123139   p->pFts3Tab->db = db;
123140   p->pFts3Tab->nIndex = 1;
123141 
123142   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
123143   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
123144   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
123145 
123146   *ppVtab = (sqlite3_vtab *)p;
123147   return SQLITE_OK;
123148 }
123149 
123150 /*
123151 ** This function does the work for both the xDisconnect and xDestroy methods.
123152 ** These tables have no persistent representation of their own, so xDisconnect
123153 ** and xDestroy are identical operations.
123154 */
123155 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
123156   Fts3auxTable *p = (Fts3auxTable *)pVtab;
123157   Fts3Table *pFts3 = p->pFts3Tab;
123158   int i;
123159 
123160   /* Free any prepared statements held */
123161   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
123162     sqlite3_finalize(pFts3->aStmt[i]);
123163   }
123164   sqlite3_free(pFts3->zSegmentsTbl);
123165   sqlite3_free(p);
123166   return SQLITE_OK;
123167 }
123168 
123169 #define FTS4AUX_EQ_CONSTRAINT 1
123170 #define FTS4AUX_GE_CONSTRAINT 2
123171 #define FTS4AUX_LE_CONSTRAINT 4
123172 
123173 /*
123174 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
123175 */
123176 static int fts3auxBestIndexMethod(
123177   sqlite3_vtab *pVTab,
123178   sqlite3_index_info *pInfo
123179 ){
123180   int i;
123181   int iEq = -1;
123182   int iGe = -1;
123183   int iLe = -1;
123184 
123185   UNUSED_PARAMETER(pVTab);
123186 
123187   /* This vtab delivers always results in "ORDER BY term ASC" order. */
123188   if( pInfo->nOrderBy==1
123189    && pInfo->aOrderBy[0].iColumn==0
123190    && pInfo->aOrderBy[0].desc==0
123191   ){
123192     pInfo->orderByConsumed = 1;
123193   }
123194 
123195   /* Search for equality and range constraints on the "term" column. */
123196   for(i=0; i<pInfo->nConstraint; i++){
123197     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
123198       int op = pInfo->aConstraint[i].op;
123199       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
123200       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
123201       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
123202       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
123203       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
123204     }
123205   }
123206 
123207   if( iEq>=0 ){
123208     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
123209     pInfo->aConstraintUsage[iEq].argvIndex = 1;
123210     pInfo->estimatedCost = 5;
123211   }else{
123212     pInfo->idxNum = 0;
123213     pInfo->estimatedCost = 20000;
123214     if( iGe>=0 ){
123215       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
123216       pInfo->aConstraintUsage[iGe].argvIndex = 1;
123217       pInfo->estimatedCost /= 2;
123218     }
123219     if( iLe>=0 ){
123220       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
123221       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
123222       pInfo->estimatedCost /= 2;
123223     }
123224   }
123225 
123226   return SQLITE_OK;
123227 }
123228 
123229 /*
123230 ** xOpen - Open a cursor.
123231 */
123232 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
123233   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
123234 
123235   UNUSED_PARAMETER(pVTab);
123236 
123237   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
123238   if( !pCsr ) return SQLITE_NOMEM;
123239   memset(pCsr, 0, sizeof(Fts3auxCursor));
123240 
123241   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
123242   return SQLITE_OK;
123243 }
123244 
123245 /*
123246 ** xClose - Close a cursor.
123247 */
123248 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
123249   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123250   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123251 
123252   sqlite3Fts3SegmentsClose(pFts3);
123253   sqlite3Fts3SegReaderFinish(&pCsr->csr);
123254   sqlite3_free((void *)pCsr->filter.zTerm);
123255   sqlite3_free(pCsr->zStop);
123256   sqlite3_free(pCsr->aStat);
123257   sqlite3_free(pCsr);
123258   return SQLITE_OK;
123259 }
123260 
123261 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
123262   if( nSize>pCsr->nStat ){
123263     struct Fts3auxColstats *aNew;
123264     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
123265         sizeof(struct Fts3auxColstats) * nSize
123266     );
123267     if( aNew==0 ) return SQLITE_NOMEM;
123268     memset(&aNew[pCsr->nStat], 0,
123269         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
123270     );
123271     pCsr->aStat = aNew;
123272     pCsr->nStat = nSize;
123273   }
123274   return SQLITE_OK;
123275 }
123276 
123277 /*
123278 ** xNext - Advance the cursor to the next row, if any.
123279 */
123280 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
123281   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123282   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123283   int rc;
123284 
123285   /* Increment our pretend rowid value. */
123286   pCsr->iRowid++;
123287 
123288   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
123289     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
123290   }
123291 
123292   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
123293   if( rc==SQLITE_ROW ){
123294     int i = 0;
123295     int nDoclist = pCsr->csr.nDoclist;
123296     char *aDoclist = pCsr->csr.aDoclist;
123297     int iCol;
123298 
123299     int eState = 0;
123300 
123301     if( pCsr->zStop ){
123302       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
123303       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
123304       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
123305         pCsr->isEof = 1;
123306         return SQLITE_OK;
123307       }
123308     }
123309 
123310     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
123311     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
123312     iCol = 0;
123313 
123314     while( i<nDoclist ){
123315       sqlite3_int64 v = 0;
123316 
123317       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
123318       switch( eState ){
123319         /* State 0. In this state the integer just read was a docid. */
123320         case 0:
123321           pCsr->aStat[0].nDoc++;
123322           eState = 1;
123323           iCol = 0;
123324           break;
123325 
123326         /* State 1. In this state we are expecting either a 1, indicating
123327         ** that the following integer will be a column number, or the
123328         ** start of a position list for column 0.
123329         **
123330         ** The only difference between state 1 and state 2 is that if the
123331         ** integer encountered in state 1 is not 0 or 1, then we need to
123332         ** increment the column 0 "nDoc" count for this term.
123333         */
123334         case 1:
123335           assert( iCol==0 );
123336           if( v>1 ){
123337             pCsr->aStat[1].nDoc++;
123338           }
123339           eState = 2;
123340           /* fall through */
123341 
123342         case 2:
123343           if( v==0 ){       /* 0x00. Next integer will be a docid. */
123344             eState = 0;
123345           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
123346             eState = 3;
123347           }else{            /* 2 or greater. A position. */
123348             pCsr->aStat[iCol+1].nOcc++;
123349             pCsr->aStat[0].nOcc++;
123350           }
123351           break;
123352 
123353         /* State 3. The integer just read is a column number. */
123354         default: assert( eState==3 );
123355           iCol = (int)v;
123356           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
123357           pCsr->aStat[iCol+1].nDoc++;
123358           eState = 2;
123359           break;
123360       }
123361     }
123362 
123363     pCsr->iCol = 0;
123364     rc = SQLITE_OK;
123365   }else{
123366     pCsr->isEof = 1;
123367   }
123368   return rc;
123369 }
123370 
123371 /*
123372 ** xFilter - Initialize a cursor to point at the start of its data.
123373 */
123374 static int fts3auxFilterMethod(
123375   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
123376   int idxNum,                     /* Strategy index */
123377   const char *idxStr,             /* Unused */
123378   int nVal,                       /* Number of elements in apVal */
123379   sqlite3_value **apVal           /* Arguments for the indexing scheme */
123380 ){
123381   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123382   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
123383   int rc;
123384   int isScan;
123385 
123386   UNUSED_PARAMETER(nVal);
123387   UNUSED_PARAMETER(idxStr);
123388 
123389   assert( idxStr==0 );
123390   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
123391        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
123392        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
123393   );
123394   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
123395 
123396   /* In case this cursor is being reused, close and zero it. */
123397   testcase(pCsr->filter.zTerm);
123398   sqlite3Fts3SegReaderFinish(&pCsr->csr);
123399   sqlite3_free((void *)pCsr->filter.zTerm);
123400   sqlite3_free(pCsr->aStat);
123401   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
123402 
123403   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
123404   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
123405 
123406   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
123407     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
123408     if( zStr ){
123409       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
123410       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
123411       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
123412     }
123413   }
123414   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
123415     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
123416     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
123417     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
123418     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
123419   }
123420 
123421   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
123422       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
123423   );
123424   if( rc==SQLITE_OK ){
123425     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
123426   }
123427 
123428   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
123429   return rc;
123430 }
123431 
123432 /*
123433 ** xEof - Return true if the cursor is at EOF, or false otherwise.
123434 */
123435 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
123436   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123437   return pCsr->isEof;
123438 }
123439 
123440 /*
123441 ** xColumn - Return a column value.
123442 */
123443 static int fts3auxColumnMethod(
123444   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
123445   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
123446   int iCol                        /* Index of column to read value from */
123447 ){
123448   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
123449 
123450   assert( p->isEof==0 );
123451   if( iCol==0 ){        /* Column "term" */
123452     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
123453   }else if( iCol==1 ){  /* Column "col" */
123454     if( p->iCol ){
123455       sqlite3_result_int(pContext, p->iCol-1);
123456     }else{
123457       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
123458     }
123459   }else if( iCol==2 ){  /* Column "documents" */
123460     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
123461   }else{                /* Column "occurrences" */
123462     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
123463   }
123464 
123465   return SQLITE_OK;
123466 }
123467 
123468 /*
123469 ** xRowid - Return the current rowid for the cursor.
123470 */
123471 static int fts3auxRowidMethod(
123472   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
123473   sqlite_int64 *pRowid            /* OUT: Rowid value */
123474 ){
123475   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
123476   *pRowid = pCsr->iRowid;
123477   return SQLITE_OK;
123478 }
123479 
123480 /*
123481 ** Register the fts3aux module with database connection db. Return SQLITE_OK
123482 ** if successful or an error code if sqlite3_create_module() fails.
123483 */
123484 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
123485   static const sqlite3_module fts3aux_module = {
123486      0,                           /* iVersion      */
123487      fts3auxConnectMethod,        /* xCreate       */
123488      fts3auxConnectMethod,        /* xConnect      */
123489      fts3auxBestIndexMethod,      /* xBestIndex    */
123490      fts3auxDisconnectMethod,     /* xDisconnect   */
123491      fts3auxDisconnectMethod,     /* xDestroy      */
123492      fts3auxOpenMethod,           /* xOpen         */
123493      fts3auxCloseMethod,          /* xClose        */
123494      fts3auxFilterMethod,         /* xFilter       */
123495      fts3auxNextMethod,           /* xNext         */
123496      fts3auxEofMethod,            /* xEof          */
123497      fts3auxColumnMethod,         /* xColumn       */
123498      fts3auxRowidMethod,          /* xRowid        */
123499      0,                           /* xUpdate       */
123500      0,                           /* xBegin        */
123501      0,                           /* xSync         */
123502      0,                           /* xCommit       */
123503      0,                           /* xRollback     */
123504      0,                           /* xFindFunction */
123505      0,                           /* xRename       */
123506      0,                           /* xSavepoint    */
123507      0,                           /* xRelease      */
123508      0                            /* xRollbackTo   */
123509   };
123510   int rc;                         /* Return code */
123511 
123512   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
123513   return rc;
123514 }
123515 
123516 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123517 
123518 /************** End of fts3_aux.c ********************************************/
123519 /************** Begin file fts3_expr.c ***************************************/
123520 /*
123521 ** 2008 Nov 28
123522 **
123523 ** The author disclaims copyright to this source code.  In place of
123524 ** a legal notice, here is a blessing:
123525 **
123526 **    May you do good and not evil.
123527 **    May you find forgiveness for yourself and forgive others.
123528 **    May you share freely, never taking more than you give.
123529 **
123530 ******************************************************************************
123531 **
123532 ** This module contains code that implements a parser for fts3 query strings
123533 ** (the right-hand argument to the MATCH operator). Because the supported
123534 ** syntax is relatively simple, the whole tokenizer/parser system is
123535 ** hand-coded.
123536 */
123537 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123538 
123539 /*
123540 ** By default, this module parses the legacy syntax that has been
123541 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
123542 ** is defined, then it uses the new syntax. The differences between
123543 ** the new and the old syntaxes are:
123544 **
123545 **  a) The new syntax supports parenthesis. The old does not.
123546 **
123547 **  b) The new syntax supports the AND and NOT operators. The old does not.
123548 **
123549 **  c) The old syntax supports the "-" token qualifier. This is not
123550 **     supported by the new syntax (it is replaced by the NOT operator).
123551 **
123552 **  d) When using the old syntax, the OR operator has a greater precedence
123553 **     than an implicit AND. When using the new, both implicity and explicit
123554 **     AND operators have a higher precedence than OR.
123555 **
123556 ** If compiled with SQLITE_TEST defined, then this module exports the
123557 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
123558 ** to zero causes the module to use the old syntax. If it is set to
123559 ** non-zero the new syntax is activated. This is so both syntaxes can
123560 ** be tested using a single build of testfixture.
123561 **
123562 ** The following describes the syntax supported by the fts3 MATCH
123563 ** operator in a similar format to that used by the lemon parser
123564 ** generator. This module does not use actually lemon, it uses a
123565 ** custom parser.
123566 **
123567 **   query ::= andexpr (OR andexpr)*.
123568 **
123569 **   andexpr ::= notexpr (AND? notexpr)*.
123570 **
123571 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
123572 **   notexpr ::= LP query RP.
123573 **
123574 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
123575 **
123576 **   distance_opt ::= .
123577 **   distance_opt ::= / INTEGER.
123578 **
123579 **   phrase ::= TOKEN.
123580 **   phrase ::= COLUMN:TOKEN.
123581 **   phrase ::= "TOKEN TOKEN TOKEN...".
123582 */
123583 
123584 #ifdef SQLITE_TEST
123585 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
123586 #else
123587 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
123588 #  define sqlite3_fts3_enable_parentheses 1
123589 # else
123590 #  define sqlite3_fts3_enable_parentheses 0
123591 # endif
123592 #endif
123593 
123594 /*
123595 ** Default span for NEAR operators.
123596 */
123597 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
123598 
123599 /* #include <string.h> */
123600 /* #include <assert.h> */
123601 
123602 /*
123603 ** isNot:
123604 **   This variable is used by function getNextNode(). When getNextNode() is
123605 **   called, it sets ParseContext.isNot to true if the 'next node' is a
123606 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
123607 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
123608 **   zero.
123609 */
123610 typedef struct ParseContext ParseContext;
123611 struct ParseContext {
123612   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
123613   int iLangid;                        /* Language id used with tokenizer */
123614   const char **azCol;                 /* Array of column names for fts3 table */
123615   int bFts4;                          /* True to allow FTS4-only syntax */
123616   int nCol;                           /* Number of entries in azCol[] */
123617   int iDefaultCol;                    /* Default column to query */
123618   int isNot;                          /* True if getNextNode() sees a unary - */
123619   sqlite3_context *pCtx;              /* Write error message here */
123620   int nNest;                          /* Number of nested brackets */
123621 };
123622 
123623 /*
123624 ** This function is equivalent to the standard isspace() function.
123625 **
123626 ** The standard isspace() can be awkward to use safely, because although it
123627 ** is defined to accept an argument of type int, its behavior when passed
123628 ** an integer that falls outside of the range of the unsigned char type
123629 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
123630 ** is defined to accept an argument of type char, and always returns 0 for
123631 ** any values that fall outside of the range of the unsigned char type (i.e.
123632 ** negative values).
123633 */
123634 static int fts3isspace(char c){
123635   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
123636 }
123637 
123638 /*
123639 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
123640 ** zero the memory before returning a pointer to it. If unsuccessful,
123641 ** return NULL.
123642 */
123643 static void *fts3MallocZero(int nByte){
123644   void *pRet = sqlite3_malloc(nByte);
123645   if( pRet ) memset(pRet, 0, nByte);
123646   return pRet;
123647 }
123648 
123649 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
123650   sqlite3_tokenizer *pTokenizer,
123651   int iLangid,
123652   const char *z,
123653   int n,
123654   sqlite3_tokenizer_cursor **ppCsr
123655 ){
123656   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123657   sqlite3_tokenizer_cursor *pCsr = 0;
123658   int rc;
123659 
123660   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
123661   assert( rc==SQLITE_OK || pCsr==0 );
123662   if( rc==SQLITE_OK ){
123663     pCsr->pTokenizer = pTokenizer;
123664     if( pModule->iVersion>=1 ){
123665       rc = pModule->xLanguageid(pCsr, iLangid);
123666       if( rc!=SQLITE_OK ){
123667         pModule->xClose(pCsr);
123668         pCsr = 0;
123669       }
123670     }
123671   }
123672   *ppCsr = pCsr;
123673   return rc;
123674 }
123675 
123676 
123677 /*
123678 ** Extract the next token from buffer z (length n) using the tokenizer
123679 ** and other information (column names etc.) in pParse. Create an Fts3Expr
123680 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
123681 ** single token and set *ppExpr to point to it. If the end of the buffer is
123682 ** reached before a token is found, set *ppExpr to zero. It is the
123683 ** responsibility of the caller to eventually deallocate the allocated
123684 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
123685 **
123686 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
123687 ** fails.
123688 */
123689 static int getNextToken(
123690   ParseContext *pParse,                   /* fts3 query parse context */
123691   int iCol,                               /* Value for Fts3Phrase.iColumn */
123692   const char *z, int n,                   /* Input string */
123693   Fts3Expr **ppExpr,                      /* OUT: expression */
123694   int *pnConsumed                         /* OUT: Number of bytes consumed */
123695 ){
123696   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123697   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123698   int rc;
123699   sqlite3_tokenizer_cursor *pCursor;
123700   Fts3Expr *pRet = 0;
123701   int nConsumed = 0;
123702 
123703   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
123704   if( rc==SQLITE_OK ){
123705     const char *zToken;
123706     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
123707     int nByte;                               /* total space to allocate */
123708 
123709     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
123710     if( rc==SQLITE_OK ){
123711       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
123712       pRet = (Fts3Expr *)fts3MallocZero(nByte);
123713       if( !pRet ){
123714         rc = SQLITE_NOMEM;
123715       }else{
123716         pRet->eType = FTSQUERY_PHRASE;
123717         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
123718         pRet->pPhrase->nToken = 1;
123719         pRet->pPhrase->iColumn = iCol;
123720         pRet->pPhrase->aToken[0].n = nToken;
123721         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
123722         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
123723 
123724         if( iEnd<n && z[iEnd]=='*' ){
123725           pRet->pPhrase->aToken[0].isPrefix = 1;
123726           iEnd++;
123727         }
123728 
123729         while( 1 ){
123730           if( !sqlite3_fts3_enable_parentheses
123731            && iStart>0 && z[iStart-1]=='-'
123732           ){
123733             pParse->isNot = 1;
123734             iStart--;
123735           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
123736             pRet->pPhrase->aToken[0].bFirst = 1;
123737             iStart--;
123738           }else{
123739             break;
123740           }
123741         }
123742 
123743       }
123744       nConsumed = iEnd;
123745     }
123746 
123747     pModule->xClose(pCursor);
123748   }
123749 
123750   *pnConsumed = nConsumed;
123751   *ppExpr = pRet;
123752   return rc;
123753 }
123754 
123755 
123756 /*
123757 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
123758 ** then free the old allocation.
123759 */
123760 static void *fts3ReallocOrFree(void *pOrig, int nNew){
123761   void *pRet = sqlite3_realloc(pOrig, nNew);
123762   if( !pRet ){
123763     sqlite3_free(pOrig);
123764   }
123765   return pRet;
123766 }
123767 
123768 /*
123769 ** Buffer zInput, length nInput, contains the contents of a quoted string
123770 ** that appeared as part of an fts3 query expression. Neither quote character
123771 ** is included in the buffer. This function attempts to tokenize the entire
123772 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
123773 ** containing the results.
123774 **
123775 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
123776 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
123777 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
123778 ** to 0.
123779 */
123780 static int getNextString(
123781   ParseContext *pParse,                   /* fts3 query parse context */
123782   const char *zInput, int nInput,         /* Input string */
123783   Fts3Expr **ppExpr                       /* OUT: expression */
123784 ){
123785   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
123786   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123787   int rc;
123788   Fts3Expr *p = 0;
123789   sqlite3_tokenizer_cursor *pCursor = 0;
123790   char *zTemp = 0;
123791   int nTemp = 0;
123792 
123793   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
123794   int nToken = 0;
123795 
123796   /* The final Fts3Expr data structure, including the Fts3Phrase,
123797   ** Fts3PhraseToken structures token buffers are all stored as a single
123798   ** allocation so that the expression can be freed with a single call to
123799   ** sqlite3_free(). Setting this up requires a two pass approach.
123800   **
123801   ** The first pass, in the block below, uses a tokenizer cursor to iterate
123802   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
123803   ** to assemble data in two dynamic buffers:
123804   **
123805   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
123806   **             structure, followed by the array of Fts3PhraseToken
123807   **             structures. This pass only populates the Fts3PhraseToken array.
123808   **
123809   **   Buffer zTemp: Contains copies of all tokens.
123810   **
123811   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
123812   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
123813   ** structures.
123814   */
123815   rc = sqlite3Fts3OpenTokenizer(
123816       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
123817   if( rc==SQLITE_OK ){
123818     int ii;
123819     for(ii=0; rc==SQLITE_OK; ii++){
123820       const char *zByte;
123821       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
123822       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
123823       if( rc==SQLITE_OK ){
123824         Fts3PhraseToken *pToken;
123825 
123826         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
123827         if( !p ) goto no_mem;
123828 
123829         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
123830         if( !zTemp ) goto no_mem;
123831 
123832         assert( nToken==ii );
123833         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
123834         memset(pToken, 0, sizeof(Fts3PhraseToken));
123835 
123836         memcpy(&zTemp[nTemp], zByte, nByte);
123837         nTemp += nByte;
123838 
123839         pToken->n = nByte;
123840         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
123841         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
123842         nToken = ii+1;
123843       }
123844     }
123845 
123846     pModule->xClose(pCursor);
123847     pCursor = 0;
123848   }
123849 
123850   if( rc==SQLITE_DONE ){
123851     int jj;
123852     char *zBuf = 0;
123853 
123854     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
123855     if( !p ) goto no_mem;
123856     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
123857     p->eType = FTSQUERY_PHRASE;
123858     p->pPhrase = (Fts3Phrase *)&p[1];
123859     p->pPhrase->iColumn = pParse->iDefaultCol;
123860     p->pPhrase->nToken = nToken;
123861 
123862     zBuf = (char *)&p->pPhrase->aToken[nToken];
123863     if( zTemp ){
123864       memcpy(zBuf, zTemp, nTemp);
123865       sqlite3_free(zTemp);
123866     }else{
123867       assert( nTemp==0 );
123868     }
123869 
123870     for(jj=0; jj<p->pPhrase->nToken; jj++){
123871       p->pPhrase->aToken[jj].z = zBuf;
123872       zBuf += p->pPhrase->aToken[jj].n;
123873     }
123874     rc = SQLITE_OK;
123875   }
123876 
123877   *ppExpr = p;
123878   return rc;
123879 no_mem:
123880 
123881   if( pCursor ){
123882     pModule->xClose(pCursor);
123883   }
123884   sqlite3_free(zTemp);
123885   sqlite3_free(p);
123886   *ppExpr = 0;
123887   return SQLITE_NOMEM;
123888 }
123889 
123890 /*
123891 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
123892 ** call fts3ExprParse(). So this forward declaration is required.
123893 */
123894 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
123895 
123896 /*
123897 ** The output variable *ppExpr is populated with an allocated Fts3Expr
123898 ** structure, or set to 0 if the end of the input buffer is reached.
123899 **
123900 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
123901 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
123902 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
123903 */
123904 static int getNextNode(
123905   ParseContext *pParse,                   /* fts3 query parse context */
123906   const char *z, int n,                   /* Input string */
123907   Fts3Expr **ppExpr,                      /* OUT: expression */
123908   int *pnConsumed                         /* OUT: Number of bytes consumed */
123909 ){
123910   static const struct Fts3Keyword {
123911     char *z;                              /* Keyword text */
123912     unsigned char n;                      /* Length of the keyword */
123913     unsigned char parenOnly;              /* Only valid in paren mode */
123914     unsigned char eType;                  /* Keyword code */
123915   } aKeyword[] = {
123916     { "OR" ,  2, 0, FTSQUERY_OR   },
123917     { "AND",  3, 1, FTSQUERY_AND  },
123918     { "NOT",  3, 1, FTSQUERY_NOT  },
123919     { "NEAR", 4, 0, FTSQUERY_NEAR }
123920   };
123921   int ii;
123922   int iCol;
123923   int iColLen;
123924   int rc;
123925   Fts3Expr *pRet = 0;
123926 
123927   const char *zInput = z;
123928   int nInput = n;
123929 
123930   pParse->isNot = 0;
123931 
123932   /* Skip over any whitespace before checking for a keyword, an open or
123933   ** close bracket, or a quoted string.
123934   */
123935   while( nInput>0 && fts3isspace(*zInput) ){
123936     nInput--;
123937     zInput++;
123938   }
123939   if( nInput==0 ){
123940     return SQLITE_DONE;
123941   }
123942 
123943   /* See if we are dealing with a keyword. */
123944   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
123945     const struct Fts3Keyword *pKey = &aKeyword[ii];
123946 
123947     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
123948       continue;
123949     }
123950 
123951     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
123952       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
123953       int nKey = pKey->n;
123954       char cNext;
123955 
123956       /* If this is a "NEAR" keyword, check for an explicit nearness. */
123957       if( pKey->eType==FTSQUERY_NEAR ){
123958         assert( nKey==4 );
123959         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
123960           nNear = 0;
123961           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
123962             nNear = nNear * 10 + (zInput[nKey] - '0');
123963           }
123964         }
123965       }
123966 
123967       /* At this point this is probably a keyword. But for that to be true,
123968       ** the next byte must contain either whitespace, an open or close
123969       ** parenthesis, a quote character, or EOF.
123970       */
123971       cNext = zInput[nKey];
123972       if( fts3isspace(cNext)
123973        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
123974       ){
123975         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
123976         if( !pRet ){
123977           return SQLITE_NOMEM;
123978         }
123979         pRet->eType = pKey->eType;
123980         pRet->nNear = nNear;
123981         *ppExpr = pRet;
123982         *pnConsumed = (int)((zInput - z) + nKey);
123983         return SQLITE_OK;
123984       }
123985 
123986       /* Turns out that wasn't a keyword after all. This happens if the
123987       ** user has supplied a token such as "ORacle". Continue.
123988       */
123989     }
123990   }
123991 
123992   /* Check for an open bracket. */
123993   if( sqlite3_fts3_enable_parentheses ){
123994     if( *zInput=='(' ){
123995       int nConsumed;
123996       pParse->nNest++;
123997       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
123998       if( rc==SQLITE_OK && !*ppExpr ){
123999         rc = SQLITE_DONE;
124000       }
124001       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
124002       return rc;
124003     }
124004 
124005     /* Check for a close bracket. */
124006     if( *zInput==')' ){
124007       pParse->nNest--;
124008       *pnConsumed = (int)((zInput - z) + 1);
124009       return SQLITE_DONE;
124010     }
124011   }
124012 
124013   /* See if we are dealing with a quoted phrase. If this is the case, then
124014   ** search for the closing quote and pass the whole string to getNextString()
124015   ** for processing. This is easy to do, as fts3 has no syntax for escaping
124016   ** a quote character embedded in a string.
124017   */
124018   if( *zInput=='"' ){
124019     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
124020     *pnConsumed = (int)((zInput - z) + ii + 1);
124021     if( ii==nInput ){
124022       return SQLITE_ERROR;
124023     }
124024     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
124025   }
124026 
124027 
124028   /* If control flows to this point, this must be a regular token, or
124029   ** the end of the input. Read a regular token using the sqlite3_tokenizer
124030   ** interface. Before doing so, figure out if there is an explicit
124031   ** column specifier for the token.
124032   **
124033   ** TODO: Strangely, it is not possible to associate a column specifier
124034   ** with a quoted phrase, only with a single token. Not sure if this was
124035   ** an implementation artifact or an intentional decision when fts3 was
124036   ** first implemented. Whichever it was, this module duplicates the
124037   ** limitation.
124038   */
124039   iCol = pParse->iDefaultCol;
124040   iColLen = 0;
124041   for(ii=0; ii<pParse->nCol; ii++){
124042     const char *zStr = pParse->azCol[ii];
124043     int nStr = (int)strlen(zStr);
124044     if( nInput>nStr && zInput[nStr]==':'
124045      && sqlite3_strnicmp(zStr, zInput, nStr)==0
124046     ){
124047       iCol = ii;
124048       iColLen = (int)((zInput - z) + nStr + 1);
124049       break;
124050     }
124051   }
124052   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
124053   *pnConsumed += iColLen;
124054   return rc;
124055 }
124056 
124057 /*
124058 ** The argument is an Fts3Expr structure for a binary operator (any type
124059 ** except an FTSQUERY_PHRASE). Return an integer value representing the
124060 ** precedence of the operator. Lower values have a higher precedence (i.e.
124061 ** group more tightly). For example, in the C language, the == operator
124062 ** groups more tightly than ||, and would therefore have a higher precedence.
124063 **
124064 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
124065 ** is defined), the order of the operators in precedence from highest to
124066 ** lowest is:
124067 **
124068 **   NEAR
124069 **   NOT
124070 **   AND (including implicit ANDs)
124071 **   OR
124072 **
124073 ** Note that when using the old query syntax, the OR operator has a higher
124074 ** precedence than the AND operator.
124075 */
124076 static int opPrecedence(Fts3Expr *p){
124077   assert( p->eType!=FTSQUERY_PHRASE );
124078   if( sqlite3_fts3_enable_parentheses ){
124079     return p->eType;
124080   }else if( p->eType==FTSQUERY_NEAR ){
124081     return 1;
124082   }else if( p->eType==FTSQUERY_OR ){
124083     return 2;
124084   }
124085   assert( p->eType==FTSQUERY_AND );
124086   return 3;
124087 }
124088 
124089 /*
124090 ** Argument ppHead contains a pointer to the current head of a query
124091 ** expression tree being parsed. pPrev is the expression node most recently
124092 ** inserted into the tree. This function adds pNew, which is always a binary
124093 ** operator node, into the expression tree based on the relative precedence
124094 ** of pNew and the existing nodes of the tree. This may result in the head
124095 ** of the tree changing, in which case *ppHead is set to the new root node.
124096 */
124097 static void insertBinaryOperator(
124098   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
124099   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
124100   Fts3Expr *pNew           /* New binary node to insert into expression tree */
124101 ){
124102   Fts3Expr *pSplit = pPrev;
124103   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
124104     pSplit = pSplit->pParent;
124105   }
124106 
124107   if( pSplit->pParent ){
124108     assert( pSplit->pParent->pRight==pSplit );
124109     pSplit->pParent->pRight = pNew;
124110     pNew->pParent = pSplit->pParent;
124111   }else{
124112     *ppHead = pNew;
124113   }
124114   pNew->pLeft = pSplit;
124115   pSplit->pParent = pNew;
124116 }
124117 
124118 /*
124119 ** Parse the fts3 query expression found in buffer z, length n. This function
124120 ** returns either when the end of the buffer is reached or an unmatched
124121 ** closing bracket - ')' - is encountered.
124122 **
124123 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
124124 ** parsed form of the expression and *pnConsumed is set to the number of
124125 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
124126 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
124127 */
124128 static int fts3ExprParse(
124129   ParseContext *pParse,                   /* fts3 query parse context */
124130   const char *z, int n,                   /* Text of MATCH query */
124131   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
124132   int *pnConsumed                         /* OUT: Number of bytes consumed */
124133 ){
124134   Fts3Expr *pRet = 0;
124135   Fts3Expr *pPrev = 0;
124136   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
124137   int nIn = n;
124138   const char *zIn = z;
124139   int rc = SQLITE_OK;
124140   int isRequirePhrase = 1;
124141 
124142   while( rc==SQLITE_OK ){
124143     Fts3Expr *p = 0;
124144     int nByte = 0;
124145     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
124146     if( rc==SQLITE_OK ){
124147       int isPhrase;
124148 
124149       if( !sqlite3_fts3_enable_parentheses
124150        && p->eType==FTSQUERY_PHRASE && pParse->isNot
124151       ){
124152         /* Create an implicit NOT operator. */
124153         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
124154         if( !pNot ){
124155           sqlite3Fts3ExprFree(p);
124156           rc = SQLITE_NOMEM;
124157           goto exprparse_out;
124158         }
124159         pNot->eType = FTSQUERY_NOT;
124160         pNot->pRight = p;
124161         if( pNotBranch ){
124162           pNot->pLeft = pNotBranch;
124163         }
124164         pNotBranch = pNot;
124165         p = pPrev;
124166       }else{
124167         int eType = p->eType;
124168         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
124169 
124170         /* The isRequirePhrase variable is set to true if a phrase or
124171         ** an expression contained in parenthesis is required. If a
124172         ** binary operator (AND, OR, NOT or NEAR) is encounted when
124173         ** isRequirePhrase is set, this is a syntax error.
124174         */
124175         if( !isPhrase && isRequirePhrase ){
124176           sqlite3Fts3ExprFree(p);
124177           rc = SQLITE_ERROR;
124178           goto exprparse_out;
124179         }
124180 
124181         if( isPhrase && !isRequirePhrase ){
124182           /* Insert an implicit AND operator. */
124183           Fts3Expr *pAnd;
124184           assert( pRet && pPrev );
124185           pAnd = fts3MallocZero(sizeof(Fts3Expr));
124186           if( !pAnd ){
124187             sqlite3Fts3ExprFree(p);
124188             rc = SQLITE_NOMEM;
124189             goto exprparse_out;
124190           }
124191           pAnd->eType = FTSQUERY_AND;
124192           insertBinaryOperator(&pRet, pPrev, pAnd);
124193           pPrev = pAnd;
124194         }
124195 
124196         /* This test catches attempts to make either operand of a NEAR
124197         ** operator something other than a phrase. For example, either of
124198         ** the following:
124199         **
124200         **    (bracketed expression) NEAR phrase
124201         **    phrase NEAR (bracketed expression)
124202         **
124203         ** Return an error in either case.
124204         */
124205         if( pPrev && (
124206             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
124207          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
124208         )){
124209           sqlite3Fts3ExprFree(p);
124210           rc = SQLITE_ERROR;
124211           goto exprparse_out;
124212         }
124213 
124214         if( isPhrase ){
124215           if( pRet ){
124216             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
124217             pPrev->pRight = p;
124218             p->pParent = pPrev;
124219           }else{
124220             pRet = p;
124221           }
124222         }else{
124223           insertBinaryOperator(&pRet, pPrev, p);
124224         }
124225         isRequirePhrase = !isPhrase;
124226       }
124227       assert( nByte>0 );
124228     }
124229     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
124230     nIn -= nByte;
124231     zIn += nByte;
124232     pPrev = p;
124233   }
124234 
124235   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
124236     rc = SQLITE_ERROR;
124237   }
124238 
124239   if( rc==SQLITE_DONE ){
124240     rc = SQLITE_OK;
124241     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
124242       if( !pRet ){
124243         rc = SQLITE_ERROR;
124244       }else{
124245         Fts3Expr *pIter = pNotBranch;
124246         while( pIter->pLeft ){
124247           pIter = pIter->pLeft;
124248         }
124249         pIter->pLeft = pRet;
124250         pRet = pNotBranch;
124251       }
124252     }
124253   }
124254   *pnConsumed = n - nIn;
124255 
124256 exprparse_out:
124257   if( rc!=SQLITE_OK ){
124258     sqlite3Fts3ExprFree(pRet);
124259     sqlite3Fts3ExprFree(pNotBranch);
124260     pRet = 0;
124261   }
124262   *ppExpr = pRet;
124263   return rc;
124264 }
124265 
124266 /*
124267 ** Parameters z and n contain a pointer to and length of a buffer containing
124268 ** an fts3 query expression, respectively. This function attempts to parse the
124269 ** query expression and create a tree of Fts3Expr structures representing the
124270 ** parsed expression. If successful, *ppExpr is set to point to the head
124271 ** of the parsed expression tree and SQLITE_OK is returned. If an error
124272 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
124273 ** error) is returned and *ppExpr is set to 0.
124274 **
124275 ** If parameter n is a negative number, then z is assumed to point to a
124276 ** nul-terminated string and the length is determined using strlen().
124277 **
124278 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
124279 ** use to normalize query tokens while parsing the expression. The azCol[]
124280 ** array, which is assumed to contain nCol entries, should contain the names
124281 ** of each column in the target fts3 table, in order from left to right.
124282 ** Column names must be nul-terminated strings.
124283 **
124284 ** The iDefaultCol parameter should be passed the index of the table column
124285 ** that appears on the left-hand-side of the MATCH operator (the default
124286 ** column to match against for tokens for which a column name is not explicitly
124287 ** specified as part of the query string), or -1 if tokens may by default
124288 ** match any table column.
124289 */
124290 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
124291   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
124292   int iLangid,                        /* Language id for tokenizer */
124293   char **azCol,                       /* Array of column names for fts3 table */
124294   int bFts4,                          /* True to allow FTS4-only syntax */
124295   int nCol,                           /* Number of entries in azCol[] */
124296   int iDefaultCol,                    /* Default column to query */
124297   const char *z, int n,               /* Text of MATCH query */
124298   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
124299 ){
124300   int nParsed;
124301   int rc;
124302   ParseContext sParse;
124303 
124304   memset(&sParse, 0, sizeof(ParseContext));
124305   sParse.pTokenizer = pTokenizer;
124306   sParse.iLangid = iLangid;
124307   sParse.azCol = (const char **)azCol;
124308   sParse.nCol = nCol;
124309   sParse.iDefaultCol = iDefaultCol;
124310   sParse.bFts4 = bFts4;
124311   if( z==0 ){
124312     *ppExpr = 0;
124313     return SQLITE_OK;
124314   }
124315   if( n<0 ){
124316     n = (int)strlen(z);
124317   }
124318   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
124319 
124320   /* Check for mismatched parenthesis */
124321   if( rc==SQLITE_OK && sParse.nNest ){
124322     rc = SQLITE_ERROR;
124323     sqlite3Fts3ExprFree(*ppExpr);
124324     *ppExpr = 0;
124325   }
124326 
124327   return rc;
124328 }
124329 
124330 /*
124331 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
124332 */
124333 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
124334   if( p ){
124335     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
124336     sqlite3Fts3ExprFree(p->pLeft);
124337     sqlite3Fts3ExprFree(p->pRight);
124338     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
124339     sqlite3_free(p->aMI);
124340     sqlite3_free(p);
124341   }
124342 }
124343 
124344 /****************************************************************************
124345 *****************************************************************************
124346 ** Everything after this point is just test code.
124347 */
124348 
124349 #ifdef SQLITE_TEST
124350 
124351 /* #include <stdio.h> */
124352 
124353 /*
124354 ** Function to query the hash-table of tokenizers (see README.tokenizers).
124355 */
124356 static int queryTestTokenizer(
124357   sqlite3 *db,
124358   const char *zName,
124359   const sqlite3_tokenizer_module **pp
124360 ){
124361   int rc;
124362   sqlite3_stmt *pStmt;
124363   const char zSql[] = "SELECT fts3_tokenizer(?)";
124364 
124365   *pp = 0;
124366   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124367   if( rc!=SQLITE_OK ){
124368     return rc;
124369   }
124370 
124371   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124372   if( SQLITE_ROW==sqlite3_step(pStmt) ){
124373     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
124374       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
124375     }
124376   }
124377 
124378   return sqlite3_finalize(pStmt);
124379 }
124380 
124381 /*
124382 ** Return a pointer to a buffer containing a text representation of the
124383 ** expression passed as the first argument. The buffer is obtained from
124384 ** sqlite3_malloc(). It is the responsibility of the caller to use
124385 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
124386 ** NULL is returned.
124387 **
124388 ** If the second argument is not NULL, then its contents are prepended to
124389 ** the returned expression text and then freed using sqlite3_free().
124390 */
124391 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
124392   switch( pExpr->eType ){
124393     case FTSQUERY_PHRASE: {
124394       Fts3Phrase *pPhrase = pExpr->pPhrase;
124395       int i;
124396       zBuf = sqlite3_mprintf(
124397           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
124398       for(i=0; zBuf && i<pPhrase->nToken; i++){
124399         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
124400             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
124401             (pPhrase->aToken[i].isPrefix?"+":"")
124402         );
124403       }
124404       return zBuf;
124405     }
124406 
124407     case FTSQUERY_NEAR:
124408       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
124409       break;
124410     case FTSQUERY_NOT:
124411       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
124412       break;
124413     case FTSQUERY_AND:
124414       zBuf = sqlite3_mprintf("%zAND ", zBuf);
124415       break;
124416     case FTSQUERY_OR:
124417       zBuf = sqlite3_mprintf("%zOR ", zBuf);
124418       break;
124419   }
124420 
124421   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
124422   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
124423   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
124424 
124425   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
124426   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
124427 
124428   return zBuf;
124429 }
124430 
124431 /*
124432 ** This is the implementation of a scalar SQL function used to test the
124433 ** expression parser. It should be called as follows:
124434 **
124435 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
124436 **
124437 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
124438 ** to parse the query expression (see README.tokenizers). The second argument
124439 ** is the query expression to parse. Each subsequent argument is the name
124440 ** of a column of the fts3 table that the query expression may refer to.
124441 ** For example:
124442 **
124443 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
124444 */
124445 static void fts3ExprTest(
124446   sqlite3_context *context,
124447   int argc,
124448   sqlite3_value **argv
124449 ){
124450   sqlite3_tokenizer_module const *pModule = 0;
124451   sqlite3_tokenizer *pTokenizer = 0;
124452   int rc;
124453   char **azCol = 0;
124454   const char *zExpr;
124455   int nExpr;
124456   int nCol;
124457   int ii;
124458   Fts3Expr *pExpr;
124459   char *zBuf = 0;
124460   sqlite3 *db = sqlite3_context_db_handle(context);
124461 
124462   if( argc<3 ){
124463     sqlite3_result_error(context,
124464         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
124465     );
124466     return;
124467   }
124468 
124469   rc = queryTestTokenizer(db,
124470                           (const char *)sqlite3_value_text(argv[0]), &pModule);
124471   if( rc==SQLITE_NOMEM ){
124472     sqlite3_result_error_nomem(context);
124473     goto exprtest_out;
124474   }else if( !pModule ){
124475     sqlite3_result_error(context, "No such tokenizer module", -1);
124476     goto exprtest_out;
124477   }
124478 
124479   rc = pModule->xCreate(0, 0, &pTokenizer);
124480   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
124481   if( rc==SQLITE_NOMEM ){
124482     sqlite3_result_error_nomem(context);
124483     goto exprtest_out;
124484   }
124485   pTokenizer->pModule = pModule;
124486 
124487   zExpr = (const char *)sqlite3_value_text(argv[1]);
124488   nExpr = sqlite3_value_bytes(argv[1]);
124489   nCol = argc-2;
124490   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
124491   if( !azCol ){
124492     sqlite3_result_error_nomem(context);
124493     goto exprtest_out;
124494   }
124495   for(ii=0; ii<nCol; ii++){
124496     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
124497   }
124498 
124499   rc = sqlite3Fts3ExprParse(
124500       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
124501   );
124502   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
124503     sqlite3_result_error(context, "Error parsing expression", -1);
124504   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
124505     sqlite3_result_error_nomem(context);
124506   }else{
124507     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
124508     sqlite3_free(zBuf);
124509   }
124510 
124511   sqlite3Fts3ExprFree(pExpr);
124512 
124513 exprtest_out:
124514   if( pModule && pTokenizer ){
124515     rc = pModule->xDestroy(pTokenizer);
124516   }
124517   sqlite3_free(azCol);
124518 }
124519 
124520 /*
124521 ** Register the query expression parser test function fts3_exprtest()
124522 ** with database connection db.
124523 */
124524 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
124525   return sqlite3_create_function(
124526       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
124527   );
124528 }
124529 
124530 #endif
124531 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124532 
124533 /************** End of fts3_expr.c *******************************************/
124534 /************** Begin file fts3_hash.c ***************************************/
124535 /*
124536 ** 2001 September 22
124537 **
124538 ** The author disclaims copyright to this source code.  In place of
124539 ** a legal notice, here is a blessing:
124540 **
124541 **    May you do good and not evil.
124542 **    May you find forgiveness for yourself and forgive others.
124543 **    May you share freely, never taking more than you give.
124544 **
124545 *************************************************************************
124546 ** This is the implementation of generic hash-tables used in SQLite.
124547 ** We've modified it slightly to serve as a standalone hash table
124548 ** implementation for the full-text indexing module.
124549 */
124550 
124551 /*
124552 ** The code in this file is only compiled if:
124553 **
124554 **     * The FTS3 module is being built as an extension
124555 **       (in which case SQLITE_CORE is not defined), or
124556 **
124557 **     * The FTS3 module is being built into the core of
124558 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124559 */
124560 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124561 
124562 /* #include <assert.h> */
124563 /* #include <stdlib.h> */
124564 /* #include <string.h> */
124565 
124566 
124567 /*
124568 ** Malloc and Free functions
124569 */
124570 static void *fts3HashMalloc(int n){
124571   void *p = sqlite3_malloc(n);
124572   if( p ){
124573     memset(p, 0, n);
124574   }
124575   return p;
124576 }
124577 static void fts3HashFree(void *p){
124578   sqlite3_free(p);
124579 }
124580 
124581 /* Turn bulk memory into a hash table object by initializing the
124582 ** fields of the Hash structure.
124583 **
124584 ** "pNew" is a pointer to the hash table that is to be initialized.
124585 ** keyClass is one of the constants
124586 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
124587 ** determines what kind of key the hash table will use.  "copyKey" is
124588 ** true if the hash table should make its own private copy of keys and
124589 ** false if it should just use the supplied pointer.
124590 */
124591 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
124592   assert( pNew!=0 );
124593   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
124594   pNew->keyClass = keyClass;
124595   pNew->copyKey = copyKey;
124596   pNew->first = 0;
124597   pNew->count = 0;
124598   pNew->htsize = 0;
124599   pNew->ht = 0;
124600 }
124601 
124602 /* Remove all entries from a hash table.  Reclaim all memory.
124603 ** Call this routine to delete a hash table or to reset a hash table
124604 ** to the empty state.
124605 */
124606 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
124607   Fts3HashElem *elem;         /* For looping over all elements of the table */
124608 
124609   assert( pH!=0 );
124610   elem = pH->first;
124611   pH->first = 0;
124612   fts3HashFree(pH->ht);
124613   pH->ht = 0;
124614   pH->htsize = 0;
124615   while( elem ){
124616     Fts3HashElem *next_elem = elem->next;
124617     if( pH->copyKey && elem->pKey ){
124618       fts3HashFree(elem->pKey);
124619     }
124620     fts3HashFree(elem);
124621     elem = next_elem;
124622   }
124623   pH->count = 0;
124624 }
124625 
124626 /*
124627 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
124628 */
124629 static int fts3StrHash(const void *pKey, int nKey){
124630   const char *z = (const char *)pKey;
124631   int h = 0;
124632   if( nKey<=0 ) nKey = (int) strlen(z);
124633   while( nKey > 0  ){
124634     h = (h<<3) ^ h ^ *z++;
124635     nKey--;
124636   }
124637   return h & 0x7fffffff;
124638 }
124639 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
124640   if( n1!=n2 ) return 1;
124641   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
124642 }
124643 
124644 /*
124645 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
124646 */
124647 static int fts3BinHash(const void *pKey, int nKey){
124648   int h = 0;
124649   const char *z = (const char *)pKey;
124650   while( nKey-- > 0 ){
124651     h = (h<<3) ^ h ^ *(z++);
124652   }
124653   return h & 0x7fffffff;
124654 }
124655 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
124656   if( n1!=n2 ) return 1;
124657   return memcmp(pKey1,pKey2,n1);
124658 }
124659 
124660 /*
124661 ** Return a pointer to the appropriate hash function given the key class.
124662 **
124663 ** The C syntax in this function definition may be unfamilar to some
124664 ** programmers, so we provide the following additional explanation:
124665 **
124666 ** The name of the function is "ftsHashFunction".  The function takes a
124667 ** single parameter "keyClass".  The return value of ftsHashFunction()
124668 ** is a pointer to another function.  Specifically, the return value
124669 ** of ftsHashFunction() is a pointer to a function that takes two parameters
124670 ** with types "const void*" and "int" and returns an "int".
124671 */
124672 static int (*ftsHashFunction(int keyClass))(const void*,int){
124673   if( keyClass==FTS3_HASH_STRING ){
124674     return &fts3StrHash;
124675   }else{
124676     assert( keyClass==FTS3_HASH_BINARY );
124677     return &fts3BinHash;
124678   }
124679 }
124680 
124681 /*
124682 ** Return a pointer to the appropriate hash function given the key class.
124683 **
124684 ** For help in interpreted the obscure C code in the function definition,
124685 ** see the header comment on the previous function.
124686 */
124687 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
124688   if( keyClass==FTS3_HASH_STRING ){
124689     return &fts3StrCompare;
124690   }else{
124691     assert( keyClass==FTS3_HASH_BINARY );
124692     return &fts3BinCompare;
124693   }
124694 }
124695 
124696 /* Link an element into the hash table
124697 */
124698 static void fts3HashInsertElement(
124699   Fts3Hash *pH,            /* The complete hash table */
124700   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
124701   Fts3HashElem *pNew       /* The element to be inserted */
124702 ){
124703   Fts3HashElem *pHead;     /* First element already in pEntry */
124704   pHead = pEntry->chain;
124705   if( pHead ){
124706     pNew->next = pHead;
124707     pNew->prev = pHead->prev;
124708     if( pHead->prev ){ pHead->prev->next = pNew; }
124709     else             { pH->first = pNew; }
124710     pHead->prev = pNew;
124711   }else{
124712     pNew->next = pH->first;
124713     if( pH->first ){ pH->first->prev = pNew; }
124714     pNew->prev = 0;
124715     pH->first = pNew;
124716   }
124717   pEntry->count++;
124718   pEntry->chain = pNew;
124719 }
124720 
124721 
124722 /* Resize the hash table so that it cantains "new_size" buckets.
124723 ** "new_size" must be a power of 2.  The hash table might fail
124724 ** to resize if sqliteMalloc() fails.
124725 **
124726 ** Return non-zero if a memory allocation error occurs.
124727 */
124728 static int fts3Rehash(Fts3Hash *pH, int new_size){
124729   struct _fts3ht *new_ht;          /* The new hash table */
124730   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
124731   int (*xHash)(const void*,int);   /* The hash function */
124732 
124733   assert( (new_size & (new_size-1))==0 );
124734   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
124735   if( new_ht==0 ) return 1;
124736   fts3HashFree(pH->ht);
124737   pH->ht = new_ht;
124738   pH->htsize = new_size;
124739   xHash = ftsHashFunction(pH->keyClass);
124740   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
124741     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
124742     next_elem = elem->next;
124743     fts3HashInsertElement(pH, &new_ht[h], elem);
124744   }
124745   return 0;
124746 }
124747 
124748 /* This function (for internal use only) locates an element in an
124749 ** hash table that matches the given key.  The hash for this key has
124750 ** already been computed and is passed as the 4th parameter.
124751 */
124752 static Fts3HashElem *fts3FindElementByHash(
124753   const Fts3Hash *pH, /* The pH to be searched */
124754   const void *pKey,   /* The key we are searching for */
124755   int nKey,
124756   int h               /* The hash for this key. */
124757 ){
124758   Fts3HashElem *elem;            /* Used to loop thru the element list */
124759   int count;                     /* Number of elements left to test */
124760   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
124761 
124762   if( pH->ht ){
124763     struct _fts3ht *pEntry = &pH->ht[h];
124764     elem = pEntry->chain;
124765     count = pEntry->count;
124766     xCompare = ftsCompareFunction(pH->keyClass);
124767     while( count-- && elem ){
124768       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
124769         return elem;
124770       }
124771       elem = elem->next;
124772     }
124773   }
124774   return 0;
124775 }
124776 
124777 /* Remove a single entry from the hash table given a pointer to that
124778 ** element and a hash on the element's key.
124779 */
124780 static void fts3RemoveElementByHash(
124781   Fts3Hash *pH,         /* The pH containing "elem" */
124782   Fts3HashElem* elem,   /* The element to be removed from the pH */
124783   int h                 /* Hash value for the element */
124784 ){
124785   struct _fts3ht *pEntry;
124786   if( elem->prev ){
124787     elem->prev->next = elem->next;
124788   }else{
124789     pH->first = elem->next;
124790   }
124791   if( elem->next ){
124792     elem->next->prev = elem->prev;
124793   }
124794   pEntry = &pH->ht[h];
124795   if( pEntry->chain==elem ){
124796     pEntry->chain = elem->next;
124797   }
124798   pEntry->count--;
124799   if( pEntry->count<=0 ){
124800     pEntry->chain = 0;
124801   }
124802   if( pH->copyKey && elem->pKey ){
124803     fts3HashFree(elem->pKey);
124804   }
124805   fts3HashFree( elem );
124806   pH->count--;
124807   if( pH->count<=0 ){
124808     assert( pH->first==0 );
124809     assert( pH->count==0 );
124810     fts3HashClear(pH);
124811   }
124812 }
124813 
124814 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
124815   const Fts3Hash *pH,
124816   const void *pKey,
124817   int nKey
124818 ){
124819   int h;                          /* A hash on key */
124820   int (*xHash)(const void*,int);  /* The hash function */
124821 
124822   if( pH==0 || pH->ht==0 ) return 0;
124823   xHash = ftsHashFunction(pH->keyClass);
124824   assert( xHash!=0 );
124825   h = (*xHash)(pKey,nKey);
124826   assert( (pH->htsize & (pH->htsize-1))==0 );
124827   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
124828 }
124829 
124830 /*
124831 ** Attempt to locate an element of the hash table pH with a key
124832 ** that matches pKey,nKey.  Return the data for this element if it is
124833 ** found, or NULL if there is no match.
124834 */
124835 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
124836   Fts3HashElem *pElem;            /* The element that matches key (if any) */
124837 
124838   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
124839   return pElem ? pElem->data : 0;
124840 }
124841 
124842 /* Insert an element into the hash table pH.  The key is pKey,nKey
124843 ** and the data is "data".
124844 **
124845 ** If no element exists with a matching key, then a new
124846 ** element is created.  A copy of the key is made if the copyKey
124847 ** flag is set.  NULL is returned.
124848 **
124849 ** If another element already exists with the same key, then the
124850 ** new data replaces the old data and the old data is returned.
124851 ** The key is not copied in this instance.  If a malloc fails, then
124852 ** the new data is returned and the hash table is unchanged.
124853 **
124854 ** If the "data" parameter to this function is NULL, then the
124855 ** element corresponding to "key" is removed from the hash table.
124856 */
124857 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
124858   Fts3Hash *pH,        /* The hash table to insert into */
124859   const void *pKey,    /* The key */
124860   int nKey,            /* Number of bytes in the key */
124861   void *data           /* The data */
124862 ){
124863   int hraw;                 /* Raw hash value of the key */
124864   int h;                    /* the hash of the key modulo hash table size */
124865   Fts3HashElem *elem;       /* Used to loop thru the element list */
124866   Fts3HashElem *new_elem;   /* New element added to the pH */
124867   int (*xHash)(const void*,int);  /* The hash function */
124868 
124869   assert( pH!=0 );
124870   xHash = ftsHashFunction(pH->keyClass);
124871   assert( xHash!=0 );
124872   hraw = (*xHash)(pKey, nKey);
124873   assert( (pH->htsize & (pH->htsize-1))==0 );
124874   h = hraw & (pH->htsize-1);
124875   elem = fts3FindElementByHash(pH,pKey,nKey,h);
124876   if( elem ){
124877     void *old_data = elem->data;
124878     if( data==0 ){
124879       fts3RemoveElementByHash(pH,elem,h);
124880     }else{
124881       elem->data = data;
124882     }
124883     return old_data;
124884   }
124885   if( data==0 ) return 0;
124886   if( (pH->htsize==0 && fts3Rehash(pH,8))
124887    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
124888   ){
124889     pH->count = 0;
124890     return data;
124891   }
124892   assert( pH->htsize>0 );
124893   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
124894   if( new_elem==0 ) return data;
124895   if( pH->copyKey && pKey!=0 ){
124896     new_elem->pKey = fts3HashMalloc( nKey );
124897     if( new_elem->pKey==0 ){
124898       fts3HashFree(new_elem);
124899       return data;
124900     }
124901     memcpy((void*)new_elem->pKey, pKey, nKey);
124902   }else{
124903     new_elem->pKey = (void*)pKey;
124904   }
124905   new_elem->nKey = nKey;
124906   pH->count++;
124907   assert( pH->htsize>0 );
124908   assert( (pH->htsize & (pH->htsize-1))==0 );
124909   h = hraw & (pH->htsize-1);
124910   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
124911   new_elem->data = data;
124912   return 0;
124913 }
124914 
124915 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124916 
124917 /************** End of fts3_hash.c *******************************************/
124918 /************** Begin file fts3_porter.c *************************************/
124919 /*
124920 ** 2006 September 30
124921 **
124922 ** The author disclaims copyright to this source code.  In place of
124923 ** a legal notice, here is a blessing:
124924 **
124925 **    May you do good and not evil.
124926 **    May you find forgiveness for yourself and forgive others.
124927 **    May you share freely, never taking more than you give.
124928 **
124929 *************************************************************************
124930 ** Implementation of the full-text-search tokenizer that implements
124931 ** a Porter stemmer.
124932 */
124933 
124934 /*
124935 ** The code in this file is only compiled if:
124936 **
124937 **     * The FTS3 module is being built as an extension
124938 **       (in which case SQLITE_CORE is not defined), or
124939 **
124940 **     * The FTS3 module is being built into the core of
124941 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124942 */
124943 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124944 
124945 /* #include <assert.h> */
124946 /* #include <stdlib.h> */
124947 /* #include <stdio.h> */
124948 /* #include <string.h> */
124949 
124950 
124951 /*
124952 ** Class derived from sqlite3_tokenizer
124953 */
124954 typedef struct porter_tokenizer {
124955   sqlite3_tokenizer base;      /* Base class */
124956 } porter_tokenizer;
124957 
124958 /*
124959 ** Class derived from sqlite3_tokenizer_cursor
124960 */
124961 typedef struct porter_tokenizer_cursor {
124962   sqlite3_tokenizer_cursor base;
124963   const char *zInput;          /* input we are tokenizing */
124964   int nInput;                  /* size of the input */
124965   int iOffset;                 /* current position in zInput */
124966   int iToken;                  /* index of next token to be returned */
124967   char *zToken;                /* storage for current token */
124968   int nAllocated;              /* space allocated to zToken buffer */
124969 } porter_tokenizer_cursor;
124970 
124971 
124972 /*
124973 ** Create a new tokenizer instance.
124974 */
124975 static int porterCreate(
124976   int argc, const char * const *argv,
124977   sqlite3_tokenizer **ppTokenizer
124978 ){
124979   porter_tokenizer *t;
124980 
124981   UNUSED_PARAMETER(argc);
124982   UNUSED_PARAMETER(argv);
124983 
124984   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
124985   if( t==NULL ) return SQLITE_NOMEM;
124986   memset(t, 0, sizeof(*t));
124987   *ppTokenizer = &t->base;
124988   return SQLITE_OK;
124989 }
124990 
124991 /*
124992 ** Destroy a tokenizer
124993 */
124994 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
124995   sqlite3_free(pTokenizer);
124996   return SQLITE_OK;
124997 }
124998 
124999 /*
125000 ** Prepare to begin tokenizing a particular string.  The input
125001 ** string to be tokenized is zInput[0..nInput-1].  A cursor
125002 ** used to incrementally tokenize this string is returned in
125003 ** *ppCursor.
125004 */
125005 static int porterOpen(
125006   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
125007   const char *zInput, int nInput,        /* String to be tokenized */
125008   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
125009 ){
125010   porter_tokenizer_cursor *c;
125011 
125012   UNUSED_PARAMETER(pTokenizer);
125013 
125014   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
125015   if( c==NULL ) return SQLITE_NOMEM;
125016 
125017   c->zInput = zInput;
125018   if( zInput==0 ){
125019     c->nInput = 0;
125020   }else if( nInput<0 ){
125021     c->nInput = (int)strlen(zInput);
125022   }else{
125023     c->nInput = nInput;
125024   }
125025   c->iOffset = 0;                 /* start tokenizing at the beginning */
125026   c->iToken = 0;
125027   c->zToken = NULL;               /* no space allocated, yet. */
125028   c->nAllocated = 0;
125029 
125030   *ppCursor = &c->base;
125031   return SQLITE_OK;
125032 }
125033 
125034 /*
125035 ** Close a tokenization cursor previously opened by a call to
125036 ** porterOpen() above.
125037 */
125038 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
125039   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
125040   sqlite3_free(c->zToken);
125041   sqlite3_free(c);
125042   return SQLITE_OK;
125043 }
125044 /*
125045 ** Vowel or consonant
125046 */
125047 static const char cType[] = {
125048    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
125049    1, 1, 1, 2, 1
125050 };
125051 
125052 /*
125053 ** isConsonant() and isVowel() determine if their first character in
125054 ** the string they point to is a consonant or a vowel, according
125055 ** to Porter ruls.
125056 **
125057 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
125058 ** 'Y' is a consonant unless it follows another consonant,
125059 ** in which case it is a vowel.
125060 **
125061 ** In these routine, the letters are in reverse order.  So the 'y' rule
125062 ** is that 'y' is a consonant unless it is followed by another
125063 ** consonent.
125064 */
125065 static int isVowel(const char*);
125066 static int isConsonant(const char *z){
125067   int j;
125068   char x = *z;
125069   if( x==0 ) return 0;
125070   assert( x>='a' && x<='z' );
125071   j = cType[x-'a'];
125072   if( j<2 ) return j;
125073   return z[1]==0 || isVowel(z + 1);
125074 }
125075 static int isVowel(const char *z){
125076   int j;
125077   char x = *z;
125078   if( x==0 ) return 0;
125079   assert( x>='a' && x<='z' );
125080   j = cType[x-'a'];
125081   if( j<2 ) return 1-j;
125082   return isConsonant(z + 1);
125083 }
125084 
125085 /*
125086 ** Let any sequence of one or more vowels be represented by V and let
125087 ** C be sequence of one or more consonants.  Then every word can be
125088 ** represented as:
125089 **
125090 **           [C] (VC){m} [V]
125091 **
125092 ** In prose:  A word is an optional consonant followed by zero or
125093 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
125094 ** number of vowel consonant pairs.  This routine computes the value
125095 ** of m for the first i bytes of a word.
125096 **
125097 ** Return true if the m-value for z is 1 or more.  In other words,
125098 ** return true if z contains at least one vowel that is followed
125099 ** by a consonant.
125100 **
125101 ** In this routine z[] is in reverse order.  So we are really looking
125102 ** for an instance of of a consonant followed by a vowel.
125103 */
125104 static int m_gt_0(const char *z){
125105   while( isVowel(z) ){ z++; }
125106   if( *z==0 ) return 0;
125107   while( isConsonant(z) ){ z++; }
125108   return *z!=0;
125109 }
125110 
125111 /* Like mgt0 above except we are looking for a value of m which is
125112 ** exactly 1
125113 */
125114 static int m_eq_1(const char *z){
125115   while( isVowel(z) ){ z++; }
125116   if( *z==0 ) return 0;
125117   while( isConsonant(z) ){ z++; }
125118   if( *z==0 ) return 0;
125119   while( isVowel(z) ){ z++; }
125120   if( *z==0 ) return 1;
125121   while( isConsonant(z) ){ z++; }
125122   return *z==0;
125123 }
125124 
125125 /* Like mgt0 above except we are looking for a value of m>1 instead
125126 ** or m>0
125127 */
125128 static int m_gt_1(const char *z){
125129   while( isVowel(z) ){ z++; }
125130   if( *z==0 ) return 0;
125131   while( isConsonant(z) ){ z++; }
125132   if( *z==0 ) return 0;
125133   while( isVowel(z) ){ z++; }
125134   if( *z==0 ) return 0;
125135   while( isConsonant(z) ){ z++; }
125136   return *z!=0;
125137 }
125138 
125139 /*
125140 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
125141 */
125142 static int hasVowel(const char *z){
125143   while( isConsonant(z) ){ z++; }
125144   return *z!=0;
125145 }
125146 
125147 /*
125148 ** Return TRUE if the word ends in a double consonant.
125149 **
125150 ** The text is reversed here. So we are really looking at
125151 ** the first two characters of z[].
125152 */
125153 static int doubleConsonant(const char *z){
125154   return isConsonant(z) && z[0]==z[1];
125155 }
125156 
125157 /*
125158 ** Return TRUE if the word ends with three letters which
125159 ** are consonant-vowel-consonent and where the final consonant
125160 ** is not 'w', 'x', or 'y'.
125161 **
125162 ** The word is reversed here.  So we are really checking the
125163 ** first three letters and the first one cannot be in [wxy].
125164 */
125165 static int star_oh(const char *z){
125166   return
125167     isConsonant(z) &&
125168     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
125169     isVowel(z+1) &&
125170     isConsonant(z+2);
125171 }
125172 
125173 /*
125174 ** If the word ends with zFrom and xCond() is true for the stem
125175 ** of the word that preceeds the zFrom ending, then change the
125176 ** ending to zTo.
125177 **
125178 ** The input word *pz and zFrom are both in reverse order.  zTo
125179 ** is in normal order.
125180 **
125181 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
125182 ** match.  Not that TRUE is returned even if xCond() fails and
125183 ** no substitution occurs.
125184 */
125185 static int stem(
125186   char **pz,             /* The word being stemmed (Reversed) */
125187   const char *zFrom,     /* If the ending matches this... (Reversed) */
125188   const char *zTo,       /* ... change the ending to this (not reversed) */
125189   int (*xCond)(const char*)   /* Condition that must be true */
125190 ){
125191   char *z = *pz;
125192   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
125193   if( *zFrom!=0 ) return 0;
125194   if( xCond && !xCond(z) ) return 1;
125195   while( *zTo ){
125196     *(--z) = *(zTo++);
125197   }
125198   *pz = z;
125199   return 1;
125200 }
125201 
125202 /*
125203 ** This is the fallback stemmer used when the porter stemmer is
125204 ** inappropriate.  The input word is copied into the output with
125205 ** US-ASCII case folding.  If the input word is too long (more
125206 ** than 20 bytes if it contains no digits or more than 6 bytes if
125207 ** it contains digits) then word is truncated to 20 or 6 bytes
125208 ** by taking 10 or 3 bytes from the beginning and end.
125209 */
125210 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
125211   int i, mx, j;
125212   int hasDigit = 0;
125213   for(i=0; i<nIn; i++){
125214     char c = zIn[i];
125215     if( c>='A' && c<='Z' ){
125216       zOut[i] = c - 'A' + 'a';
125217     }else{
125218       if( c>='0' && c<='9' ) hasDigit = 1;
125219       zOut[i] = c;
125220     }
125221   }
125222   mx = hasDigit ? 3 : 10;
125223   if( nIn>mx*2 ){
125224     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
125225       zOut[j] = zOut[i];
125226     }
125227     i = j;
125228   }
125229   zOut[i] = 0;
125230   *pnOut = i;
125231 }
125232 
125233 
125234 /*
125235 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
125236 ** zOut is at least big enough to hold nIn bytes.  Write the actual
125237 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
125238 **
125239 ** Any upper-case characters in the US-ASCII character set ([A-Z])
125240 ** are converted to lower case.  Upper-case UTF characters are
125241 ** unchanged.
125242 **
125243 ** Words that are longer than about 20 bytes are stemmed by retaining
125244 ** a few bytes from the beginning and the end of the word.  If the
125245 ** word contains digits, 3 bytes are taken from the beginning and
125246 ** 3 bytes from the end.  For long words without digits, 10 bytes
125247 ** are taken from each end.  US-ASCII case folding still applies.
125248 **
125249 ** If the input word contains not digits but does characters not
125250 ** in [a-zA-Z] then no stemming is attempted and this routine just
125251 ** copies the input into the input into the output with US-ASCII
125252 ** case folding.
125253 **
125254 ** Stemming never increases the length of the word.  So there is
125255 ** no chance of overflowing the zOut buffer.
125256 */
125257 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
125258   int i, j;
125259   char zReverse[28];
125260   char *z, *z2;
125261   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
125262     /* The word is too big or too small for the porter stemmer.
125263     ** Fallback to the copy stemmer */
125264     copy_stemmer(zIn, nIn, zOut, pnOut);
125265     return;
125266   }
125267   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
125268     char c = zIn[i];
125269     if( c>='A' && c<='Z' ){
125270       zReverse[j] = c + 'a' - 'A';
125271     }else if( c>='a' && c<='z' ){
125272       zReverse[j] = c;
125273     }else{
125274       /* The use of a character not in [a-zA-Z] means that we fallback
125275       ** to the copy stemmer */
125276       copy_stemmer(zIn, nIn, zOut, pnOut);
125277       return;
125278     }
125279   }
125280   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
125281   z = &zReverse[j+1];
125282 
125283 
125284   /* Step 1a */
125285   if( z[0]=='s' ){
125286     if(
125287      !stem(&z, "sess", "ss", 0) &&
125288      !stem(&z, "sei", "i", 0)  &&
125289      !stem(&z, "ss", "ss", 0)
125290     ){
125291       z++;
125292     }
125293   }
125294 
125295   /* Step 1b */
125296   z2 = z;
125297   if( stem(&z, "dee", "ee", m_gt_0) ){
125298     /* Do nothing.  The work was all in the test */
125299   }else if(
125300      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
125301       && z!=z2
125302   ){
125303      if( stem(&z, "ta", "ate", 0) ||
125304          stem(&z, "lb", "ble", 0) ||
125305          stem(&z, "zi", "ize", 0) ){
125306        /* Do nothing.  The work was all in the test */
125307      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
125308        z++;
125309      }else if( m_eq_1(z) && star_oh(z) ){
125310        *(--z) = 'e';
125311      }
125312   }
125313 
125314   /* Step 1c */
125315   if( z[0]=='y' && hasVowel(z+1) ){
125316     z[0] = 'i';
125317   }
125318 
125319   /* Step 2 */
125320   switch( z[1] ){
125321    case 'a':
125322      stem(&z, "lanoita", "ate", m_gt_0) ||
125323      stem(&z, "lanoit", "tion", m_gt_0);
125324      break;
125325    case 'c':
125326      stem(&z, "icne", "ence", m_gt_0) ||
125327      stem(&z, "icna", "ance", m_gt_0);
125328      break;
125329    case 'e':
125330      stem(&z, "rezi", "ize", m_gt_0);
125331      break;
125332    case 'g':
125333      stem(&z, "igol", "log", m_gt_0);
125334      break;
125335    case 'l':
125336      stem(&z, "ilb", "ble", m_gt_0) ||
125337      stem(&z, "illa", "al", m_gt_0) ||
125338      stem(&z, "iltne", "ent", m_gt_0) ||
125339      stem(&z, "ile", "e", m_gt_0) ||
125340      stem(&z, "ilsuo", "ous", m_gt_0);
125341      break;
125342    case 'o':
125343      stem(&z, "noitazi", "ize", m_gt_0) ||
125344      stem(&z, "noita", "ate", m_gt_0) ||
125345      stem(&z, "rota", "ate", m_gt_0);
125346      break;
125347    case 's':
125348      stem(&z, "msila", "al", m_gt_0) ||
125349      stem(&z, "ssenevi", "ive", m_gt_0) ||
125350      stem(&z, "ssenluf", "ful", m_gt_0) ||
125351      stem(&z, "ssensuo", "ous", m_gt_0);
125352      break;
125353    case 't':
125354      stem(&z, "itila", "al", m_gt_0) ||
125355      stem(&z, "itivi", "ive", m_gt_0) ||
125356      stem(&z, "itilib", "ble", m_gt_0);
125357      break;
125358   }
125359 
125360   /* Step 3 */
125361   switch( z[0] ){
125362    case 'e':
125363      stem(&z, "etaci", "ic", m_gt_0) ||
125364      stem(&z, "evita", "", m_gt_0)   ||
125365      stem(&z, "ezila", "al", m_gt_0);
125366      break;
125367    case 'i':
125368      stem(&z, "itici", "ic", m_gt_0);
125369      break;
125370    case 'l':
125371      stem(&z, "laci", "ic", m_gt_0) ||
125372      stem(&z, "luf", "", m_gt_0);
125373      break;
125374    case 's':
125375      stem(&z, "ssen", "", m_gt_0);
125376      break;
125377   }
125378 
125379   /* Step 4 */
125380   switch( z[1] ){
125381    case 'a':
125382      if( z[0]=='l' && m_gt_1(z+2) ){
125383        z += 2;
125384      }
125385      break;
125386    case 'c':
125387      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
125388        z += 4;
125389      }
125390      break;
125391    case 'e':
125392      if( z[0]=='r' && m_gt_1(z+2) ){
125393        z += 2;
125394      }
125395      break;
125396    case 'i':
125397      if( z[0]=='c' && m_gt_1(z+2) ){
125398        z += 2;
125399      }
125400      break;
125401    case 'l':
125402      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
125403        z += 4;
125404      }
125405      break;
125406    case 'n':
125407      if( z[0]=='t' ){
125408        if( z[2]=='a' ){
125409          if( m_gt_1(z+3) ){
125410            z += 3;
125411          }
125412        }else if( z[2]=='e' ){
125413          stem(&z, "tneme", "", m_gt_1) ||
125414          stem(&z, "tnem", "", m_gt_1) ||
125415          stem(&z, "tne", "", m_gt_1);
125416        }
125417      }
125418      break;
125419    case 'o':
125420      if( z[0]=='u' ){
125421        if( m_gt_1(z+2) ){
125422          z += 2;
125423        }
125424      }else if( z[3]=='s' || z[3]=='t' ){
125425        stem(&z, "noi", "", m_gt_1);
125426      }
125427      break;
125428    case 's':
125429      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
125430        z += 3;
125431      }
125432      break;
125433    case 't':
125434      stem(&z, "eta", "", m_gt_1) ||
125435      stem(&z, "iti", "", m_gt_1);
125436      break;
125437    case 'u':
125438      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
125439        z += 3;
125440      }
125441      break;
125442    case 'v':
125443    case 'z':
125444      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
125445        z += 3;
125446      }
125447      break;
125448   }
125449 
125450   /* Step 5a */
125451   if( z[0]=='e' ){
125452     if( m_gt_1(z+1) ){
125453       z++;
125454     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
125455       z++;
125456     }
125457   }
125458 
125459   /* Step 5b */
125460   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
125461     z++;
125462   }
125463 
125464   /* z[] is now the stemmed word in reverse order.  Flip it back
125465   ** around into forward order and return.
125466   */
125467   *pnOut = i = (int)strlen(z);
125468   zOut[i] = 0;
125469   while( *z ){
125470     zOut[--i] = *(z++);
125471   }
125472 }
125473 
125474 /*
125475 ** Characters that can be part of a token.  We assume any character
125476 ** whose value is greater than 0x80 (any UTF character) can be
125477 ** part of a token.  In other words, delimiters all must have
125478 ** values of 0x7f or lower.
125479 */
125480 static const char porterIdChar[] = {
125481 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
125482     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
125483     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
125484     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
125485     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
125486     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
125487 };
125488 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
125489 
125490 /*
125491 ** Extract the next token from a tokenization cursor.  The cursor must
125492 ** have been opened by a prior call to porterOpen().
125493 */
125494 static int porterNext(
125495   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
125496   const char **pzToken,               /* OUT: *pzToken is the token text */
125497   int *pnBytes,                       /* OUT: Number of bytes in token */
125498   int *piStartOffset,                 /* OUT: Starting offset of token */
125499   int *piEndOffset,                   /* OUT: Ending offset of token */
125500   int *piPosition                     /* OUT: Position integer of token */
125501 ){
125502   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
125503   const char *z = c->zInput;
125504 
125505   while( c->iOffset<c->nInput ){
125506     int iStartOffset, ch;
125507 
125508     /* Scan past delimiter characters */
125509     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
125510       c->iOffset++;
125511     }
125512 
125513     /* Count non-delimiter characters. */
125514     iStartOffset = c->iOffset;
125515     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
125516       c->iOffset++;
125517     }
125518 
125519     if( c->iOffset>iStartOffset ){
125520       int n = c->iOffset-iStartOffset;
125521       if( n>c->nAllocated ){
125522         char *pNew;
125523         c->nAllocated = n+20;
125524         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
125525         if( !pNew ) return SQLITE_NOMEM;
125526         c->zToken = pNew;
125527       }
125528       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
125529       *pzToken = c->zToken;
125530       *piStartOffset = iStartOffset;
125531       *piEndOffset = c->iOffset;
125532       *piPosition = c->iToken++;
125533       return SQLITE_OK;
125534     }
125535   }
125536   return SQLITE_DONE;
125537 }
125538 
125539 /*
125540 ** The set of routines that implement the porter-stemmer tokenizer
125541 */
125542 static const sqlite3_tokenizer_module porterTokenizerModule = {
125543   0,
125544   porterCreate,
125545   porterDestroy,
125546   porterOpen,
125547   porterClose,
125548   porterNext,
125549   0
125550 };
125551 
125552 /*
125553 ** Allocate a new porter tokenizer.  Return a pointer to the new
125554 ** tokenizer in *ppModule
125555 */
125556 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
125557   sqlite3_tokenizer_module const**ppModule
125558 ){
125559   *ppModule = &porterTokenizerModule;
125560 }
125561 
125562 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125563 
125564 /************** End of fts3_porter.c *****************************************/
125565 /************** Begin file fts3_tokenizer.c **********************************/
125566 /*
125567 ** 2007 June 22
125568 **
125569 ** The author disclaims copyright to this source code.  In place of
125570 ** a legal notice, here is a blessing:
125571 **
125572 **    May you do good and not evil.
125573 **    May you find forgiveness for yourself and forgive others.
125574 **    May you share freely, never taking more than you give.
125575 **
125576 ******************************************************************************
125577 **
125578 ** This is part of an SQLite module implementing full-text search.
125579 ** This particular file implements the generic tokenizer interface.
125580 */
125581 
125582 /*
125583 ** The code in this file is only compiled if:
125584 **
125585 **     * The FTS3 module is being built as an extension
125586 **       (in which case SQLITE_CORE is not defined), or
125587 **
125588 **     * The FTS3 module is being built into the core of
125589 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125590 */
125591 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125592 
125593 /* #include <assert.h> */
125594 /* #include <string.h> */
125595 
125596 /*
125597 ** Implementation of the SQL scalar function for accessing the underlying
125598 ** hash table. This function may be called as follows:
125599 **
125600 **   SELECT <function-name>(<key-name>);
125601 **   SELECT <function-name>(<key-name>, <pointer>);
125602 **
125603 ** where <function-name> is the name passed as the second argument
125604 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
125605 **
125606 ** If the <pointer> argument is specified, it must be a blob value
125607 ** containing a pointer to be stored as the hash data corresponding
125608 ** to the string <key-name>. If <pointer> is not specified, then
125609 ** the string <key-name> must already exist in the has table. Otherwise,
125610 ** an error is returned.
125611 **
125612 ** Whether or not the <pointer> argument is specified, the value returned
125613 ** is a blob containing the pointer stored as the hash data corresponding
125614 ** to string <key-name> (after the hash-table is updated, if applicable).
125615 */
125616 static void scalarFunc(
125617   sqlite3_context *context,
125618   int argc,
125619   sqlite3_value **argv
125620 ){
125621   Fts3Hash *pHash;
125622   void *pPtr = 0;
125623   const unsigned char *zName;
125624   int nName;
125625 
125626   assert( argc==1 || argc==2 );
125627 
125628   pHash = (Fts3Hash *)sqlite3_user_data(context);
125629 
125630   zName = sqlite3_value_text(argv[0]);
125631   nName = sqlite3_value_bytes(argv[0])+1;
125632 
125633   if( argc==2 ){
125634     void *pOld;
125635     int n = sqlite3_value_bytes(argv[1]);
125636     if( n!=sizeof(pPtr) ){
125637       sqlite3_result_error(context, "argument type mismatch", -1);
125638       return;
125639     }
125640     pPtr = *(void **)sqlite3_value_blob(argv[1]);
125641     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
125642     if( pOld==pPtr ){
125643       sqlite3_result_error(context, "out of memory", -1);
125644       return;
125645     }
125646   }else{
125647     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
125648     if( !pPtr ){
125649       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
125650       sqlite3_result_error(context, zErr, -1);
125651       sqlite3_free(zErr);
125652       return;
125653     }
125654   }
125655 
125656   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
125657 }
125658 
125659 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
125660   static const char isFtsIdChar[] = {
125661       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
125662       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
125663       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
125664       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
125665       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
125666       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
125667       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
125668       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
125669   };
125670   return (c&0x80 || isFtsIdChar[(int)(c)]);
125671 }
125672 
125673 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
125674   const char *z1;
125675   const char *z2 = 0;
125676 
125677   /* Find the start of the next token. */
125678   z1 = zStr;
125679   while( z2==0 ){
125680     char c = *z1;
125681     switch( c ){
125682       case '\0': return 0;        /* No more tokens here */
125683       case '\'':
125684       case '"':
125685       case '`': {
125686         z2 = z1;
125687         while( *++z2 && (*z2!=c || *++z2==c) );
125688         break;
125689       }
125690       case '[':
125691         z2 = &z1[1];
125692         while( *z2 && z2[0]!=']' ) z2++;
125693         if( *z2 ) z2++;
125694         break;
125695 
125696       default:
125697         if( sqlite3Fts3IsIdChar(*z1) ){
125698           z2 = &z1[1];
125699           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
125700         }else{
125701           z1++;
125702         }
125703     }
125704   }
125705 
125706   *pn = (int)(z2-z1);
125707   return z1;
125708 }
125709 
125710 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
125711   Fts3Hash *pHash,                /* Tokenizer hash table */
125712   const char *zArg,               /* Tokenizer name */
125713   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
125714   char **pzErr                    /* OUT: Set to malloced error message */
125715 ){
125716   int rc;
125717   char *z = (char *)zArg;
125718   int n = 0;
125719   char *zCopy;
125720   char *zEnd;                     /* Pointer to nul-term of zCopy */
125721   sqlite3_tokenizer_module *m;
125722 
125723   zCopy = sqlite3_mprintf("%s", zArg);
125724   if( !zCopy ) return SQLITE_NOMEM;
125725   zEnd = &zCopy[strlen(zCopy)];
125726 
125727   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
125728   z[n] = '\0';
125729   sqlite3Fts3Dequote(z);
125730 
125731   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
125732   if( !m ){
125733     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
125734     rc = SQLITE_ERROR;
125735   }else{
125736     char const **aArg = 0;
125737     int iArg = 0;
125738     z = &z[n+1];
125739     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
125740       int nNew = sizeof(char *)*(iArg+1);
125741       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
125742       if( !aNew ){
125743         sqlite3_free(zCopy);
125744         sqlite3_free((void *)aArg);
125745         return SQLITE_NOMEM;
125746       }
125747       aArg = aNew;
125748       aArg[iArg++] = z;
125749       z[n] = '\0';
125750       sqlite3Fts3Dequote(z);
125751       z = &z[n+1];
125752     }
125753     rc = m->xCreate(iArg, aArg, ppTok);
125754     assert( rc!=SQLITE_OK || *ppTok );
125755     if( rc!=SQLITE_OK ){
125756       *pzErr = sqlite3_mprintf("unknown tokenizer");
125757     }else{
125758       (*ppTok)->pModule = m;
125759     }
125760     sqlite3_free((void *)aArg);
125761   }
125762 
125763   sqlite3_free(zCopy);
125764   return rc;
125765 }
125766 
125767 
125768 #ifdef SQLITE_TEST
125769 
125770 /* #include <tcl.h> */
125771 /* #include <string.h> */
125772 
125773 /*
125774 ** Implementation of a special SQL scalar function for testing tokenizers
125775 ** designed to be used in concert with the Tcl testing framework. This
125776 ** function must be called with two or more arguments:
125777 **
125778 **   SELECT <function-name>(<key-name>, ..., <input-string>);
125779 **
125780 ** where <function-name> is the name passed as the second argument
125781 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
125782 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
125783 **
125784 ** The return value is a string that may be interpreted as a Tcl
125785 ** list. For each token in the <input-string>, three elements are
125786 ** added to the returned list. The first is the token position, the
125787 ** second is the token text (folded, stemmed, etc.) and the third is the
125788 ** substring of <input-string> associated with the token. For example,
125789 ** using the built-in "simple" tokenizer:
125790 **
125791 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
125792 **
125793 ** will return the string:
125794 **
125795 **   "{0 i I 1 dont don't 2 see see 3 how how}"
125796 **
125797 */
125798 static void testFunc(
125799   sqlite3_context *context,
125800   int argc,
125801   sqlite3_value **argv
125802 ){
125803   Fts3Hash *pHash;
125804   sqlite3_tokenizer_module *p;
125805   sqlite3_tokenizer *pTokenizer = 0;
125806   sqlite3_tokenizer_cursor *pCsr = 0;
125807 
125808   const char *zErr = 0;
125809 
125810   const char *zName;
125811   int nName;
125812   const char *zInput;
125813   int nInput;
125814 
125815   const char *azArg[64];
125816 
125817   const char *zToken;
125818   int nToken = 0;
125819   int iStart = 0;
125820   int iEnd = 0;
125821   int iPos = 0;
125822   int i;
125823 
125824   Tcl_Obj *pRet;
125825 
125826   if( argc<2 ){
125827     sqlite3_result_error(context, "insufficient arguments", -1);
125828     return;
125829   }
125830 
125831   nName = sqlite3_value_bytes(argv[0]);
125832   zName = (const char *)sqlite3_value_text(argv[0]);
125833   nInput = sqlite3_value_bytes(argv[argc-1]);
125834   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
125835 
125836   pHash = (Fts3Hash *)sqlite3_user_data(context);
125837   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
125838 
125839   if( !p ){
125840     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
125841     sqlite3_result_error(context, zErr, -1);
125842     sqlite3_free(zErr);
125843     return;
125844   }
125845 
125846   pRet = Tcl_NewObj();
125847   Tcl_IncrRefCount(pRet);
125848 
125849   for(i=1; i<argc-1; i++){
125850     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
125851   }
125852 
125853   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
125854     zErr = "error in xCreate()";
125855     goto finish;
125856   }
125857   pTokenizer->pModule = p;
125858   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
125859     zErr = "error in xOpen()";
125860     goto finish;
125861   }
125862 
125863   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
125864     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
125865     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
125866     zToken = &zInput[iStart];
125867     nToken = iEnd-iStart;
125868     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
125869   }
125870 
125871   if( SQLITE_OK!=p->xClose(pCsr) ){
125872     zErr = "error in xClose()";
125873     goto finish;
125874   }
125875   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
125876     zErr = "error in xDestroy()";
125877     goto finish;
125878   }
125879 
125880 finish:
125881   if( zErr ){
125882     sqlite3_result_error(context, zErr, -1);
125883   }else{
125884     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
125885   }
125886   Tcl_DecrRefCount(pRet);
125887 }
125888 
125889 static
125890 int registerTokenizer(
125891   sqlite3 *db,
125892   char *zName,
125893   const sqlite3_tokenizer_module *p
125894 ){
125895   int rc;
125896   sqlite3_stmt *pStmt;
125897   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
125898 
125899   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125900   if( rc!=SQLITE_OK ){
125901     return rc;
125902   }
125903 
125904   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125905   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
125906   sqlite3_step(pStmt);
125907 
125908   return sqlite3_finalize(pStmt);
125909 }
125910 
125911 static
125912 int queryTokenizer(
125913   sqlite3 *db,
125914   char *zName,
125915   const sqlite3_tokenizer_module **pp
125916 ){
125917   int rc;
125918   sqlite3_stmt *pStmt;
125919   const char zSql[] = "SELECT fts3_tokenizer(?)";
125920 
125921   *pp = 0;
125922   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125923   if( rc!=SQLITE_OK ){
125924     return rc;
125925   }
125926 
125927   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125928   if( SQLITE_ROW==sqlite3_step(pStmt) ){
125929     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
125930       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
125931     }
125932   }
125933 
125934   return sqlite3_finalize(pStmt);
125935 }
125936 
125937 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
125938 
125939 /*
125940 ** Implementation of the scalar function fts3_tokenizer_internal_test().
125941 ** This function is used for testing only, it is not included in the
125942 ** build unless SQLITE_TEST is defined.
125943 **
125944 ** The purpose of this is to test that the fts3_tokenizer() function
125945 ** can be used as designed by the C-code in the queryTokenizer and
125946 ** registerTokenizer() functions above. These two functions are repeated
125947 ** in the README.tokenizer file as an example, so it is important to
125948 ** test them.
125949 **
125950 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
125951 ** function with no arguments. An assert() will fail if a problem is
125952 ** detected. i.e.:
125953 **
125954 **     SELECT fts3_tokenizer_internal_test();
125955 **
125956 */
125957 static void intTestFunc(
125958   sqlite3_context *context,
125959   int argc,
125960   sqlite3_value **argv
125961 ){
125962   int rc;
125963   const sqlite3_tokenizer_module *p1;
125964   const sqlite3_tokenizer_module *p2;
125965   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
125966 
125967   UNUSED_PARAMETER(argc);
125968   UNUSED_PARAMETER(argv);
125969 
125970   /* Test the query function */
125971   sqlite3Fts3SimpleTokenizerModule(&p1);
125972   rc = queryTokenizer(db, "simple", &p2);
125973   assert( rc==SQLITE_OK );
125974   assert( p1==p2 );
125975   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
125976   assert( rc==SQLITE_ERROR );
125977   assert( p2==0 );
125978   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
125979 
125980   /* Test the storage function */
125981   rc = registerTokenizer(db, "nosuchtokenizer", p1);
125982   assert( rc==SQLITE_OK );
125983   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
125984   assert( rc==SQLITE_OK );
125985   assert( p2==p1 );
125986 
125987   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
125988 }
125989 
125990 #endif
125991 
125992 /*
125993 ** Set up SQL objects in database db used to access the contents of
125994 ** the hash table pointed to by argument pHash. The hash table must
125995 ** been initialized to use string keys, and to take a private copy
125996 ** of the key when a value is inserted. i.e. by a call similar to:
125997 **
125998 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
125999 **
126000 ** This function adds a scalar function (see header comment above
126001 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
126002 ** defined at compilation time, a temporary virtual table (see header
126003 ** comment above struct HashTableVtab) to the database schema. Both
126004 ** provide read/write access to the contents of *pHash.
126005 **
126006 ** The third argument to this function, zName, is used as the name
126007 ** of both the scalar and, if created, the virtual table.
126008 */
126009 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
126010   sqlite3 *db,
126011   Fts3Hash *pHash,
126012   const char *zName
126013 ){
126014   int rc = SQLITE_OK;
126015   void *p = (void *)pHash;
126016   const int any = SQLITE_ANY;
126017 
126018 #ifdef SQLITE_TEST
126019   char *zTest = 0;
126020   char *zTest2 = 0;
126021   void *pdb = (void *)db;
126022   zTest = sqlite3_mprintf("%s_test", zName);
126023   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
126024   if( !zTest || !zTest2 ){
126025     rc = SQLITE_NOMEM;
126026   }
126027 #endif
126028 
126029   if( SQLITE_OK==rc ){
126030     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
126031   }
126032   if( SQLITE_OK==rc ){
126033     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
126034   }
126035 #ifdef SQLITE_TEST
126036   if( SQLITE_OK==rc ){
126037     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
126038   }
126039   if( SQLITE_OK==rc ){
126040     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
126041   }
126042 #endif
126043 
126044 #ifdef SQLITE_TEST
126045   sqlite3_free(zTest);
126046   sqlite3_free(zTest2);
126047 #endif
126048 
126049   return rc;
126050 }
126051 
126052 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126053 
126054 /************** End of fts3_tokenizer.c **************************************/
126055 /************** Begin file fts3_tokenizer1.c *********************************/
126056 /*
126057 ** 2006 Oct 10
126058 **
126059 ** The author disclaims copyright to this source code.  In place of
126060 ** a legal notice, here is a blessing:
126061 **
126062 **    May you do good and not evil.
126063 **    May you find forgiveness for yourself and forgive others.
126064 **    May you share freely, never taking more than you give.
126065 **
126066 ******************************************************************************
126067 **
126068 ** Implementation of the "simple" full-text-search tokenizer.
126069 */
126070 
126071 /*
126072 ** The code in this file is only compiled if:
126073 **
126074 **     * The FTS3 module is being built as an extension
126075 **       (in which case SQLITE_CORE is not defined), or
126076 **
126077 **     * The FTS3 module is being built into the core of
126078 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126079 */
126080 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126081 
126082 /* #include <assert.h> */
126083 /* #include <stdlib.h> */
126084 /* #include <stdio.h> */
126085 /* #include <string.h> */
126086 
126087 
126088 typedef struct simple_tokenizer {
126089   sqlite3_tokenizer base;
126090   char delim[128];             /* flag ASCII delimiters */
126091 } simple_tokenizer;
126092 
126093 typedef struct simple_tokenizer_cursor {
126094   sqlite3_tokenizer_cursor base;
126095   const char *pInput;          /* input we are tokenizing */
126096   int nBytes;                  /* size of the input */
126097   int iOffset;                 /* current position in pInput */
126098   int iToken;                  /* index of next token to be returned */
126099   char *pToken;                /* storage for current token */
126100   int nTokenAllocated;         /* space allocated to zToken buffer */
126101 } simple_tokenizer_cursor;
126102 
126103 
126104 static int simpleDelim(simple_tokenizer *t, unsigned char c){
126105   return c<0x80 && t->delim[c];
126106 }
126107 static int fts3_isalnum(int x){
126108   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
126109 }
126110 
126111 /*
126112 ** Create a new tokenizer instance.
126113 */
126114 static int simpleCreate(
126115   int argc, const char * const *argv,
126116   sqlite3_tokenizer **ppTokenizer
126117 ){
126118   simple_tokenizer *t;
126119 
126120   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
126121   if( t==NULL ) return SQLITE_NOMEM;
126122   memset(t, 0, sizeof(*t));
126123 
126124   /* TODO(shess) Delimiters need to remain the same from run to run,
126125   ** else we need to reindex.  One solution would be a meta-table to
126126   ** track such information in the database, then we'd only want this
126127   ** information on the initial create.
126128   */
126129   if( argc>1 ){
126130     int i, n = (int)strlen(argv[1]);
126131     for(i=0; i<n; i++){
126132       unsigned char ch = argv[1][i];
126133       /* We explicitly don't support UTF-8 delimiters for now. */
126134       if( ch>=0x80 ){
126135         sqlite3_free(t);
126136         return SQLITE_ERROR;
126137       }
126138       t->delim[ch] = 1;
126139     }
126140   } else {
126141     /* Mark non-alphanumeric ASCII characters as delimiters */
126142     int i;
126143     for(i=1; i<0x80; i++){
126144       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
126145     }
126146   }
126147 
126148   *ppTokenizer = &t->base;
126149   return SQLITE_OK;
126150 }
126151 
126152 /*
126153 ** Destroy a tokenizer
126154 */
126155 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
126156   sqlite3_free(pTokenizer);
126157   return SQLITE_OK;
126158 }
126159 
126160 /*
126161 ** Prepare to begin tokenizing a particular string.  The input
126162 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
126163 ** used to incrementally tokenize this string is returned in
126164 ** *ppCursor.
126165 */
126166 static int simpleOpen(
126167   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
126168   const char *pInput, int nBytes,        /* String to be tokenized */
126169   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
126170 ){
126171   simple_tokenizer_cursor *c;
126172 
126173   UNUSED_PARAMETER(pTokenizer);
126174 
126175   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
126176   if( c==NULL ) return SQLITE_NOMEM;
126177 
126178   c->pInput = pInput;
126179   if( pInput==0 ){
126180     c->nBytes = 0;
126181   }else if( nBytes<0 ){
126182     c->nBytes = (int)strlen(pInput);
126183   }else{
126184     c->nBytes = nBytes;
126185   }
126186   c->iOffset = 0;                 /* start tokenizing at the beginning */
126187   c->iToken = 0;
126188   c->pToken = NULL;               /* no space allocated, yet. */
126189   c->nTokenAllocated = 0;
126190 
126191   *ppCursor = &c->base;
126192   return SQLITE_OK;
126193 }
126194 
126195 /*
126196 ** Close a tokenization cursor previously opened by a call to
126197 ** simpleOpen() above.
126198 */
126199 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
126200   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
126201   sqlite3_free(c->pToken);
126202   sqlite3_free(c);
126203   return SQLITE_OK;
126204 }
126205 
126206 /*
126207 ** Extract the next token from a tokenization cursor.  The cursor must
126208 ** have been opened by a prior call to simpleOpen().
126209 */
126210 static int simpleNext(
126211   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
126212   const char **ppToken,               /* OUT: *ppToken is the token text */
126213   int *pnBytes,                       /* OUT: Number of bytes in token */
126214   int *piStartOffset,                 /* OUT: Starting offset of token */
126215   int *piEndOffset,                   /* OUT: Ending offset of token */
126216   int *piPosition                     /* OUT: Position integer of token */
126217 ){
126218   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
126219   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
126220   unsigned char *p = (unsigned char *)c->pInput;
126221 
126222   while( c->iOffset<c->nBytes ){
126223     int iStartOffset;
126224 
126225     /* Scan past delimiter characters */
126226     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
126227       c->iOffset++;
126228     }
126229 
126230     /* Count non-delimiter characters. */
126231     iStartOffset = c->iOffset;
126232     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
126233       c->iOffset++;
126234     }
126235 
126236     if( c->iOffset>iStartOffset ){
126237       int i, n = c->iOffset-iStartOffset;
126238       if( n>c->nTokenAllocated ){
126239         char *pNew;
126240         c->nTokenAllocated = n+20;
126241         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
126242         if( !pNew ) return SQLITE_NOMEM;
126243         c->pToken = pNew;
126244       }
126245       for(i=0; i<n; i++){
126246         /* TODO(shess) This needs expansion to handle UTF-8
126247         ** case-insensitivity.
126248         */
126249         unsigned char ch = p[iStartOffset+i];
126250         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
126251       }
126252       *ppToken = c->pToken;
126253       *pnBytes = n;
126254       *piStartOffset = iStartOffset;
126255       *piEndOffset = c->iOffset;
126256       *piPosition = c->iToken++;
126257 
126258       return SQLITE_OK;
126259     }
126260   }
126261   return SQLITE_DONE;
126262 }
126263 
126264 /*
126265 ** The set of routines that implement the simple tokenizer
126266 */
126267 static const sqlite3_tokenizer_module simpleTokenizerModule = {
126268   0,
126269   simpleCreate,
126270   simpleDestroy,
126271   simpleOpen,
126272   simpleClose,
126273   simpleNext,
126274   0,
126275 };
126276 
126277 /*
126278 ** Allocate a new simple tokenizer.  Return a pointer to the new
126279 ** tokenizer in *ppModule
126280 */
126281 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
126282   sqlite3_tokenizer_module const**ppModule
126283 ){
126284   *ppModule = &simpleTokenizerModule;
126285 }
126286 
126287 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126288 
126289 /************** End of fts3_tokenizer1.c *************************************/
126290 /************** Begin file fts3_write.c **************************************/
126291 /*
126292 ** 2009 Oct 23
126293 **
126294 ** The author disclaims copyright to this source code.  In place of
126295 ** a legal notice, here is a blessing:
126296 **
126297 **    May you do good and not evil.
126298 **    May you find forgiveness for yourself and forgive others.
126299 **    May you share freely, never taking more than you give.
126300 **
126301 ******************************************************************************
126302 **
126303 ** This file is part of the SQLite FTS3 extension module. Specifically,
126304 ** this file contains code to insert, update and delete rows from FTS3
126305 ** tables. It also contains code to merge FTS3 b-tree segments. Some
126306 ** of the sub-routines used to merge segments are also used by the query
126307 ** code in fts3.c.
126308 */
126309 
126310 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126311 
126312 /* #include <string.h> */
126313 /* #include <assert.h> */
126314 /* #include <stdlib.h> */
126315 
126316 
126317 #define FTS_MAX_APPENDABLE_HEIGHT 16
126318 
126319 /*
126320 ** When full-text index nodes are loaded from disk, the buffer that they
126321 ** are loaded into has the following number of bytes of padding at the end
126322 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
126323 ** of 920 bytes is allocated for it.
126324 **
126325 ** This means that if we have a pointer into a buffer containing node data,
126326 ** it is always safe to read up to two varints from it without risking an
126327 ** overread, even if the node data is corrupted.
126328 */
126329 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
126330 
126331 /*
126332 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
126333 ** memory incrementally instead of all at once. This can be a big performance
126334 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
126335 ** method before retrieving all query results (as may happen, for example,
126336 ** if a query has a LIMIT clause).
126337 **
126338 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
126339 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
126340 ** The code is written so that the hard lower-limit for each of these values
126341 ** is 1. Clearly such small values would be inefficient, but can be useful
126342 ** for testing purposes.
126343 **
126344 ** If this module is built with SQLITE_TEST defined, these constants may
126345 ** be overridden at runtime for testing purposes. File fts3_test.c contains
126346 ** a Tcl interface to read and write the values.
126347 */
126348 #ifdef SQLITE_TEST
126349 int test_fts3_node_chunksize = (4*1024);
126350 int test_fts3_node_chunk_threshold = (4*1024)*4;
126351 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
126352 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
126353 #else
126354 # define FTS3_NODE_CHUNKSIZE (4*1024)
126355 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
126356 #endif
126357 
126358 /*
126359 ** The two values that may be meaningfully bound to the :1 parameter in
126360 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
126361 */
126362 #define FTS_STAT_DOCTOTAL      0
126363 #define FTS_STAT_INCRMERGEHINT 1
126364 #define FTS_STAT_AUTOINCRMERGE 2
126365 
126366 /*
126367 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
126368 ** and incremental merge operation that takes place. This is used for
126369 ** debugging FTS only, it should not usually be turned on in production
126370 ** systems.
126371 */
126372 #ifdef FTS3_LOG_MERGES
126373 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
126374   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
126375 }
126376 #else
126377 #define fts3LogMerge(x, y)
126378 #endif
126379 
126380 
126381 typedef struct PendingList PendingList;
126382 typedef struct SegmentNode SegmentNode;
126383 typedef struct SegmentWriter SegmentWriter;
126384 
126385 /*
126386 ** An instance of the following data structure is used to build doclists
126387 ** incrementally. See function fts3PendingListAppend() for details.
126388 */
126389 struct PendingList {
126390   int nData;
126391   char *aData;
126392   int nSpace;
126393   sqlite3_int64 iLastDocid;
126394   sqlite3_int64 iLastCol;
126395   sqlite3_int64 iLastPos;
126396 };
126397 
126398 
126399 /*
126400 ** Each cursor has a (possibly empty) linked list of the following objects.
126401 */
126402 struct Fts3DeferredToken {
126403   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
126404   int iCol;                       /* Column token must occur in */
126405   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
126406   PendingList *pList;             /* Doclist is assembled here */
126407 };
126408 
126409 /*
126410 ** An instance of this structure is used to iterate through the terms on
126411 ** a contiguous set of segment b-tree leaf nodes. Although the details of
126412 ** this structure are only manipulated by code in this file, opaque handles
126413 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
126414 ** terms when querying the full-text index. See functions:
126415 **
126416 **   sqlite3Fts3SegReaderNew()
126417 **   sqlite3Fts3SegReaderFree()
126418 **   sqlite3Fts3SegReaderIterate()
126419 **
126420 ** Methods used to manipulate Fts3SegReader structures:
126421 **
126422 **   fts3SegReaderNext()
126423 **   fts3SegReaderFirstDocid()
126424 **   fts3SegReaderNextDocid()
126425 */
126426 struct Fts3SegReader {
126427   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
126428   u8 bLookup;                     /* True for a lookup only */
126429   u8 rootOnly;                    /* True for a root-only reader */
126430 
126431   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
126432   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
126433   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
126434   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
126435 
126436   char *aNode;                    /* Pointer to node data (or NULL) */
126437   int nNode;                      /* Size of buffer at aNode (or 0) */
126438   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
126439   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
126440 
126441   Fts3HashElem **ppNextElem;
126442 
126443   /* Variables set by fts3SegReaderNext(). These may be read directly
126444   ** by the caller. They are valid from the time SegmentReaderNew() returns
126445   ** until SegmentReaderNext() returns something other than SQLITE_OK
126446   ** (i.e. SQLITE_DONE).
126447   */
126448   int nTerm;                      /* Number of bytes in current term */
126449   char *zTerm;                    /* Pointer to current term */
126450   int nTermAlloc;                 /* Allocated size of zTerm buffer */
126451   char *aDoclist;                 /* Pointer to doclist of current entry */
126452   int nDoclist;                   /* Size of doclist in current entry */
126453 
126454   /* The following variables are used by fts3SegReaderNextDocid() to iterate
126455   ** through the current doclist (aDoclist/nDoclist).
126456   */
126457   char *pOffsetList;
126458   int nOffsetList;                /* For descending pending seg-readers only */
126459   sqlite3_int64 iDocid;
126460 };
126461 
126462 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
126463 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
126464 
126465 /*
126466 ** An instance of this structure is used to create a segment b-tree in the
126467 ** database. The internal details of this type are only accessed by the
126468 ** following functions:
126469 **
126470 **   fts3SegWriterAdd()
126471 **   fts3SegWriterFlush()
126472 **   fts3SegWriterFree()
126473 */
126474 struct SegmentWriter {
126475   SegmentNode *pTree;             /* Pointer to interior tree structure */
126476   sqlite3_int64 iFirst;           /* First slot in %_segments written */
126477   sqlite3_int64 iFree;            /* Next free slot in %_segments */
126478   char *zTerm;                    /* Pointer to previous term buffer */
126479   int nTerm;                      /* Number of bytes in zTerm */
126480   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
126481   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
126482   int nSize;                      /* Size of allocation at aData */
126483   int nData;                      /* Bytes of data in aData */
126484   char *aData;                    /* Pointer to block from malloc() */
126485 };
126486 
126487 /*
126488 ** Type SegmentNode is used by the following three functions to create
126489 ** the interior part of the segment b+-tree structures (everything except
126490 ** the leaf nodes). These functions and type are only ever used by code
126491 ** within the fts3SegWriterXXX() family of functions described above.
126492 **
126493 **   fts3NodeAddTerm()
126494 **   fts3NodeWrite()
126495 **   fts3NodeFree()
126496 **
126497 ** When a b+tree is written to the database (either as a result of a merge
126498 ** or the pending-terms table being flushed), leaves are written into the
126499 ** database file as soon as they are completely populated. The interior of
126500 ** the tree is assembled in memory and written out only once all leaves have
126501 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
126502 ** very large, meaning that the interior of the tree consumes relatively
126503 ** little memory.
126504 */
126505 struct SegmentNode {
126506   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
126507   SegmentNode *pRight;            /* Pointer to right-sibling */
126508   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
126509   int nEntry;                     /* Number of terms written to node so far */
126510   char *zTerm;                    /* Pointer to previous term buffer */
126511   int nTerm;                      /* Number of bytes in zTerm */
126512   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
126513   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
126514   int nData;                      /* Bytes of valid data so far */
126515   char *aData;                    /* Node data */
126516 };
126517 
126518 /*
126519 ** Valid values for the second argument to fts3SqlStmt().
126520 */
126521 #define SQL_DELETE_CONTENT             0
126522 #define SQL_IS_EMPTY                   1
126523 #define SQL_DELETE_ALL_CONTENT         2
126524 #define SQL_DELETE_ALL_SEGMENTS        3
126525 #define SQL_DELETE_ALL_SEGDIR          4
126526 #define SQL_DELETE_ALL_DOCSIZE         5
126527 #define SQL_DELETE_ALL_STAT            6
126528 #define SQL_SELECT_CONTENT_BY_ROWID    7
126529 #define SQL_NEXT_SEGMENT_INDEX         8
126530 #define SQL_INSERT_SEGMENTS            9
126531 #define SQL_NEXT_SEGMENTS_ID          10
126532 #define SQL_INSERT_SEGDIR             11
126533 #define SQL_SELECT_LEVEL              12
126534 #define SQL_SELECT_LEVEL_RANGE        13
126535 #define SQL_SELECT_LEVEL_COUNT        14
126536 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
126537 #define SQL_DELETE_SEGDIR_LEVEL       16
126538 #define SQL_DELETE_SEGMENTS_RANGE     17
126539 #define SQL_CONTENT_INSERT            18
126540 #define SQL_DELETE_DOCSIZE            19
126541 #define SQL_REPLACE_DOCSIZE           20
126542 #define SQL_SELECT_DOCSIZE            21
126543 #define SQL_SELECT_STAT               22
126544 #define SQL_REPLACE_STAT              23
126545 
126546 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
126547 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
126548 #define SQL_DELETE_SEGDIR_RANGE       26
126549 #define SQL_SELECT_ALL_LANGID         27
126550 #define SQL_FIND_MERGE_LEVEL          28
126551 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
126552 #define SQL_DELETE_SEGDIR_ENTRY       30
126553 #define SQL_SHIFT_SEGDIR_ENTRY        31
126554 #define SQL_SELECT_SEGDIR             32
126555 #define SQL_CHOMP_SEGDIR              33
126556 #define SQL_SEGMENT_IS_APPENDABLE     34
126557 #define SQL_SELECT_INDEXES            35
126558 #define SQL_SELECT_MXLEVEL            36
126559 
126560 /*
126561 ** This function is used to obtain an SQLite prepared statement handle
126562 ** for the statement identified by the second argument. If successful,
126563 ** *pp is set to the requested statement handle and SQLITE_OK returned.
126564 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
126565 **
126566 ** If argument apVal is not NULL, then it must point to an array with
126567 ** at least as many entries as the requested statement has bound
126568 ** parameters. The values are bound to the statements parameters before
126569 ** returning.
126570 */
126571 static int fts3SqlStmt(
126572   Fts3Table *p,                   /* Virtual table handle */
126573   int eStmt,                      /* One of the SQL_XXX constants above */
126574   sqlite3_stmt **pp,              /* OUT: Statement handle */
126575   sqlite3_value **apVal           /* Values to bind to statement */
126576 ){
126577   const char *azSql[] = {
126578 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
126579 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
126580 /* 2  */  "DELETE FROM %Q.'%q_content'",
126581 /* 3  */  "DELETE FROM %Q.'%q_segments'",
126582 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
126583 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
126584 /* 6  */  "DELETE FROM %Q.'%q_stat'",
126585 /* 7  */  "SELECT %s WHERE rowid=?",
126586 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
126587 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
126588 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
126589 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
126590 
126591           /* Return segments in order from oldest to newest.*/
126592 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126593             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
126594 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126595             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
126596             "ORDER BY level DESC, idx ASC",
126597 
126598 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
126599 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
126600 
126601 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
126602 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
126603 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
126604 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
126605 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
126606 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
126607 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
126608 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
126609 /* 24 */  "",
126610 /* 25 */  "",
126611 
126612 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
126613 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
126614 
126615 /* This statement is used to determine which level to read the input from
126616 ** when performing an incremental merge. It returns the absolute level number
126617 ** of the oldest level in the db that contains at least ? segments. Or,
126618 ** if no level in the FTS index contains more than ? segments, the statement
126619 ** returns zero rows.  */
126620 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
126621          "  ORDER BY (level %% 1024) ASC LIMIT 1",
126622 
126623 /* Estimate the upper limit on the number of leaf nodes in a new segment
126624 ** created by merging the oldest :2 segments from absolute level :1. See
126625 ** function sqlite3Fts3Incrmerge() for details.  */
126626 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
126627          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
126628 
126629 /* SQL_DELETE_SEGDIR_ENTRY
126630 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
126631 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
126632 
126633 /* SQL_SHIFT_SEGDIR_ENTRY
126634 **   Modify the idx value for the segment with idx=:3 on absolute level :2
126635 **   to :1.  */
126636 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
126637 
126638 /* SQL_SELECT_SEGDIR
126639 **   Read a single entry from the %_segdir table. The entry from absolute
126640 **   level :1 with index value :2.  */
126641 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
126642             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
126643 
126644 /* SQL_CHOMP_SEGDIR
126645 **   Update the start_block (:1) and root (:2) fields of the %_segdir
126646 **   entry located on absolute level :3 with index :4.  */
126647 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
126648             "WHERE level = ? AND idx = ?",
126649 
126650 /* SQL_SEGMENT_IS_APPENDABLE
126651 **   Return a single row if the segment with end_block=? is appendable. Or
126652 **   no rows otherwise.  */
126653 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
126654 
126655 /* SQL_SELECT_INDEXES
126656 **   Return the list of valid segment indexes for absolute level ?  */
126657 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
126658 
126659 /* SQL_SELECT_MXLEVEL
126660 **   Return the largest relative level in the FTS index or indexes.  */
126661 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
126662   };
126663   int rc = SQLITE_OK;
126664   sqlite3_stmt *pStmt;
126665 
126666   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
126667   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
126668 
126669   pStmt = p->aStmt[eStmt];
126670   if( !pStmt ){
126671     char *zSql;
126672     if( eStmt==SQL_CONTENT_INSERT ){
126673       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
126674     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
126675       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
126676     }else{
126677       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
126678     }
126679     if( !zSql ){
126680       rc = SQLITE_NOMEM;
126681     }else{
126682       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
126683       sqlite3_free(zSql);
126684       assert( rc==SQLITE_OK || pStmt==0 );
126685       p->aStmt[eStmt] = pStmt;
126686     }
126687   }
126688   if( apVal ){
126689     int i;
126690     int nParam = sqlite3_bind_parameter_count(pStmt);
126691     for(i=0; rc==SQLITE_OK && i<nParam; i++){
126692       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
126693     }
126694   }
126695   *pp = pStmt;
126696   return rc;
126697 }
126698 
126699 
126700 static int fts3SelectDocsize(
126701   Fts3Table *pTab,                /* FTS3 table handle */
126702   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
126703   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126704 ){
126705   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
126706   int rc;                         /* Return code */
126707 
126708   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
126709   if( rc==SQLITE_OK ){
126710     sqlite3_bind_int64(pStmt, 1, iDocid);
126711     rc = sqlite3_step(pStmt);
126712     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
126713       rc = sqlite3_reset(pStmt);
126714       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126715       pStmt = 0;
126716     }else{
126717       rc = SQLITE_OK;
126718     }
126719   }
126720 
126721   *ppStmt = pStmt;
126722   return rc;
126723 }
126724 
126725 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
126726   Fts3Table *pTab,                /* Fts3 table handle */
126727   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126728 ){
126729   sqlite3_stmt *pStmt = 0;
126730   int rc;
126731   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
126732   if( rc==SQLITE_OK ){
126733     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
126734     if( sqlite3_step(pStmt)!=SQLITE_ROW
126735      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
126736     ){
126737       rc = sqlite3_reset(pStmt);
126738       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
126739       pStmt = 0;
126740     }
126741   }
126742   *ppStmt = pStmt;
126743   return rc;
126744 }
126745 
126746 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
126747   Fts3Table *pTab,                /* Fts3 table handle */
126748   sqlite3_int64 iDocid,           /* Docid to read size data for */
126749   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
126750 ){
126751   return fts3SelectDocsize(pTab, iDocid, ppStmt);
126752 }
126753 
126754 /*
126755 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
126756 ** array apVal[] to the SQL statement identified by eStmt, the statement
126757 ** is executed.
126758 **
126759 ** Returns SQLITE_OK if the statement is successfully executed, or an
126760 ** SQLite error code otherwise.
126761 */
126762 static void fts3SqlExec(
126763   int *pRC,                /* Result code */
126764   Fts3Table *p,            /* The FTS3 table */
126765   int eStmt,               /* Index of statement to evaluate */
126766   sqlite3_value **apVal    /* Parameters to bind */
126767 ){
126768   sqlite3_stmt *pStmt;
126769   int rc;
126770   if( *pRC ) return;
126771   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
126772   if( rc==SQLITE_OK ){
126773     sqlite3_step(pStmt);
126774     rc = sqlite3_reset(pStmt);
126775   }
126776   *pRC = rc;
126777 }
126778 
126779 
126780 /*
126781 ** This function ensures that the caller has obtained a shared-cache
126782 ** table-lock on the %_content table. This is required before reading
126783 ** data from the fts3 table. If this lock is not acquired first, then
126784 ** the caller may end up holding read-locks on the %_segments and %_segdir
126785 ** tables, but no read-lock on the %_content table. If this happens
126786 ** a second connection will be able to write to the fts3 table, but
126787 ** attempting to commit those writes might return SQLITE_LOCKED or
126788 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
126789 ** write-locks on the %_segments and %_segdir ** tables).
126790 **
126791 ** We try to avoid this because if FTS3 returns any error when committing
126792 ** a transaction, the whole transaction will be rolled back. And this is
126793 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
126794 ** still happen if the user reads data directly from the %_segments or
126795 ** %_segdir tables instead of going through FTS3 though.
126796 **
126797 ** This reasoning does not apply to a content=xxx table.
126798 */
126799 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
126800   int rc;                         /* Return code */
126801   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
126802 
126803   if( p->zContentTbl==0 ){
126804     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
126805     if( rc==SQLITE_OK ){
126806       sqlite3_bind_null(pStmt, 1);
126807       sqlite3_step(pStmt);
126808       rc = sqlite3_reset(pStmt);
126809     }
126810   }else{
126811     rc = SQLITE_OK;
126812   }
126813 
126814   return rc;
126815 }
126816 
126817 /*
126818 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
126819 ** Within each language id, a separate index is maintained to store the
126820 ** document terms, and each configured prefix size (configured the FTS
126821 ** "prefix=" option). And each index consists of multiple levels ("relative
126822 ** levels").
126823 **
126824 ** All three of these values (the language id, the specific index and the
126825 ** level within the index) are encoded in 64-bit integer values stored
126826 ** in the %_segdir table on disk. This function is used to convert three
126827 ** separate component values into the single 64-bit integer value that
126828 ** can be used to query the %_segdir table.
126829 **
126830 ** Specifically, each language-id/index combination is allocated 1024
126831 ** 64-bit integer level values ("absolute levels"). The main terms index
126832 ** for language-id 0 is allocate values 0-1023. The first prefix index
126833 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
126834 ** Language 1 indexes are allocated immediately following language 0.
126835 **
126836 ** So, for a system with nPrefix prefix indexes configured, the block of
126837 ** absolute levels that corresponds to language-id iLangid and index
126838 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
126839 */
126840 static sqlite3_int64 getAbsoluteLevel(
126841   Fts3Table *p,                   /* FTS3 table handle */
126842   int iLangid,                    /* Language id */
126843   int iIndex,                     /* Index in p->aIndex[] */
126844   int iLevel                      /* Level of segments */
126845 ){
126846   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
126847   assert( iLangid>=0 );
126848   assert( p->nIndex>0 );
126849   assert( iIndex>=0 && iIndex<p->nIndex );
126850 
126851   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
126852   return iBase + iLevel;
126853 }
126854 
126855 /*
126856 ** Set *ppStmt to a statement handle that may be used to iterate through
126857 ** all rows in the %_segdir table, from oldest to newest. If successful,
126858 ** return SQLITE_OK. If an error occurs while preparing the statement,
126859 ** return an SQLite error code.
126860 **
126861 ** There is only ever one instance of this SQL statement compiled for
126862 ** each FTS3 table.
126863 **
126864 ** The statement returns the following columns from the %_segdir table:
126865 **
126866 **   0: idx
126867 **   1: start_block
126868 **   2: leaves_end_block
126869 **   3: end_block
126870 **   4: root
126871 */
126872 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
126873   Fts3Table *p,                   /* FTS3 table */
126874   int iLangid,                    /* Language being queried */
126875   int iIndex,                     /* Index for p->aIndex[] */
126876   int iLevel,                     /* Level to select (relative level) */
126877   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
126878 ){
126879   int rc;
126880   sqlite3_stmt *pStmt = 0;
126881 
126882   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
126883   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
126884   assert( iIndex>=0 && iIndex<p->nIndex );
126885 
126886   if( iLevel<0 ){
126887     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
126888     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
126889     if( rc==SQLITE_OK ){
126890       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
126891       sqlite3_bind_int64(pStmt, 2,
126892           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
126893       );
126894     }
126895   }else{
126896     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
126897     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
126898     if( rc==SQLITE_OK ){
126899       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
126900     }
126901   }
126902   *ppStmt = pStmt;
126903   return rc;
126904 }
126905 
126906 
126907 /*
126908 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
126909 ** if successful, or an SQLite error code otherwise.
126910 **
126911 ** This function also serves to allocate the PendingList structure itself.
126912 ** For example, to create a new PendingList structure containing two
126913 ** varints:
126914 **
126915 **   PendingList *p = 0;
126916 **   fts3PendingListAppendVarint(&p, 1);
126917 **   fts3PendingListAppendVarint(&p, 2);
126918 */
126919 static int fts3PendingListAppendVarint(
126920   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
126921   sqlite3_int64 i                 /* Value to append to data */
126922 ){
126923   PendingList *p = *pp;
126924 
126925   /* Allocate or grow the PendingList as required. */
126926   if( !p ){
126927     p = sqlite3_malloc(sizeof(*p) + 100);
126928     if( !p ){
126929       return SQLITE_NOMEM;
126930     }
126931     p->nSpace = 100;
126932     p->aData = (char *)&p[1];
126933     p->nData = 0;
126934   }
126935   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
126936     int nNew = p->nSpace * 2;
126937     p = sqlite3_realloc(p, sizeof(*p) + nNew);
126938     if( !p ){
126939       sqlite3_free(*pp);
126940       *pp = 0;
126941       return SQLITE_NOMEM;
126942     }
126943     p->nSpace = nNew;
126944     p->aData = (char *)&p[1];
126945   }
126946 
126947   /* Append the new serialized varint to the end of the list. */
126948   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
126949   p->aData[p->nData] = '\0';
126950   *pp = p;
126951   return SQLITE_OK;
126952 }
126953 
126954 /*
126955 ** Add a docid/column/position entry to a PendingList structure. Non-zero
126956 ** is returned if the structure is sqlite3_realloced as part of adding
126957 ** the entry. Otherwise, zero.
126958 **
126959 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
126960 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
126961 ** it is set to SQLITE_OK.
126962 */
126963 static int fts3PendingListAppend(
126964   PendingList **pp,               /* IN/OUT: PendingList structure */
126965   sqlite3_int64 iDocid,           /* Docid for entry to add */
126966   sqlite3_int64 iCol,             /* Column for entry to add */
126967   sqlite3_int64 iPos,             /* Position of term for entry to add */
126968   int *pRc                        /* OUT: Return code */
126969 ){
126970   PendingList *p = *pp;
126971   int rc = SQLITE_OK;
126972 
126973   assert( !p || p->iLastDocid<=iDocid );
126974 
126975   if( !p || p->iLastDocid!=iDocid ){
126976     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
126977     if( p ){
126978       assert( p->nData<p->nSpace );
126979       assert( p->aData[p->nData]==0 );
126980       p->nData++;
126981     }
126982     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
126983       goto pendinglistappend_out;
126984     }
126985     p->iLastCol = -1;
126986     p->iLastPos = 0;
126987     p->iLastDocid = iDocid;
126988   }
126989   if( iCol>0 && p->iLastCol!=iCol ){
126990     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
126991      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
126992     ){
126993       goto pendinglistappend_out;
126994     }
126995     p->iLastCol = iCol;
126996     p->iLastPos = 0;
126997   }
126998   if( iCol>=0 ){
126999     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
127000     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
127001     if( rc==SQLITE_OK ){
127002       p->iLastPos = iPos;
127003     }
127004   }
127005 
127006  pendinglistappend_out:
127007   *pRc = rc;
127008   if( p!=*pp ){
127009     *pp = p;
127010     return 1;
127011   }
127012   return 0;
127013 }
127014 
127015 /*
127016 ** Free a PendingList object allocated by fts3PendingListAppend().
127017 */
127018 static void fts3PendingListDelete(PendingList *pList){
127019   sqlite3_free(pList);
127020 }
127021 
127022 /*
127023 ** Add an entry to one of the pending-terms hash tables.
127024 */
127025 static int fts3PendingTermsAddOne(
127026   Fts3Table *p,
127027   int iCol,
127028   int iPos,
127029   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
127030   const char *zToken,
127031   int nToken
127032 ){
127033   PendingList *pList;
127034   int rc = SQLITE_OK;
127035 
127036   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
127037   if( pList ){
127038     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
127039   }
127040   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
127041     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
127042       /* Malloc failed while inserting the new entry. This can only
127043       ** happen if there was no previous entry for this token.
127044       */
127045       assert( 0==fts3HashFind(pHash, zToken, nToken) );
127046       sqlite3_free(pList);
127047       rc = SQLITE_NOMEM;
127048     }
127049   }
127050   if( rc==SQLITE_OK ){
127051     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
127052   }
127053   return rc;
127054 }
127055 
127056 /*
127057 ** Tokenize the nul-terminated string zText and add all tokens to the
127058 ** pending-terms hash-table. The docid used is that currently stored in
127059 ** p->iPrevDocid, and the column is specified by argument iCol.
127060 **
127061 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
127062 */
127063 static int fts3PendingTermsAdd(
127064   Fts3Table *p,                   /* Table into which text will be inserted */
127065   int iLangid,                    /* Language id to use */
127066   const char *zText,              /* Text of document to be inserted */
127067   int iCol,                       /* Column into which text is being inserted */
127068   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
127069 ){
127070   int rc;
127071   int iStart = 0;
127072   int iEnd = 0;
127073   int iPos = 0;
127074   int nWord = 0;
127075 
127076   char const *zToken;
127077   int nToken = 0;
127078 
127079   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
127080   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
127081   sqlite3_tokenizer_cursor *pCsr;
127082   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
127083       const char**,int*,int*,int*,int*);
127084 
127085   assert( pTokenizer && pModule );
127086 
127087   /* If the user has inserted a NULL value, this function may be called with
127088   ** zText==0. In this case, add zero token entries to the hash table and
127089   ** return early. */
127090   if( zText==0 ){
127091     *pnWord = 0;
127092     return SQLITE_OK;
127093   }
127094 
127095   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
127096   if( rc!=SQLITE_OK ){
127097     return rc;
127098   }
127099 
127100   xNext = pModule->xNext;
127101   while( SQLITE_OK==rc
127102       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
127103   ){
127104     int i;
127105     if( iPos>=nWord ) nWord = iPos+1;
127106 
127107     /* Positions cannot be negative; we use -1 as a terminator internally.
127108     ** Tokens must have a non-zero length.
127109     */
127110     if( iPos<0 || !zToken || nToken<=0 ){
127111       rc = SQLITE_ERROR;
127112       break;
127113     }
127114 
127115     /* Add the term to the terms index */
127116     rc = fts3PendingTermsAddOne(
127117         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
127118     );
127119 
127120     /* Add the term to each of the prefix indexes that it is not too
127121     ** short for. */
127122     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
127123       struct Fts3Index *pIndex = &p->aIndex[i];
127124       if( nToken<pIndex->nPrefix ) continue;
127125       rc = fts3PendingTermsAddOne(
127126           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
127127       );
127128     }
127129   }
127130 
127131   pModule->xClose(pCsr);
127132   *pnWord += nWord;
127133   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
127134 }
127135 
127136 /*
127137 ** Calling this function indicates that subsequent calls to
127138 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
127139 ** contents of the document with docid iDocid.
127140 */
127141 static int fts3PendingTermsDocid(
127142   Fts3Table *p,                   /* Full-text table handle */
127143   int iLangid,                    /* Language id of row being written */
127144   sqlite_int64 iDocid             /* Docid of row being written */
127145 ){
127146   assert( iLangid>=0 );
127147 
127148   /* TODO(shess) Explore whether partially flushing the buffer on
127149   ** forced-flush would provide better performance.  I suspect that if
127150   ** we ordered the doclists by size and flushed the largest until the
127151   ** buffer was half empty, that would let the less frequent terms
127152   ** generate longer doclists.
127153   */
127154   if( iDocid<=p->iPrevDocid
127155    || p->iPrevLangid!=iLangid
127156    || p->nPendingData>p->nMaxPendingData
127157   ){
127158     int rc = sqlite3Fts3PendingTermsFlush(p);
127159     if( rc!=SQLITE_OK ) return rc;
127160   }
127161   p->iPrevDocid = iDocid;
127162   p->iPrevLangid = iLangid;
127163   return SQLITE_OK;
127164 }
127165 
127166 /*
127167 ** Discard the contents of the pending-terms hash tables.
127168 */
127169 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
127170   int i;
127171   for(i=0; i<p->nIndex; i++){
127172     Fts3HashElem *pElem;
127173     Fts3Hash *pHash = &p->aIndex[i].hPending;
127174     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
127175       PendingList *pList = (PendingList *)fts3HashData(pElem);
127176       fts3PendingListDelete(pList);
127177     }
127178     fts3HashClear(pHash);
127179   }
127180   p->nPendingData = 0;
127181 }
127182 
127183 /*
127184 ** This function is called by the xUpdate() method as part of an INSERT
127185 ** operation. It adds entries for each term in the new record to the
127186 ** pendingTerms hash table.
127187 **
127188 ** Argument apVal is the same as the similarly named argument passed to
127189 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
127190 */
127191 static int fts3InsertTerms(
127192   Fts3Table *p,
127193   int iLangid,
127194   sqlite3_value **apVal,
127195   u32 *aSz
127196 ){
127197   int i;                          /* Iterator variable */
127198   for(i=2; i<p->nColumn+2; i++){
127199     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
127200     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
127201     if( rc!=SQLITE_OK ){
127202       return rc;
127203     }
127204     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
127205   }
127206   return SQLITE_OK;
127207 }
127208 
127209 /*
127210 ** This function is called by the xUpdate() method for an INSERT operation.
127211 ** The apVal parameter is passed a copy of the apVal argument passed by
127212 ** SQLite to the xUpdate() method. i.e:
127213 **
127214 **   apVal[0]                Not used for INSERT.
127215 **   apVal[1]                rowid
127216 **   apVal[2]                Left-most user-defined column
127217 **   ...
127218 **   apVal[p->nColumn+1]     Right-most user-defined column
127219 **   apVal[p->nColumn+2]     Hidden column with same name as table
127220 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
127221 **   apVal[p->nColumn+4]     Hidden languageid column
127222 */
127223 static int fts3InsertData(
127224   Fts3Table *p,                   /* Full-text table */
127225   sqlite3_value **apVal,          /* Array of values to insert */
127226   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
127227 ){
127228   int rc;                         /* Return code */
127229   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
127230 
127231   if( p->zContentTbl ){
127232     sqlite3_value *pRowid = apVal[p->nColumn+3];
127233     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
127234       pRowid = apVal[1];
127235     }
127236     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
127237       return SQLITE_CONSTRAINT;
127238     }
127239     *piDocid = sqlite3_value_int64(pRowid);
127240     return SQLITE_OK;
127241   }
127242 
127243   /* Locate the statement handle used to insert data into the %_content
127244   ** table. The SQL for this statement is:
127245   **
127246   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
127247   **
127248   ** The statement features N '?' variables, where N is the number of user
127249   ** defined columns in the FTS3 table, plus one for the docid field.
127250   */
127251   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
127252   if( rc==SQLITE_OK && p->zLanguageid ){
127253     rc = sqlite3_bind_int(
127254         pContentInsert, p->nColumn+2,
127255         sqlite3_value_int(apVal[p->nColumn+4])
127256     );
127257   }
127258   if( rc!=SQLITE_OK ) return rc;
127259 
127260   /* There is a quirk here. The users INSERT statement may have specified
127261   ** a value for the "rowid" field, for the "docid" field, or for both.
127262   ** Which is a problem, since "rowid" and "docid" are aliases for the
127263   ** same value. For example:
127264   **
127265   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
127266   **
127267   ** In FTS3, this is an error. It is an error to specify non-NULL values
127268   ** for both docid and some other rowid alias.
127269   */
127270   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
127271     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
127272      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
127273     ){
127274       /* A rowid/docid conflict. */
127275       return SQLITE_ERROR;
127276     }
127277     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
127278     if( rc!=SQLITE_OK ) return rc;
127279   }
127280 
127281   /* Execute the statement to insert the record. Set *piDocid to the
127282   ** new docid value.
127283   */
127284   sqlite3_step(pContentInsert);
127285   rc = sqlite3_reset(pContentInsert);
127286 
127287   *piDocid = sqlite3_last_insert_rowid(p->db);
127288   return rc;
127289 }
127290 
127291 
127292 
127293 /*
127294 ** Remove all data from the FTS3 table. Clear the hash table containing
127295 ** pending terms.
127296 */
127297 static int fts3DeleteAll(Fts3Table *p, int bContent){
127298   int rc = SQLITE_OK;             /* Return code */
127299 
127300   /* Discard the contents of the pending-terms hash table. */
127301   sqlite3Fts3PendingTermsClear(p);
127302 
127303   /* Delete everything from the shadow tables. Except, leave %_content as
127304   ** is if bContent is false.  */
127305   assert( p->zContentTbl==0 || bContent==0 );
127306   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
127307   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
127308   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
127309   if( p->bHasDocsize ){
127310     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
127311   }
127312   if( p->bHasStat ){
127313     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
127314   }
127315   return rc;
127316 }
127317 
127318 /*
127319 **
127320 */
127321 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
127322   int iLangid = 0;
127323   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
127324   return iLangid;
127325 }
127326 
127327 /*
127328 ** The first element in the apVal[] array is assumed to contain the docid
127329 ** (an integer) of a row about to be deleted. Remove all terms from the
127330 ** full-text index.
127331 */
127332 static void fts3DeleteTerms(
127333   int *pRC,               /* Result code */
127334   Fts3Table *p,           /* The FTS table to delete from */
127335   sqlite3_value *pRowid,  /* The docid to be deleted */
127336   u32 *aSz,               /* Sizes of deleted document written here */
127337   int *pbFound            /* OUT: Set to true if row really does exist */
127338 ){
127339   int rc;
127340   sqlite3_stmt *pSelect;
127341 
127342   assert( *pbFound==0 );
127343   if( *pRC ) return;
127344   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
127345   if( rc==SQLITE_OK ){
127346     if( SQLITE_ROW==sqlite3_step(pSelect) ){
127347       int i;
127348       int iLangid = langidFromSelect(p, pSelect);
127349       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
127350       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
127351         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
127352         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
127353         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
127354       }
127355       if( rc!=SQLITE_OK ){
127356         sqlite3_reset(pSelect);
127357         *pRC = rc;
127358         return;
127359       }
127360       *pbFound = 1;
127361     }
127362     rc = sqlite3_reset(pSelect);
127363   }else{
127364     sqlite3_reset(pSelect);
127365   }
127366   *pRC = rc;
127367 }
127368 
127369 /*
127370 ** Forward declaration to account for the circular dependency between
127371 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
127372 */
127373 static int fts3SegmentMerge(Fts3Table *, int, int, int);
127374 
127375 /*
127376 ** This function allocates a new level iLevel index in the segdir table.
127377 ** Usually, indexes are allocated within a level sequentially starting
127378 ** with 0, so the allocated index is one greater than the value returned
127379 ** by:
127380 **
127381 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
127382 **
127383 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
127384 ** level, they are merged into a single level (iLevel+1) segment and the
127385 ** allocated index is 0.
127386 **
127387 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
127388 ** returned. Otherwise, an SQLite error code is returned.
127389 */
127390 static int fts3AllocateSegdirIdx(
127391   Fts3Table *p,
127392   int iLangid,                    /* Language id */
127393   int iIndex,                     /* Index for p->aIndex */
127394   int iLevel,
127395   int *piIdx
127396 ){
127397   int rc;                         /* Return Code */
127398   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
127399   int iNext = 0;                  /* Result of query pNextIdx */
127400 
127401   assert( iLangid>=0 );
127402   assert( p->nIndex>=1 );
127403 
127404   /* Set variable iNext to the next available segdir index at level iLevel. */
127405   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
127406   if( rc==SQLITE_OK ){
127407     sqlite3_bind_int64(
127408         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
127409     );
127410     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
127411       iNext = sqlite3_column_int(pNextIdx, 0);
127412     }
127413     rc = sqlite3_reset(pNextIdx);
127414   }
127415 
127416   if( rc==SQLITE_OK ){
127417     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
127418     ** full, merge all segments in level iLevel into a single iLevel+1
127419     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
127420     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
127421     */
127422     if( iNext>=FTS3_MERGE_COUNT ){
127423       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
127424       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
127425       *piIdx = 0;
127426     }else{
127427       *piIdx = iNext;
127428     }
127429   }
127430 
127431   return rc;
127432 }
127433 
127434 /*
127435 ** The %_segments table is declared as follows:
127436 **
127437 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
127438 **
127439 ** This function reads data from a single row of the %_segments table. The
127440 ** specific row is identified by the iBlockid parameter. If paBlob is not
127441 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
127442 ** with the contents of the blob stored in the "block" column of the
127443 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
127444 ** to the size of the blob in bytes before returning.
127445 **
127446 ** If an error occurs, or the table does not contain the specified row,
127447 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
127448 ** paBlob is non-NULL, then it is the responsibility of the caller to
127449 ** eventually free the returned buffer.
127450 **
127451 ** This function may leave an open sqlite3_blob* handle in the
127452 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
127453 ** to this function. The handle may be closed by calling the
127454 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
127455 ** performance improvement, but the blob handle should always be closed
127456 ** before control is returned to the user (to prevent a lock being held
127457 ** on the database file for longer than necessary). Thus, any virtual table
127458 ** method (xFilter etc.) that may directly or indirectly call this function
127459 ** must call sqlite3Fts3SegmentsClose() before returning.
127460 */
127461 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
127462   Fts3Table *p,                   /* FTS3 table handle */
127463   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
127464   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
127465   int *pnBlob,                    /* OUT: Size of blob data */
127466   int *pnLoad                     /* OUT: Bytes actually loaded */
127467 ){
127468   int rc;                         /* Return code */
127469 
127470   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
127471   assert( pnBlob );
127472 
127473   if( p->pSegments ){
127474     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
127475   }else{
127476     if( 0==p->zSegmentsTbl ){
127477       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
127478       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
127479     }
127480     rc = sqlite3_blob_open(
127481        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
127482     );
127483   }
127484 
127485   if( rc==SQLITE_OK ){
127486     int nByte = sqlite3_blob_bytes(p->pSegments);
127487     *pnBlob = nByte;
127488     if( paBlob ){
127489       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
127490       if( !aByte ){
127491         rc = SQLITE_NOMEM;
127492       }else{
127493         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
127494           nByte = FTS3_NODE_CHUNKSIZE;
127495           *pnLoad = nByte;
127496         }
127497         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
127498         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
127499         if( rc!=SQLITE_OK ){
127500           sqlite3_free(aByte);
127501           aByte = 0;
127502         }
127503       }
127504       *paBlob = aByte;
127505     }
127506   }
127507 
127508   return rc;
127509 }
127510 
127511 /*
127512 ** Close the blob handle at p->pSegments, if it is open. See comments above
127513 ** the sqlite3Fts3ReadBlock() function for details.
127514 */
127515 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
127516   sqlite3_blob_close(p->pSegments);
127517   p->pSegments = 0;
127518 }
127519 
127520 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
127521   int nRead;                      /* Number of bytes to read */
127522   int rc;                         /* Return code */
127523 
127524   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
127525   rc = sqlite3_blob_read(
127526       pReader->pBlob,
127527       &pReader->aNode[pReader->nPopulate],
127528       nRead,
127529       pReader->nPopulate
127530   );
127531 
127532   if( rc==SQLITE_OK ){
127533     pReader->nPopulate += nRead;
127534     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
127535     if( pReader->nPopulate==pReader->nNode ){
127536       sqlite3_blob_close(pReader->pBlob);
127537       pReader->pBlob = 0;
127538       pReader->nPopulate = 0;
127539     }
127540   }
127541   return rc;
127542 }
127543 
127544 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
127545   int rc = SQLITE_OK;
127546   assert( !pReader->pBlob
127547        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
127548   );
127549   while( pReader->pBlob && rc==SQLITE_OK
127550      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
127551   ){
127552     rc = fts3SegReaderIncrRead(pReader);
127553   }
127554   return rc;
127555 }
127556 
127557 /*
127558 ** Set an Fts3SegReader cursor to point at EOF.
127559 */
127560 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
127561   if( !fts3SegReaderIsRootOnly(pSeg) ){
127562     sqlite3_free(pSeg->aNode);
127563     sqlite3_blob_close(pSeg->pBlob);
127564     pSeg->pBlob = 0;
127565   }
127566   pSeg->aNode = 0;
127567 }
127568 
127569 /*
127570 ** Move the iterator passed as the first argument to the next term in the
127571 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
127572 ** SQLITE_DONE. Otherwise, an SQLite error code.
127573 */
127574 static int fts3SegReaderNext(
127575   Fts3Table *p,
127576   Fts3SegReader *pReader,
127577   int bIncr
127578 ){
127579   int rc;                         /* Return code of various sub-routines */
127580   char *pNext;                    /* Cursor variable */
127581   int nPrefix;                    /* Number of bytes in term prefix */
127582   int nSuffix;                    /* Number of bytes in term suffix */
127583 
127584   if( !pReader->aDoclist ){
127585     pNext = pReader->aNode;
127586   }else{
127587     pNext = &pReader->aDoclist[pReader->nDoclist];
127588   }
127589 
127590   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
127591 
127592     if( fts3SegReaderIsPending(pReader) ){
127593       Fts3HashElem *pElem = *(pReader->ppNextElem);
127594       if( pElem==0 ){
127595         pReader->aNode = 0;
127596       }else{
127597         PendingList *pList = (PendingList *)fts3HashData(pElem);
127598         pReader->zTerm = (char *)fts3HashKey(pElem);
127599         pReader->nTerm = fts3HashKeysize(pElem);
127600         pReader->nNode = pReader->nDoclist = pList->nData + 1;
127601         pReader->aNode = pReader->aDoclist = pList->aData;
127602         pReader->ppNextElem++;
127603         assert( pReader->aNode );
127604       }
127605       return SQLITE_OK;
127606     }
127607 
127608     fts3SegReaderSetEof(pReader);
127609 
127610     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
127611     ** blocks have already been traversed.  */
127612     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
127613     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
127614       return SQLITE_OK;
127615     }
127616 
127617     rc = sqlite3Fts3ReadBlock(
127618         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
127619         (bIncr ? &pReader->nPopulate : 0)
127620     );
127621     if( rc!=SQLITE_OK ) return rc;
127622     assert( pReader->pBlob==0 );
127623     if( bIncr && pReader->nPopulate<pReader->nNode ){
127624       pReader->pBlob = p->pSegments;
127625       p->pSegments = 0;
127626     }
127627     pNext = pReader->aNode;
127628   }
127629 
127630   assert( !fts3SegReaderIsPending(pReader) );
127631 
127632   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
127633   if( rc!=SQLITE_OK ) return rc;
127634 
127635   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
127636   ** safe (no risk of overread) even if the node data is corrupted. */
127637   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
127638   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
127639   if( nPrefix<0 || nSuffix<=0
127640    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
127641   ){
127642     return FTS_CORRUPT_VTAB;
127643   }
127644 
127645   if( nPrefix+nSuffix>pReader->nTermAlloc ){
127646     int nNew = (nPrefix+nSuffix)*2;
127647     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
127648     if( !zNew ){
127649       return SQLITE_NOMEM;
127650     }
127651     pReader->zTerm = zNew;
127652     pReader->nTermAlloc = nNew;
127653   }
127654 
127655   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
127656   if( rc!=SQLITE_OK ) return rc;
127657 
127658   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
127659   pReader->nTerm = nPrefix+nSuffix;
127660   pNext += nSuffix;
127661   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
127662   pReader->aDoclist = pNext;
127663   pReader->pOffsetList = 0;
127664 
127665   /* Check that the doclist does not appear to extend past the end of the
127666   ** b-tree node. And that the final byte of the doclist is 0x00. If either
127667   ** of these statements is untrue, then the data structure is corrupt.
127668   */
127669   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
127670    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
127671   ){
127672     return FTS_CORRUPT_VTAB;
127673   }
127674   return SQLITE_OK;
127675 }
127676 
127677 /*
127678 ** Set the SegReader to point to the first docid in the doclist associated
127679 ** with the current term.
127680 */
127681 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
127682   int rc = SQLITE_OK;
127683   assert( pReader->aDoclist );
127684   assert( !pReader->pOffsetList );
127685   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127686     u8 bEof = 0;
127687     pReader->iDocid = 0;
127688     pReader->nOffsetList = 0;
127689     sqlite3Fts3DoclistPrev(0,
127690         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
127691         &pReader->iDocid, &pReader->nOffsetList, &bEof
127692     );
127693   }else{
127694     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
127695     if( rc==SQLITE_OK ){
127696       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
127697       pReader->pOffsetList = &pReader->aDoclist[n];
127698     }
127699   }
127700   return rc;
127701 }
127702 
127703 /*
127704 ** Advance the SegReader to point to the next docid in the doclist
127705 ** associated with the current term.
127706 **
127707 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
127708 ** *ppOffsetList is set to point to the first column-offset list
127709 ** in the doclist entry (i.e. immediately past the docid varint).
127710 ** *pnOffsetList is set to the length of the set of column-offset
127711 ** lists, not including the nul-terminator byte. For example:
127712 */
127713 static int fts3SegReaderNextDocid(
127714   Fts3Table *pTab,
127715   Fts3SegReader *pReader,         /* Reader to advance to next docid */
127716   char **ppOffsetList,            /* OUT: Pointer to current position-list */
127717   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
127718 ){
127719   int rc = SQLITE_OK;
127720   char *p = pReader->pOffsetList;
127721   char c = 0;
127722 
127723   assert( p );
127724 
127725   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
127726     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
127727     ** Pending-terms doclists are always built up in ascending order, so
127728     ** we have to iterate through them backwards here. */
127729     u8 bEof = 0;
127730     if( ppOffsetList ){
127731       *ppOffsetList = pReader->pOffsetList;
127732       *pnOffsetList = pReader->nOffsetList - 1;
127733     }
127734     sqlite3Fts3DoclistPrev(0,
127735         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
127736         &pReader->nOffsetList, &bEof
127737     );
127738     if( bEof ){
127739       pReader->pOffsetList = 0;
127740     }else{
127741       pReader->pOffsetList = p;
127742     }
127743   }else{
127744     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
127745 
127746     /* Pointer p currently points at the first byte of an offset list. The
127747     ** following block advances it to point one byte past the end of
127748     ** the same offset list. */
127749     while( 1 ){
127750 
127751       /* The following line of code (and the "p++" below the while() loop) is
127752       ** normally all that is required to move pointer p to the desired
127753       ** position. The exception is if this node is being loaded from disk
127754       ** incrementally and pointer "p" now points to the first byte passed
127755       ** the populated part of pReader->aNode[].
127756       */
127757       while( *p | c ) c = *p++ & 0x80;
127758       assert( *p==0 );
127759 
127760       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
127761       rc = fts3SegReaderIncrRead(pReader);
127762       if( rc!=SQLITE_OK ) return rc;
127763     }
127764     p++;
127765 
127766     /* If required, populate the output variables with a pointer to and the
127767     ** size of the previous offset-list.
127768     */
127769     if( ppOffsetList ){
127770       *ppOffsetList = pReader->pOffsetList;
127771       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
127772     }
127773 
127774     /* List may have been edited in place by fts3EvalNearTrim() */
127775     while( p<pEnd && *p==0 ) p++;
127776 
127777     /* If there are no more entries in the doclist, set pOffsetList to
127778     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
127779     ** Fts3SegReader.pOffsetList to point to the next offset list before
127780     ** returning.
127781     */
127782     if( p>=pEnd ){
127783       pReader->pOffsetList = 0;
127784     }else{
127785       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
127786       if( rc==SQLITE_OK ){
127787         sqlite3_int64 iDelta;
127788         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
127789         if( pTab->bDescIdx ){
127790           pReader->iDocid -= iDelta;
127791         }else{
127792           pReader->iDocid += iDelta;
127793         }
127794       }
127795     }
127796   }
127797 
127798   return SQLITE_OK;
127799 }
127800 
127801 
127802 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
127803   Fts3Cursor *pCsr,
127804   Fts3MultiSegReader *pMsr,
127805   int *pnOvfl
127806 ){
127807   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
127808   int nOvfl = 0;
127809   int ii;
127810   int rc = SQLITE_OK;
127811   int pgsz = p->nPgsz;
127812 
127813   assert( p->bFts4 );
127814   assert( pgsz>0 );
127815 
127816   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
127817     Fts3SegReader *pReader = pMsr->apSegment[ii];
127818     if( !fts3SegReaderIsPending(pReader)
127819      && !fts3SegReaderIsRootOnly(pReader)
127820     ){
127821       sqlite3_int64 jj;
127822       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
127823         int nBlob;
127824         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
127825         if( rc!=SQLITE_OK ) break;
127826         if( (nBlob+35)>pgsz ){
127827           nOvfl += (nBlob + 34)/pgsz;
127828         }
127829       }
127830     }
127831   }
127832   *pnOvfl = nOvfl;
127833   return rc;
127834 }
127835 
127836 /*
127837 ** Free all allocations associated with the iterator passed as the
127838 ** second argument.
127839 */
127840 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
127841   if( pReader && !fts3SegReaderIsPending(pReader) ){
127842     sqlite3_free(pReader->zTerm);
127843     if( !fts3SegReaderIsRootOnly(pReader) ){
127844       sqlite3_free(pReader->aNode);
127845       sqlite3_blob_close(pReader->pBlob);
127846     }
127847   }
127848   sqlite3_free(pReader);
127849 }
127850 
127851 /*
127852 ** Allocate a new SegReader object.
127853 */
127854 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
127855   int iAge,                       /* Segment "age". */
127856   int bLookup,                    /* True for a lookup only */
127857   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
127858   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
127859   sqlite3_int64 iEndBlock,        /* Final block of segment */
127860   const char *zRoot,              /* Buffer containing root node */
127861   int nRoot,                      /* Size of buffer containing root node */
127862   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
127863 ){
127864   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
127865   int nExtra = 0;                 /* Bytes to allocate segment root node */
127866 
127867   assert( iStartLeaf<=iEndLeaf );
127868   if( iStartLeaf==0 ){
127869     nExtra = nRoot + FTS3_NODE_PADDING;
127870   }
127871 
127872   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
127873   if( !pReader ){
127874     return SQLITE_NOMEM;
127875   }
127876   memset(pReader, 0, sizeof(Fts3SegReader));
127877   pReader->iIdx = iAge;
127878   pReader->bLookup = bLookup!=0;
127879   pReader->iStartBlock = iStartLeaf;
127880   pReader->iLeafEndBlock = iEndLeaf;
127881   pReader->iEndBlock = iEndBlock;
127882 
127883   if( nExtra ){
127884     /* The entire segment is stored in the root node. */
127885     pReader->aNode = (char *)&pReader[1];
127886     pReader->rootOnly = 1;
127887     pReader->nNode = nRoot;
127888     memcpy(pReader->aNode, zRoot, nRoot);
127889     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
127890   }else{
127891     pReader->iCurrentBlock = iStartLeaf-1;
127892   }
127893   *ppReader = pReader;
127894   return SQLITE_OK;
127895 }
127896 
127897 /*
127898 ** This is a comparison function used as a qsort() callback when sorting
127899 ** an array of pending terms by term. This occurs as part of flushing
127900 ** the contents of the pending-terms hash table to the database.
127901 */
127902 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
127903   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
127904   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
127905   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
127906   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
127907 
127908   int n = (n1<n2 ? n1 : n2);
127909   int c = memcmp(z1, z2, n);
127910   if( c==0 ){
127911     c = n1 - n2;
127912   }
127913   return c;
127914 }
127915 
127916 /*
127917 ** This function is used to allocate an Fts3SegReader that iterates through
127918 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
127919 **
127920 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
127921 ** through each term in the pending-terms table. Or, if isPrefixIter is
127922 ** non-zero, it iterates through each term and its prefixes. For example, if
127923 ** the pending terms hash table contains the terms "sqlite", "mysql" and
127924 ** "firebird", then the iterator visits the following 'terms' (in the order
127925 ** shown):
127926 **
127927 **   f fi fir fire fireb firebi firebir firebird
127928 **   m my mys mysq mysql
127929 **   s sq sql sqli sqlit sqlite
127930 **
127931 ** Whereas if isPrefixIter is zero, the terms visited are:
127932 **
127933 **   firebird mysql sqlite
127934 */
127935 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
127936   Fts3Table *p,                   /* Virtual table handle */
127937   int iIndex,                     /* Index for p->aIndex */
127938   const char *zTerm,              /* Term to search for */
127939   int nTerm,                      /* Size of buffer zTerm */
127940   int bPrefix,                    /* True for a prefix iterator */
127941   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
127942 ){
127943   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
127944   Fts3HashElem *pE;               /* Iterator variable */
127945   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
127946   int nElem = 0;                  /* Size of array at aElem */
127947   int rc = SQLITE_OK;             /* Return Code */
127948   Fts3Hash *pHash;
127949 
127950   pHash = &p->aIndex[iIndex].hPending;
127951   if( bPrefix ){
127952     int nAlloc = 0;               /* Size of allocated array at aElem */
127953 
127954     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
127955       char *zKey = (char *)fts3HashKey(pE);
127956       int nKey = fts3HashKeysize(pE);
127957       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
127958         if( nElem==nAlloc ){
127959           Fts3HashElem **aElem2;
127960           nAlloc += 16;
127961           aElem2 = (Fts3HashElem **)sqlite3_realloc(
127962               aElem, nAlloc*sizeof(Fts3HashElem *)
127963           );
127964           if( !aElem2 ){
127965             rc = SQLITE_NOMEM;
127966             nElem = 0;
127967             break;
127968           }
127969           aElem = aElem2;
127970         }
127971 
127972         aElem[nElem++] = pE;
127973       }
127974     }
127975 
127976     /* If more than one term matches the prefix, sort the Fts3HashElem
127977     ** objects in term order using qsort(). This uses the same comparison
127978     ** callback as is used when flushing terms to disk.
127979     */
127980     if( nElem>1 ){
127981       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
127982     }
127983 
127984   }else{
127985     /* The query is a simple term lookup that matches at most one term in
127986     ** the index. All that is required is a straight hash-lookup.
127987     **
127988     ** Because the stack address of pE may be accessed via the aElem pointer
127989     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
127990     ** within this entire function, not just this "else{...}" block.
127991     */
127992     pE = fts3HashFindElem(pHash, zTerm, nTerm);
127993     if( pE ){
127994       aElem = &pE;
127995       nElem = 1;
127996     }
127997   }
127998 
127999   if( nElem>0 ){
128000     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
128001     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
128002     if( !pReader ){
128003       rc = SQLITE_NOMEM;
128004     }else{
128005       memset(pReader, 0, nByte);
128006       pReader->iIdx = 0x7FFFFFFF;
128007       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
128008       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
128009     }
128010   }
128011 
128012   if( bPrefix ){
128013     sqlite3_free(aElem);
128014   }
128015   *ppReader = pReader;
128016   return rc;
128017 }
128018 
128019 /*
128020 ** Compare the entries pointed to by two Fts3SegReader structures.
128021 ** Comparison is as follows:
128022 **
128023 **   1) EOF is greater than not EOF.
128024 **
128025 **   2) The current terms (if any) are compared using memcmp(). If one
128026 **      term is a prefix of another, the longer term is considered the
128027 **      larger.
128028 **
128029 **   3) By segment age. An older segment is considered larger.
128030 */
128031 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128032   int rc;
128033   if( pLhs->aNode && pRhs->aNode ){
128034     int rc2 = pLhs->nTerm - pRhs->nTerm;
128035     if( rc2<0 ){
128036       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
128037     }else{
128038       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
128039     }
128040     if( rc==0 ){
128041       rc = rc2;
128042     }
128043   }else{
128044     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
128045   }
128046   if( rc==0 ){
128047     rc = pRhs->iIdx - pLhs->iIdx;
128048   }
128049   assert( rc!=0 );
128050   return rc;
128051 }
128052 
128053 /*
128054 ** A different comparison function for SegReader structures. In this
128055 ** version, it is assumed that each SegReader points to an entry in
128056 ** a doclist for identical terms. Comparison is made as follows:
128057 **
128058 **   1) EOF (end of doclist in this case) is greater than not EOF.
128059 **
128060 **   2) By current docid.
128061 **
128062 **   3) By segment age. An older segment is considered larger.
128063 */
128064 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128065   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
128066   if( rc==0 ){
128067     if( pLhs->iDocid==pRhs->iDocid ){
128068       rc = pRhs->iIdx - pLhs->iIdx;
128069     }else{
128070       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
128071     }
128072   }
128073   assert( pLhs->aNode && pRhs->aNode );
128074   return rc;
128075 }
128076 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
128077   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
128078   if( rc==0 ){
128079     if( pLhs->iDocid==pRhs->iDocid ){
128080       rc = pRhs->iIdx - pLhs->iIdx;
128081     }else{
128082       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
128083     }
128084   }
128085   assert( pLhs->aNode && pRhs->aNode );
128086   return rc;
128087 }
128088 
128089 /*
128090 ** Compare the term that the Fts3SegReader object passed as the first argument
128091 ** points to with the term specified by arguments zTerm and nTerm.
128092 **
128093 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
128094 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
128095 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
128096 */
128097 static int fts3SegReaderTermCmp(
128098   Fts3SegReader *pSeg,            /* Segment reader object */
128099   const char *zTerm,              /* Term to compare to */
128100   int nTerm                       /* Size of term zTerm in bytes */
128101 ){
128102   int res = 0;
128103   if( pSeg->aNode ){
128104     if( pSeg->nTerm>nTerm ){
128105       res = memcmp(pSeg->zTerm, zTerm, nTerm);
128106     }else{
128107       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
128108     }
128109     if( res==0 ){
128110       res = pSeg->nTerm-nTerm;
128111     }
128112   }
128113   return res;
128114 }
128115 
128116 /*
128117 ** Argument apSegment is an array of nSegment elements. It is known that
128118 ** the final (nSegment-nSuspect) members are already in sorted order
128119 ** (according to the comparison function provided). This function shuffles
128120 ** the array around until all entries are in sorted order.
128121 */
128122 static void fts3SegReaderSort(
128123   Fts3SegReader **apSegment,                     /* Array to sort entries of */
128124   int nSegment,                                  /* Size of apSegment array */
128125   int nSuspect,                                  /* Unsorted entry count */
128126   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
128127 ){
128128   int i;                          /* Iterator variable */
128129 
128130   assert( nSuspect<=nSegment );
128131 
128132   if( nSuspect==nSegment ) nSuspect--;
128133   for(i=nSuspect-1; i>=0; i--){
128134     int j;
128135     for(j=i; j<(nSegment-1); j++){
128136       Fts3SegReader *pTmp;
128137       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
128138       pTmp = apSegment[j+1];
128139       apSegment[j+1] = apSegment[j];
128140       apSegment[j] = pTmp;
128141     }
128142   }
128143 
128144 #ifndef NDEBUG
128145   /* Check that the list really is sorted now. */
128146   for(i=0; i<(nSuspect-1); i++){
128147     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
128148   }
128149 #endif
128150 }
128151 
128152 /*
128153 ** Insert a record into the %_segments table.
128154 */
128155 static int fts3WriteSegment(
128156   Fts3Table *p,                   /* Virtual table handle */
128157   sqlite3_int64 iBlock,           /* Block id for new block */
128158   char *z,                        /* Pointer to buffer containing block data */
128159   int n                           /* Size of buffer z in bytes */
128160 ){
128161   sqlite3_stmt *pStmt;
128162   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
128163   if( rc==SQLITE_OK ){
128164     sqlite3_bind_int64(pStmt, 1, iBlock);
128165     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
128166     sqlite3_step(pStmt);
128167     rc = sqlite3_reset(pStmt);
128168   }
128169   return rc;
128170 }
128171 
128172 /*
128173 ** Find the largest relative level number in the table. If successful, set
128174 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
128175 ** set *pnMax to zero and return an SQLite error code.
128176 */
128177 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
128178   int rc;
128179   int mxLevel = 0;
128180   sqlite3_stmt *pStmt = 0;
128181 
128182   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
128183   if( rc==SQLITE_OK ){
128184     if( SQLITE_ROW==sqlite3_step(pStmt) ){
128185       mxLevel = sqlite3_column_int(pStmt, 0);
128186     }
128187     rc = sqlite3_reset(pStmt);
128188   }
128189   *pnMax = mxLevel;
128190   return rc;
128191 }
128192 
128193 /*
128194 ** Insert a record into the %_segdir table.
128195 */
128196 static int fts3WriteSegdir(
128197   Fts3Table *p,                   /* Virtual table handle */
128198   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
128199   int iIdx,                       /* Value for "idx" field */
128200   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
128201   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
128202   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
128203   char *zRoot,                    /* Blob value for "root" field */
128204   int nRoot                       /* Number of bytes in buffer zRoot */
128205 ){
128206   sqlite3_stmt *pStmt;
128207   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
128208   if( rc==SQLITE_OK ){
128209     sqlite3_bind_int64(pStmt, 1, iLevel);
128210     sqlite3_bind_int(pStmt, 2, iIdx);
128211     sqlite3_bind_int64(pStmt, 3, iStartBlock);
128212     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
128213     sqlite3_bind_int64(pStmt, 5, iEndBlock);
128214     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
128215     sqlite3_step(pStmt);
128216     rc = sqlite3_reset(pStmt);
128217   }
128218   return rc;
128219 }
128220 
128221 /*
128222 ** Return the size of the common prefix (if any) shared by zPrev and
128223 ** zNext, in bytes. For example,
128224 **
128225 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
128226 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
128227 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
128228 */
128229 static int fts3PrefixCompress(
128230   const char *zPrev,              /* Buffer containing previous term */
128231   int nPrev,                      /* Size of buffer zPrev in bytes */
128232   const char *zNext,              /* Buffer containing next term */
128233   int nNext                       /* Size of buffer zNext in bytes */
128234 ){
128235   int n;
128236   UNUSED_PARAMETER(nNext);
128237   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
128238   return n;
128239 }
128240 
128241 /*
128242 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
128243 ** (according to memcmp) than the previous term.
128244 */
128245 static int fts3NodeAddTerm(
128246   Fts3Table *p,                   /* Virtual table handle */
128247   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
128248   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
128249   const char *zTerm,              /* Pointer to buffer containing term */
128250   int nTerm                       /* Size of term in bytes */
128251 ){
128252   SegmentNode *pTree = *ppTree;
128253   int rc;
128254   SegmentNode *pNew;
128255 
128256   /* First try to append the term to the current node. Return early if
128257   ** this is possible.
128258   */
128259   if( pTree ){
128260     int nData = pTree->nData;     /* Current size of node in bytes */
128261     int nReq = nData;             /* Required space after adding zTerm */
128262     int nPrefix;                  /* Number of bytes of prefix compression */
128263     int nSuffix;                  /* Suffix length */
128264 
128265     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
128266     nSuffix = nTerm-nPrefix;
128267 
128268     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
128269     if( nReq<=p->nNodeSize || !pTree->zTerm ){
128270 
128271       if( nReq>p->nNodeSize ){
128272         /* An unusual case: this is the first term to be added to the node
128273         ** and the static node buffer (p->nNodeSize bytes) is not large
128274         ** enough. Use a separately malloced buffer instead This wastes
128275         ** p->nNodeSize bytes, but since this scenario only comes about when
128276         ** the database contain two terms that share a prefix of almost 2KB,
128277         ** this is not expected to be a serious problem.
128278         */
128279         assert( pTree->aData==(char *)&pTree[1] );
128280         pTree->aData = (char *)sqlite3_malloc(nReq);
128281         if( !pTree->aData ){
128282           return SQLITE_NOMEM;
128283         }
128284       }
128285 
128286       if( pTree->zTerm ){
128287         /* There is no prefix-length field for first term in a node */
128288         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
128289       }
128290 
128291       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
128292       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
128293       pTree->nData = nData + nSuffix;
128294       pTree->nEntry++;
128295 
128296       if( isCopyTerm ){
128297         if( pTree->nMalloc<nTerm ){
128298           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
128299           if( !zNew ){
128300             return SQLITE_NOMEM;
128301           }
128302           pTree->nMalloc = nTerm*2;
128303           pTree->zMalloc = zNew;
128304         }
128305         pTree->zTerm = pTree->zMalloc;
128306         memcpy(pTree->zTerm, zTerm, nTerm);
128307         pTree->nTerm = nTerm;
128308       }else{
128309         pTree->zTerm = (char *)zTerm;
128310         pTree->nTerm = nTerm;
128311       }
128312       return SQLITE_OK;
128313     }
128314   }
128315 
128316   /* If control flows to here, it was not possible to append zTerm to the
128317   ** current node. Create a new node (a right-sibling of the current node).
128318   ** If this is the first node in the tree, the term is added to it.
128319   **
128320   ** Otherwise, the term is not added to the new node, it is left empty for
128321   ** now. Instead, the term is inserted into the parent of pTree. If pTree
128322   ** has no parent, one is created here.
128323   */
128324   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
128325   if( !pNew ){
128326     return SQLITE_NOMEM;
128327   }
128328   memset(pNew, 0, sizeof(SegmentNode));
128329   pNew->nData = 1 + FTS3_VARINT_MAX;
128330   pNew->aData = (char *)&pNew[1];
128331 
128332   if( pTree ){
128333     SegmentNode *pParent = pTree->pParent;
128334     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
128335     if( pTree->pParent==0 ){
128336       pTree->pParent = pParent;
128337     }
128338     pTree->pRight = pNew;
128339     pNew->pLeftmost = pTree->pLeftmost;
128340     pNew->pParent = pParent;
128341     pNew->zMalloc = pTree->zMalloc;
128342     pNew->nMalloc = pTree->nMalloc;
128343     pTree->zMalloc = 0;
128344   }else{
128345     pNew->pLeftmost = pNew;
128346     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
128347   }
128348 
128349   *ppTree = pNew;
128350   return rc;
128351 }
128352 
128353 /*
128354 ** Helper function for fts3NodeWrite().
128355 */
128356 static int fts3TreeFinishNode(
128357   SegmentNode *pTree,
128358   int iHeight,
128359   sqlite3_int64 iLeftChild
128360 ){
128361   int nStart;
128362   assert( iHeight>=1 && iHeight<128 );
128363   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
128364   pTree->aData[nStart] = (char)iHeight;
128365   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
128366   return nStart;
128367 }
128368 
128369 /*
128370 ** Write the buffer for the segment node pTree and all of its peers to the
128371 ** database. Then call this function recursively to write the parent of
128372 ** pTree and its peers to the database.
128373 **
128374 ** Except, if pTree is a root node, do not write it to the database. Instead,
128375 ** set output variables *paRoot and *pnRoot to contain the root node.
128376 **
128377 ** If successful, SQLITE_OK is returned and output variable *piLast is
128378 ** set to the largest blockid written to the database (or zero if no
128379 ** blocks were written to the db). Otherwise, an SQLite error code is
128380 ** returned.
128381 */
128382 static int fts3NodeWrite(
128383   Fts3Table *p,                   /* Virtual table handle */
128384   SegmentNode *pTree,             /* SegmentNode handle */
128385   int iHeight,                    /* Height of this node in tree */
128386   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
128387   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
128388   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
128389   char **paRoot,                  /* OUT: Data for root node */
128390   int *pnRoot                     /* OUT: Size of root node in bytes */
128391 ){
128392   int rc = SQLITE_OK;
128393 
128394   if( !pTree->pParent ){
128395     /* Root node of the tree. */
128396     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
128397     *piLast = iFree-1;
128398     *pnRoot = pTree->nData - nStart;
128399     *paRoot = &pTree->aData[nStart];
128400   }else{
128401     SegmentNode *pIter;
128402     sqlite3_int64 iNextFree = iFree;
128403     sqlite3_int64 iNextLeaf = iLeaf;
128404     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
128405       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
128406       int nWrite = pIter->nData - nStart;
128407 
128408       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
128409       iNextFree++;
128410       iNextLeaf += (pIter->nEntry+1);
128411     }
128412     if( rc==SQLITE_OK ){
128413       assert( iNextLeaf==iFree );
128414       rc = fts3NodeWrite(
128415           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
128416       );
128417     }
128418   }
128419 
128420   return rc;
128421 }
128422 
128423 /*
128424 ** Free all memory allocations associated with the tree pTree.
128425 */
128426 static void fts3NodeFree(SegmentNode *pTree){
128427   if( pTree ){
128428     SegmentNode *p = pTree->pLeftmost;
128429     fts3NodeFree(p->pParent);
128430     while( p ){
128431       SegmentNode *pRight = p->pRight;
128432       if( p->aData!=(char *)&p[1] ){
128433         sqlite3_free(p->aData);
128434       }
128435       assert( pRight==0 || p->zMalloc==0 );
128436       sqlite3_free(p->zMalloc);
128437       sqlite3_free(p);
128438       p = pRight;
128439     }
128440   }
128441 }
128442 
128443 /*
128444 ** Add a term to the segment being constructed by the SegmentWriter object
128445 ** *ppWriter. When adding the first term to a segment, *ppWriter should
128446 ** be passed NULL. This function will allocate a new SegmentWriter object
128447 ** and return it via the input/output variable *ppWriter in this case.
128448 **
128449 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
128450 */
128451 static int fts3SegWriterAdd(
128452   Fts3Table *p,                   /* Virtual table handle */
128453   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
128454   int isCopyTerm,                 /* True if buffer zTerm must be copied */
128455   const char *zTerm,              /* Pointer to buffer containing term */
128456   int nTerm,                      /* Size of term in bytes */
128457   const char *aDoclist,           /* Pointer to buffer containing doclist */
128458   int nDoclist                    /* Size of doclist in bytes */
128459 ){
128460   int nPrefix;                    /* Size of term prefix in bytes */
128461   int nSuffix;                    /* Size of term suffix in bytes */
128462   int nReq;                       /* Number of bytes required on leaf page */
128463   int nData;
128464   SegmentWriter *pWriter = *ppWriter;
128465 
128466   if( !pWriter ){
128467     int rc;
128468     sqlite3_stmt *pStmt;
128469 
128470     /* Allocate the SegmentWriter structure */
128471     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
128472     if( !pWriter ) return SQLITE_NOMEM;
128473     memset(pWriter, 0, sizeof(SegmentWriter));
128474     *ppWriter = pWriter;
128475 
128476     /* Allocate a buffer in which to accumulate data */
128477     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
128478     if( !pWriter->aData ) return SQLITE_NOMEM;
128479     pWriter->nSize = p->nNodeSize;
128480 
128481     /* Find the next free blockid in the %_segments table */
128482     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
128483     if( rc!=SQLITE_OK ) return rc;
128484     if( SQLITE_ROW==sqlite3_step(pStmt) ){
128485       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
128486       pWriter->iFirst = pWriter->iFree;
128487     }
128488     rc = sqlite3_reset(pStmt);
128489     if( rc!=SQLITE_OK ) return rc;
128490   }
128491   nData = pWriter->nData;
128492 
128493   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
128494   nSuffix = nTerm-nPrefix;
128495 
128496   /* Figure out how many bytes are required by this new entry */
128497   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
128498     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
128499     nSuffix +                               /* Term suffix */
128500     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
128501     nDoclist;                               /* Doclist data */
128502 
128503   if( nData>0 && nData+nReq>p->nNodeSize ){
128504     int rc;
128505 
128506     /* The current leaf node is full. Write it out to the database. */
128507     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
128508     if( rc!=SQLITE_OK ) return rc;
128509     p->nLeafAdd++;
128510 
128511     /* Add the current term to the interior node tree. The term added to
128512     ** the interior tree must:
128513     **
128514     **   a) be greater than the largest term on the leaf node just written
128515     **      to the database (still available in pWriter->zTerm), and
128516     **
128517     **   b) be less than or equal to the term about to be added to the new
128518     **      leaf node (zTerm/nTerm).
128519     **
128520     ** In other words, it must be the prefix of zTerm 1 byte longer than
128521     ** the common prefix (if any) of zTerm and pWriter->zTerm.
128522     */
128523     assert( nPrefix<nTerm );
128524     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
128525     if( rc!=SQLITE_OK ) return rc;
128526 
128527     nData = 0;
128528     pWriter->nTerm = 0;
128529 
128530     nPrefix = 0;
128531     nSuffix = nTerm;
128532     nReq = 1 +                              /* varint containing prefix size */
128533       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
128534       nTerm +                               /* Term suffix */
128535       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
128536       nDoclist;                             /* Doclist data */
128537   }
128538 
128539   /* If the buffer currently allocated is too small for this entry, realloc
128540   ** the buffer to make it large enough.
128541   */
128542   if( nReq>pWriter->nSize ){
128543     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
128544     if( !aNew ) return SQLITE_NOMEM;
128545     pWriter->aData = aNew;
128546     pWriter->nSize = nReq;
128547   }
128548   assert( nData+nReq<=pWriter->nSize );
128549 
128550   /* Append the prefix-compressed term and doclist to the buffer. */
128551   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
128552   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
128553   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
128554   nData += nSuffix;
128555   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
128556   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
128557   pWriter->nData = nData + nDoclist;
128558 
128559   /* Save the current term so that it can be used to prefix-compress the next.
128560   ** If the isCopyTerm parameter is true, then the buffer pointed to by
128561   ** zTerm is transient, so take a copy of the term data. Otherwise, just
128562   ** store a copy of the pointer.
128563   */
128564   if( isCopyTerm ){
128565     if( nTerm>pWriter->nMalloc ){
128566       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
128567       if( !zNew ){
128568         return SQLITE_NOMEM;
128569       }
128570       pWriter->nMalloc = nTerm*2;
128571       pWriter->zMalloc = zNew;
128572       pWriter->zTerm = zNew;
128573     }
128574     assert( pWriter->zTerm==pWriter->zMalloc );
128575     memcpy(pWriter->zTerm, zTerm, nTerm);
128576   }else{
128577     pWriter->zTerm = (char *)zTerm;
128578   }
128579   pWriter->nTerm = nTerm;
128580 
128581   return SQLITE_OK;
128582 }
128583 
128584 /*
128585 ** Flush all data associated with the SegmentWriter object pWriter to the
128586 ** database. This function must be called after all terms have been added
128587 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
128588 ** returned. Otherwise, an SQLite error code.
128589 */
128590 static int fts3SegWriterFlush(
128591   Fts3Table *p,                   /* Virtual table handle */
128592   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
128593   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
128594   int iIdx                        /* Value for 'idx' column of %_segdir */
128595 ){
128596   int rc;                         /* Return code */
128597   if( pWriter->pTree ){
128598     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
128599     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
128600     char *zRoot = NULL;           /* Pointer to buffer containing root node */
128601     int nRoot = 0;                /* Size of buffer zRoot */
128602 
128603     iLastLeaf = pWriter->iFree;
128604     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
128605     if( rc==SQLITE_OK ){
128606       rc = fts3NodeWrite(p, pWriter->pTree, 1,
128607           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
128608     }
128609     if( rc==SQLITE_OK ){
128610       rc = fts3WriteSegdir(
128611           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
128612     }
128613   }else{
128614     /* The entire tree fits on the root node. Write it to the segdir table. */
128615     rc = fts3WriteSegdir(
128616         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
128617   }
128618   p->nLeafAdd++;
128619   return rc;
128620 }
128621 
128622 /*
128623 ** Release all memory held by the SegmentWriter object passed as the
128624 ** first argument.
128625 */
128626 static void fts3SegWriterFree(SegmentWriter *pWriter){
128627   if( pWriter ){
128628     sqlite3_free(pWriter->aData);
128629     sqlite3_free(pWriter->zMalloc);
128630     fts3NodeFree(pWriter->pTree);
128631     sqlite3_free(pWriter);
128632   }
128633 }
128634 
128635 /*
128636 ** The first value in the apVal[] array is assumed to contain an integer.
128637 ** This function tests if there exist any documents with docid values that
128638 ** are different from that integer. i.e. if deleting the document with docid
128639 ** pRowid would mean the FTS3 table were empty.
128640 **
128641 ** If successful, *pisEmpty is set to true if the table is empty except for
128642 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
128643 ** error occurs, an SQLite error code is returned.
128644 */
128645 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
128646   sqlite3_stmt *pStmt;
128647   int rc;
128648   if( p->zContentTbl ){
128649     /* If using the content=xxx option, assume the table is never empty */
128650     *pisEmpty = 0;
128651     rc = SQLITE_OK;
128652   }else{
128653     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
128654     if( rc==SQLITE_OK ){
128655       if( SQLITE_ROW==sqlite3_step(pStmt) ){
128656         *pisEmpty = sqlite3_column_int(pStmt, 0);
128657       }
128658       rc = sqlite3_reset(pStmt);
128659     }
128660   }
128661   return rc;
128662 }
128663 
128664 /*
128665 ** Set *pnMax to the largest segment level in the database for the index
128666 ** iIndex.
128667 **
128668 ** Segment levels are stored in the 'level' column of the %_segdir table.
128669 **
128670 ** Return SQLITE_OK if successful, or an SQLite error code if not.
128671 */
128672 static int fts3SegmentMaxLevel(
128673   Fts3Table *p,
128674   int iLangid,
128675   int iIndex,
128676   sqlite3_int64 *pnMax
128677 ){
128678   sqlite3_stmt *pStmt;
128679   int rc;
128680   assert( iIndex>=0 && iIndex<p->nIndex );
128681 
128682   /* Set pStmt to the compiled version of:
128683   **
128684   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
128685   **
128686   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
128687   */
128688   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
128689   if( rc!=SQLITE_OK ) return rc;
128690   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128691   sqlite3_bind_int64(pStmt, 2,
128692       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128693   );
128694   if( SQLITE_ROW==sqlite3_step(pStmt) ){
128695     *pnMax = sqlite3_column_int64(pStmt, 0);
128696   }
128697   return sqlite3_reset(pStmt);
128698 }
128699 
128700 /*
128701 ** Delete all entries in the %_segments table associated with the segment
128702 ** opened with seg-reader pSeg. This function does not affect the contents
128703 ** of the %_segdir table.
128704 */
128705 static int fts3DeleteSegment(
128706   Fts3Table *p,                   /* FTS table handle */
128707   Fts3SegReader *pSeg             /* Segment to delete */
128708 ){
128709   int rc = SQLITE_OK;             /* Return code */
128710   if( pSeg->iStartBlock ){
128711     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
128712     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
128713     if( rc==SQLITE_OK ){
128714       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
128715       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
128716       sqlite3_step(pDelete);
128717       rc = sqlite3_reset(pDelete);
128718     }
128719   }
128720   return rc;
128721 }
128722 
128723 /*
128724 ** This function is used after merging multiple segments into a single large
128725 ** segment to delete the old, now redundant, segment b-trees. Specifically,
128726 ** it:
128727 **
128728 **   1) Deletes all %_segments entries for the segments associated with
128729 **      each of the SegReader objects in the array passed as the third
128730 **      argument, and
128731 **
128732 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
128733 **      entries regardless of level if (iLevel<0).
128734 **
128735 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
128736 */
128737 static int fts3DeleteSegdir(
128738   Fts3Table *p,                   /* Virtual table handle */
128739   int iLangid,                    /* Language id */
128740   int iIndex,                     /* Index for p->aIndex */
128741   int iLevel,                     /* Level of %_segdir entries to delete */
128742   Fts3SegReader **apSegment,      /* Array of SegReader objects */
128743   int nReader                     /* Size of array apSegment */
128744 ){
128745   int rc = SQLITE_OK;             /* Return Code */
128746   int i;                          /* Iterator variable */
128747   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
128748 
128749   for(i=0; rc==SQLITE_OK && i<nReader; i++){
128750     rc = fts3DeleteSegment(p, apSegment[i]);
128751   }
128752   if( rc!=SQLITE_OK ){
128753     return rc;
128754   }
128755 
128756   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
128757   if( iLevel==FTS3_SEGCURSOR_ALL ){
128758     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
128759     if( rc==SQLITE_OK ){
128760       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
128761       sqlite3_bind_int64(pDelete, 2,
128762           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
128763       );
128764     }
128765   }else{
128766     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
128767     if( rc==SQLITE_OK ){
128768       sqlite3_bind_int64(
128769           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
128770       );
128771     }
128772   }
128773 
128774   if( rc==SQLITE_OK ){
128775     sqlite3_step(pDelete);
128776     rc = sqlite3_reset(pDelete);
128777   }
128778 
128779   return rc;
128780 }
128781 
128782 /*
128783 ** When this function is called, buffer *ppList (size *pnList bytes) contains
128784 ** a position list that may (or may not) feature multiple columns. This
128785 ** function adjusts the pointer *ppList and the length *pnList so that they
128786 ** identify the subset of the position list that corresponds to column iCol.
128787 **
128788 ** If there are no entries in the input position list for column iCol, then
128789 ** *pnList is set to zero before returning.
128790 **
128791 ** If parameter bZero is non-zero, then any part of the input list following
128792 ** the end of the output list is zeroed before returning.
128793 */
128794 static void fts3ColumnFilter(
128795   int iCol,                       /* Column to filter on */
128796   int bZero,                      /* Zero out anything following *ppList */
128797   char **ppList,                  /* IN/OUT: Pointer to position list */
128798   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
128799 ){
128800   char *pList = *ppList;
128801   int nList = *pnList;
128802   char *pEnd = &pList[nList];
128803   int iCurrent = 0;
128804   char *p = pList;
128805 
128806   assert( iCol>=0 );
128807   while( 1 ){
128808     char c = 0;
128809     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
128810 
128811     if( iCol==iCurrent ){
128812       nList = (int)(p - pList);
128813       break;
128814     }
128815 
128816     nList -= (int)(p - pList);
128817     pList = p;
128818     if( nList==0 ){
128819       break;
128820     }
128821     p = &pList[1];
128822     p += sqlite3Fts3GetVarint32(p, &iCurrent);
128823   }
128824 
128825   if( bZero && &pList[nList]!=pEnd ){
128826     memset(&pList[nList], 0, pEnd - &pList[nList]);
128827   }
128828   *ppList = pList;
128829   *pnList = nList;
128830 }
128831 
128832 /*
128833 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
128834 ** existing data). Grow the buffer if required.
128835 **
128836 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
128837 ** trying to resize the buffer, return SQLITE_NOMEM.
128838 */
128839 static int fts3MsrBufferData(
128840   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128841   char *pList,
128842   int nList
128843 ){
128844   if( nList>pMsr->nBuffer ){
128845     char *pNew;
128846     pMsr->nBuffer = nList*2;
128847     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
128848     if( !pNew ) return SQLITE_NOMEM;
128849     pMsr->aBuffer = pNew;
128850   }
128851 
128852   memcpy(pMsr->aBuffer, pList, nList);
128853   return SQLITE_OK;
128854 }
128855 
128856 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
128857   Fts3Table *p,                   /* Virtual table handle */
128858   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
128859   sqlite3_int64 *piDocid,         /* OUT: Docid value */
128860   char **paPoslist,               /* OUT: Pointer to position list */
128861   int *pnPoslist                  /* OUT: Size of position list in bytes */
128862 ){
128863   int nMerge = pMsr->nAdvance;
128864   Fts3SegReader **apSegment = pMsr->apSegment;
128865   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128866     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128867   );
128868 
128869   if( nMerge==0 ){
128870     *paPoslist = 0;
128871     return SQLITE_OK;
128872   }
128873 
128874   while( 1 ){
128875     Fts3SegReader *pSeg;
128876     pSeg = pMsr->apSegment[0];
128877 
128878     if( pSeg->pOffsetList==0 ){
128879       *paPoslist = 0;
128880       break;
128881     }else{
128882       int rc;
128883       char *pList;
128884       int nList;
128885       int j;
128886       sqlite3_int64 iDocid = apSegment[0]->iDocid;
128887 
128888       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
128889       j = 1;
128890       while( rc==SQLITE_OK
128891         && j<nMerge
128892         && apSegment[j]->pOffsetList
128893         && apSegment[j]->iDocid==iDocid
128894       ){
128895         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
128896         j++;
128897       }
128898       if( rc!=SQLITE_OK ) return rc;
128899       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
128900 
128901       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
128902         rc = fts3MsrBufferData(pMsr, pList, nList+1);
128903         if( rc!=SQLITE_OK ) return rc;
128904         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
128905         pList = pMsr->aBuffer;
128906       }
128907 
128908       if( pMsr->iColFilter>=0 ){
128909         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
128910       }
128911 
128912       if( nList>0 ){
128913         *paPoslist = pList;
128914         *piDocid = iDocid;
128915         *pnPoslist = nList;
128916         break;
128917       }
128918     }
128919   }
128920 
128921   return SQLITE_OK;
128922 }
128923 
128924 static int fts3SegReaderStart(
128925   Fts3Table *p,                   /* Virtual table handle */
128926   Fts3MultiSegReader *pCsr,       /* Cursor object */
128927   const char *zTerm,              /* Term searched for (or NULL) */
128928   int nTerm                       /* Length of zTerm in bytes */
128929 ){
128930   int i;
128931   int nSeg = pCsr->nSegment;
128932 
128933   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
128934   ** for, then advance each segment iterator until it points to a term of
128935   ** equal or greater value than the specified term. This prevents many
128936   ** unnecessary merge/sort operations for the case where single segment
128937   ** b-tree leaf nodes contain more than one term.
128938   */
128939   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
128940     int res = 0;
128941     Fts3SegReader *pSeg = pCsr->apSegment[i];
128942     do {
128943       int rc = fts3SegReaderNext(p, pSeg, 0);
128944       if( rc!=SQLITE_OK ) return rc;
128945     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
128946 
128947     if( pSeg->bLookup && res!=0 ){
128948       fts3SegReaderSetEof(pSeg);
128949     }
128950   }
128951   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
128952 
128953   return SQLITE_OK;
128954 }
128955 
128956 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
128957   Fts3Table *p,                   /* Virtual table handle */
128958   Fts3MultiSegReader *pCsr,       /* Cursor object */
128959   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
128960 ){
128961   pCsr->pFilter = pFilter;
128962   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
128963 }
128964 
128965 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
128966   Fts3Table *p,                   /* Virtual table handle */
128967   Fts3MultiSegReader *pCsr,       /* Cursor object */
128968   int iCol,                       /* Column to match on. */
128969   const char *zTerm,              /* Term to iterate through a doclist for */
128970   int nTerm                       /* Number of bytes in zTerm */
128971 ){
128972   int i;
128973   int rc;
128974   int nSegment = pCsr->nSegment;
128975   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
128976     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
128977   );
128978 
128979   assert( pCsr->pFilter==0 );
128980   assert( zTerm && nTerm>0 );
128981 
128982   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
128983   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
128984   if( rc!=SQLITE_OK ) return rc;
128985 
128986   /* Determine how many of the segments actually point to zTerm/nTerm. */
128987   for(i=0; i<nSegment; i++){
128988     Fts3SegReader *pSeg = pCsr->apSegment[i];
128989     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
128990       break;
128991     }
128992   }
128993   pCsr->nAdvance = i;
128994 
128995   /* Advance each of the segments to point to the first docid. */
128996   for(i=0; i<pCsr->nAdvance; i++){
128997     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
128998     if( rc!=SQLITE_OK ) return rc;
128999   }
129000   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
129001 
129002   assert( iCol<0 || iCol<p->nColumn );
129003   pCsr->iColFilter = iCol;
129004 
129005   return SQLITE_OK;
129006 }
129007 
129008 /*
129009 ** This function is called on a MultiSegReader that has been started using
129010 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
129011 ** have been made. Calling this function puts the MultiSegReader in such
129012 ** a state that if the next two calls are:
129013 **
129014 **   sqlite3Fts3SegReaderStart()
129015 **   sqlite3Fts3SegReaderStep()
129016 **
129017 ** then the entire doclist for the term is available in
129018 ** MultiSegReader.aDoclist/nDoclist.
129019 */
129020 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
129021   int i;                          /* Used to iterate through segment-readers */
129022 
129023   assert( pCsr->zTerm==0 );
129024   assert( pCsr->nTerm==0 );
129025   assert( pCsr->aDoclist==0 );
129026   assert( pCsr->nDoclist==0 );
129027 
129028   pCsr->nAdvance = 0;
129029   pCsr->bRestart = 1;
129030   for(i=0; i<pCsr->nSegment; i++){
129031     pCsr->apSegment[i]->pOffsetList = 0;
129032     pCsr->apSegment[i]->nOffsetList = 0;
129033     pCsr->apSegment[i]->iDocid = 0;
129034   }
129035 
129036   return SQLITE_OK;
129037 }
129038 
129039 
129040 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
129041   Fts3Table *p,                   /* Virtual table handle */
129042   Fts3MultiSegReader *pCsr        /* Cursor object */
129043 ){
129044   int rc = SQLITE_OK;
129045 
129046   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
129047   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
129048   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
129049   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
129050   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
129051   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
129052 
129053   Fts3SegReader **apSegment = pCsr->apSegment;
129054   int nSegment = pCsr->nSegment;
129055   Fts3SegFilter *pFilter = pCsr->pFilter;
129056   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129057     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129058   );
129059 
129060   if( pCsr->nSegment==0 ) return SQLITE_OK;
129061 
129062   do {
129063     int nMerge;
129064     int i;
129065 
129066     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
129067     ** forward. Then sort the list in order of current term again.
129068     */
129069     for(i=0; i<pCsr->nAdvance; i++){
129070       Fts3SegReader *pSeg = apSegment[i];
129071       if( pSeg->bLookup ){
129072         fts3SegReaderSetEof(pSeg);
129073       }else{
129074         rc = fts3SegReaderNext(p, pSeg, 0);
129075       }
129076       if( rc!=SQLITE_OK ) return rc;
129077     }
129078     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
129079     pCsr->nAdvance = 0;
129080 
129081     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
129082     assert( rc==SQLITE_OK );
129083     if( apSegment[0]->aNode==0 ) break;
129084 
129085     pCsr->nTerm = apSegment[0]->nTerm;
129086     pCsr->zTerm = apSegment[0]->zTerm;
129087 
129088     /* If this is a prefix-search, and if the term that apSegment[0] points
129089     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
129090     ** required callbacks have been made. In this case exit early.
129091     **
129092     ** Similarly, if this is a search for an exact match, and the first term
129093     ** of segment apSegment[0] is not a match, exit early.
129094     */
129095     if( pFilter->zTerm && !isScan ){
129096       if( pCsr->nTerm<pFilter->nTerm
129097        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
129098        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
129099       ){
129100         break;
129101       }
129102     }
129103 
129104     nMerge = 1;
129105     while( nMerge<nSegment
129106         && apSegment[nMerge]->aNode
129107         && apSegment[nMerge]->nTerm==pCsr->nTerm
129108         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
129109     ){
129110       nMerge++;
129111     }
129112 
129113     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
129114     if( nMerge==1
129115      && !isIgnoreEmpty
129116      && !isFirst
129117      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
129118     ){
129119       pCsr->nDoclist = apSegment[0]->nDoclist;
129120       if( fts3SegReaderIsPending(apSegment[0]) ){
129121         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
129122         pCsr->aDoclist = pCsr->aBuffer;
129123       }else{
129124         pCsr->aDoclist = apSegment[0]->aDoclist;
129125       }
129126       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
129127     }else{
129128       int nDoclist = 0;           /* Size of doclist */
129129       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
129130 
129131       /* The current term of the first nMerge entries in the array
129132       ** of Fts3SegReader objects is the same. The doclists must be merged
129133       ** and a single term returned with the merged doclist.
129134       */
129135       for(i=0; i<nMerge; i++){
129136         fts3SegReaderFirstDocid(p, apSegment[i]);
129137       }
129138       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
129139       while( apSegment[0]->pOffsetList ){
129140         int j;                    /* Number of segments that share a docid */
129141         char *pList;
129142         int nList;
129143         int nByte;
129144         sqlite3_int64 iDocid = apSegment[0]->iDocid;
129145         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
129146         j = 1;
129147         while( j<nMerge
129148             && apSegment[j]->pOffsetList
129149             && apSegment[j]->iDocid==iDocid
129150         ){
129151           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
129152           j++;
129153         }
129154 
129155         if( isColFilter ){
129156           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
129157         }
129158 
129159         if( !isIgnoreEmpty || nList>0 ){
129160 
129161           /* Calculate the 'docid' delta value to write into the merged
129162           ** doclist. */
129163           sqlite3_int64 iDelta;
129164           if( p->bDescIdx && nDoclist>0 ){
129165             iDelta = iPrev - iDocid;
129166           }else{
129167             iDelta = iDocid - iPrev;
129168           }
129169           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
129170           assert( nDoclist>0 || iDelta==iDocid );
129171 
129172           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
129173           if( nDoclist+nByte>pCsr->nBuffer ){
129174             char *aNew;
129175             pCsr->nBuffer = (nDoclist+nByte)*2;
129176             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
129177             if( !aNew ){
129178               return SQLITE_NOMEM;
129179             }
129180             pCsr->aBuffer = aNew;
129181           }
129182 
129183           if( isFirst ){
129184             char *a = &pCsr->aBuffer[nDoclist];
129185             int nWrite;
129186 
129187             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
129188             if( nWrite ){
129189               iPrev = iDocid;
129190               nDoclist += nWrite;
129191             }
129192           }else{
129193             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
129194             iPrev = iDocid;
129195             if( isRequirePos ){
129196               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
129197               nDoclist += nList;
129198               pCsr->aBuffer[nDoclist++] = '\0';
129199             }
129200           }
129201         }
129202 
129203         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
129204       }
129205       if( nDoclist>0 ){
129206         pCsr->aDoclist = pCsr->aBuffer;
129207         pCsr->nDoclist = nDoclist;
129208         rc = SQLITE_ROW;
129209       }
129210     }
129211     pCsr->nAdvance = nMerge;
129212   }while( rc==SQLITE_OK );
129213 
129214   return rc;
129215 }
129216 
129217 
129218 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
129219   Fts3MultiSegReader *pCsr       /* Cursor object */
129220 ){
129221   if( pCsr ){
129222     int i;
129223     for(i=0; i<pCsr->nSegment; i++){
129224       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
129225     }
129226     sqlite3_free(pCsr->apSegment);
129227     sqlite3_free(pCsr->aBuffer);
129228 
129229     pCsr->nSegment = 0;
129230     pCsr->apSegment = 0;
129231     pCsr->aBuffer = 0;
129232   }
129233 }
129234 
129235 /*
129236 ** Merge all level iLevel segments in the database into a single
129237 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
129238 ** single segment with a level equal to the numerically largest level
129239 ** currently present in the database.
129240 **
129241 ** If this function is called with iLevel<0, but there is only one
129242 ** segment in the database, SQLITE_DONE is returned immediately.
129243 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
129244 ** an SQLite error code is returned.
129245 */
129246 static int fts3SegmentMerge(
129247   Fts3Table *p,
129248   int iLangid,                    /* Language id to merge */
129249   int iIndex,                     /* Index in p->aIndex[] to merge */
129250   int iLevel                      /* Level to merge */
129251 ){
129252   int rc;                         /* Return code */
129253   int iIdx = 0;                   /* Index of new segment */
129254   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
129255   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
129256   Fts3SegFilter filter;           /* Segment term filter condition */
129257   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
129258   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
129259 
129260   assert( iLevel==FTS3_SEGCURSOR_ALL
129261        || iLevel==FTS3_SEGCURSOR_PENDING
129262        || iLevel>=0
129263   );
129264   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
129265   assert( iIndex>=0 && iIndex<p->nIndex );
129266 
129267   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
129268   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
129269 
129270   if( iLevel==FTS3_SEGCURSOR_ALL ){
129271     /* This call is to merge all segments in the database to a single
129272     ** segment. The level of the new segment is equal to the numerically
129273     ** greatest segment level currently present in the database for this
129274     ** index. The idx of the new segment is always 0.  */
129275     if( csr.nSegment==1 ){
129276       rc = SQLITE_DONE;
129277       goto finished;
129278     }
129279     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
129280     bIgnoreEmpty = 1;
129281 
129282   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
129283     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
129284     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
129285   }else{
129286     /* This call is to merge all segments at level iLevel. find the next
129287     ** available segment index at level iLevel+1. The call to
129288     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
129289     ** a single iLevel+2 segment if necessary.  */
129290     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
129291     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
129292   }
129293   if( rc!=SQLITE_OK ) goto finished;
129294   assert( csr.nSegment>0 );
129295   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
129296   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
129297 
129298   memset(&filter, 0, sizeof(Fts3SegFilter));
129299   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
129300   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
129301 
129302   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
129303   while( SQLITE_OK==rc ){
129304     rc = sqlite3Fts3SegReaderStep(p, &csr);
129305     if( rc!=SQLITE_ROW ) break;
129306     rc = fts3SegWriterAdd(p, &pWriter, 1,
129307         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
129308   }
129309   if( rc!=SQLITE_OK ) goto finished;
129310   assert( pWriter );
129311 
129312   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
129313     rc = fts3DeleteSegdir(
129314         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
129315     );
129316     if( rc!=SQLITE_OK ) goto finished;
129317   }
129318   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
129319 
129320  finished:
129321   fts3SegWriterFree(pWriter);
129322   sqlite3Fts3SegReaderFinish(&csr);
129323   return rc;
129324 }
129325 
129326 
129327 /*
129328 ** Flush the contents of pendingTerms to level 0 segments.
129329 */
129330 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
129331   int rc = SQLITE_OK;
129332   int i;
129333 
129334   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
129335     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
129336     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
129337   }
129338   sqlite3Fts3PendingTermsClear(p);
129339 
129340   /* Determine the auto-incr-merge setting if unknown.  If enabled,
129341   ** estimate the number of leaf blocks of content to be written
129342   */
129343   if( rc==SQLITE_OK && p->bHasStat
129344    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
129345   ){
129346     sqlite3_stmt *pStmt = 0;
129347     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
129348     if( rc==SQLITE_OK ){
129349       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
129350       rc = sqlite3_step(pStmt);
129351       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
129352       rc = sqlite3_reset(pStmt);
129353     }
129354   }
129355   return rc;
129356 }
129357 
129358 /*
129359 ** Encode N integers as varints into a blob.
129360 */
129361 static void fts3EncodeIntArray(
129362   int N,             /* The number of integers to encode */
129363   u32 *a,            /* The integer values */
129364   char *zBuf,        /* Write the BLOB here */
129365   int *pNBuf         /* Write number of bytes if zBuf[] used here */
129366 ){
129367   int i, j;
129368   for(i=j=0; i<N; i++){
129369     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
129370   }
129371   *pNBuf = j;
129372 }
129373 
129374 /*
129375 ** Decode a blob of varints into N integers
129376 */
129377 static void fts3DecodeIntArray(
129378   int N,             /* The number of integers to decode */
129379   u32 *a,            /* Write the integer values */
129380   const char *zBuf,  /* The BLOB containing the varints */
129381   int nBuf           /* size of the BLOB */
129382 ){
129383   int i, j;
129384   UNUSED_PARAMETER(nBuf);
129385   for(i=j=0; i<N; i++){
129386     sqlite3_int64 x;
129387     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
129388     assert(j<=nBuf);
129389     a[i] = (u32)(x & 0xffffffff);
129390   }
129391 }
129392 
129393 /*
129394 ** Insert the sizes (in tokens) for each column of the document
129395 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
129396 ** a blob of varints.
129397 */
129398 static void fts3InsertDocsize(
129399   int *pRC,                       /* Result code */
129400   Fts3Table *p,                   /* Table into which to insert */
129401   u32 *aSz                        /* Sizes of each column, in tokens */
129402 ){
129403   char *pBlob;             /* The BLOB encoding of the document size */
129404   int nBlob;               /* Number of bytes in the BLOB */
129405   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
129406   int rc;                  /* Result code from subfunctions */
129407 
129408   if( *pRC ) return;
129409   pBlob = sqlite3_malloc( 10*p->nColumn );
129410   if( pBlob==0 ){
129411     *pRC = SQLITE_NOMEM;
129412     return;
129413   }
129414   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
129415   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
129416   if( rc ){
129417     sqlite3_free(pBlob);
129418     *pRC = rc;
129419     return;
129420   }
129421   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
129422   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
129423   sqlite3_step(pStmt);
129424   *pRC = sqlite3_reset(pStmt);
129425 }
129426 
129427 /*
129428 ** Record 0 of the %_stat table contains a blob consisting of N varints,
129429 ** where N is the number of user defined columns in the fts3 table plus
129430 ** two. If nCol is the number of user defined columns, then values of the
129431 ** varints are set as follows:
129432 **
129433 **   Varint 0:       Total number of rows in the table.
129434 **
129435 **   Varint 1..nCol: For each column, the total number of tokens stored in
129436 **                   the column for all rows of the table.
129437 **
129438 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
129439 **                   columns of all rows of the table.
129440 **
129441 */
129442 static void fts3UpdateDocTotals(
129443   int *pRC,                       /* The result code */
129444   Fts3Table *p,                   /* Table being updated */
129445   u32 *aSzIns,                    /* Size increases */
129446   u32 *aSzDel,                    /* Size decreases */
129447   int nChng                       /* Change in the number of documents */
129448 ){
129449   char *pBlob;             /* Storage for BLOB written into %_stat */
129450   int nBlob;               /* Size of BLOB written into %_stat */
129451   u32 *a;                  /* Array of integers that becomes the BLOB */
129452   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
129453   int i;                   /* Loop counter */
129454   int rc;                  /* Result code from subfunctions */
129455 
129456   const int nStat = p->nColumn+2;
129457 
129458   if( *pRC ) return;
129459   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
129460   if( a==0 ){
129461     *pRC = SQLITE_NOMEM;
129462     return;
129463   }
129464   pBlob = (char*)&a[nStat];
129465   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
129466   if( rc ){
129467     sqlite3_free(a);
129468     *pRC = rc;
129469     return;
129470   }
129471   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129472   if( sqlite3_step(pStmt)==SQLITE_ROW ){
129473     fts3DecodeIntArray(nStat, a,
129474          sqlite3_column_blob(pStmt, 0),
129475          sqlite3_column_bytes(pStmt, 0));
129476   }else{
129477     memset(a, 0, sizeof(u32)*(nStat) );
129478   }
129479   rc = sqlite3_reset(pStmt);
129480   if( rc!=SQLITE_OK ){
129481     sqlite3_free(a);
129482     *pRC = rc;
129483     return;
129484   }
129485   if( nChng<0 && a[0]<(u32)(-nChng) ){
129486     a[0] = 0;
129487   }else{
129488     a[0] += nChng;
129489   }
129490   for(i=0; i<p->nColumn+1; i++){
129491     u32 x = a[i+1];
129492     if( x+aSzIns[i] < aSzDel[i] ){
129493       x = 0;
129494     }else{
129495       x = x + aSzIns[i] - aSzDel[i];
129496     }
129497     a[i+1] = x;
129498   }
129499   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
129500   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
129501   if( rc ){
129502     sqlite3_free(a);
129503     *pRC = rc;
129504     return;
129505   }
129506   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129507   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
129508   sqlite3_step(pStmt);
129509   *pRC = sqlite3_reset(pStmt);
129510   sqlite3_free(a);
129511 }
129512 
129513 /*
129514 ** Merge the entire database so that there is one segment for each
129515 ** iIndex/iLangid combination.
129516 */
129517 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
129518   int bSeenDone = 0;
129519   int rc;
129520   sqlite3_stmt *pAllLangid = 0;
129521 
129522   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
129523   if( rc==SQLITE_OK ){
129524     int rc2;
129525     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
129526     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
129527       int i;
129528       int iLangid = sqlite3_column_int(pAllLangid, 0);
129529       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
129530         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
129531         if( rc==SQLITE_DONE ){
129532           bSeenDone = 1;
129533           rc = SQLITE_OK;
129534         }
129535       }
129536     }
129537     rc2 = sqlite3_reset(pAllLangid);
129538     if( rc==SQLITE_OK ) rc = rc2;
129539   }
129540 
129541   sqlite3Fts3SegmentsClose(p);
129542   sqlite3Fts3PendingTermsClear(p);
129543 
129544   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
129545 }
129546 
129547 /*
129548 ** This function is called when the user executes the following statement:
129549 **
129550 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
129551 **
129552 ** The entire FTS index is discarded and rebuilt. If the table is one
129553 ** created using the content=xxx option, then the new index is based on
129554 ** the current contents of the xxx table. Otherwise, it is rebuilt based
129555 ** on the contents of the %_content table.
129556 */
129557 static int fts3DoRebuild(Fts3Table *p){
129558   int rc;                         /* Return Code */
129559 
129560   rc = fts3DeleteAll(p, 0);
129561   if( rc==SQLITE_OK ){
129562     u32 *aSz = 0;
129563     u32 *aSzIns = 0;
129564     u32 *aSzDel = 0;
129565     sqlite3_stmt *pStmt = 0;
129566     int nEntry = 0;
129567 
129568     /* Compose and prepare an SQL statement to loop through the content table */
129569     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
129570     if( !zSql ){
129571       rc = SQLITE_NOMEM;
129572     }else{
129573       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
129574       sqlite3_free(zSql);
129575     }
129576 
129577     if( rc==SQLITE_OK ){
129578       int nByte = sizeof(u32) * (p->nColumn+1)*3;
129579       aSz = (u32 *)sqlite3_malloc(nByte);
129580       if( aSz==0 ){
129581         rc = SQLITE_NOMEM;
129582       }else{
129583         memset(aSz, 0, nByte);
129584         aSzIns = &aSz[p->nColumn+1];
129585         aSzDel = &aSzIns[p->nColumn+1];
129586       }
129587     }
129588 
129589     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
129590       int iCol;
129591       int iLangid = langidFromSelect(p, pStmt);
129592       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
129593       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
129594       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
129595         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
129596         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
129597         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
129598       }
129599       if( p->bHasDocsize ){
129600         fts3InsertDocsize(&rc, p, aSz);
129601       }
129602       if( rc!=SQLITE_OK ){
129603         sqlite3_finalize(pStmt);
129604         pStmt = 0;
129605       }else{
129606         nEntry++;
129607         for(iCol=0; iCol<=p->nColumn; iCol++){
129608           aSzIns[iCol] += aSz[iCol];
129609         }
129610       }
129611     }
129612     if( p->bFts4 ){
129613       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
129614     }
129615     sqlite3_free(aSz);
129616 
129617     if( pStmt ){
129618       int rc2 = sqlite3_finalize(pStmt);
129619       if( rc==SQLITE_OK ){
129620         rc = rc2;
129621       }
129622     }
129623   }
129624 
129625   return rc;
129626 }
129627 
129628 
129629 /*
129630 ** This function opens a cursor used to read the input data for an
129631 ** incremental merge operation. Specifically, it opens a cursor to scan
129632 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
129633 ** level iAbsLevel.
129634 */
129635 static int fts3IncrmergeCsr(
129636   Fts3Table *p,                   /* FTS3 table handle */
129637   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
129638   int nSeg,                       /* Number of segments to merge */
129639   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
129640 ){
129641   int rc;                         /* Return Code */
129642   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
129643   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
129644 
129645   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
129646   memset(pCsr, 0, sizeof(*pCsr));
129647   nByte = sizeof(Fts3SegReader *) * nSeg;
129648   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
129649 
129650   if( pCsr->apSegment==0 ){
129651     rc = SQLITE_NOMEM;
129652   }else{
129653     memset(pCsr->apSegment, 0, nByte);
129654     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
129655   }
129656   if( rc==SQLITE_OK ){
129657     int i;
129658     int rc2;
129659     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
129660     assert( pCsr->nSegment==0 );
129661     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
129662       rc = sqlite3Fts3SegReaderNew(i, 0,
129663           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
129664           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
129665           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
129666           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
129667           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
129668           &pCsr->apSegment[i]
129669       );
129670       pCsr->nSegment++;
129671     }
129672     rc2 = sqlite3_reset(pStmt);
129673     if( rc==SQLITE_OK ) rc = rc2;
129674   }
129675 
129676   return rc;
129677 }
129678 
129679 typedef struct IncrmergeWriter IncrmergeWriter;
129680 typedef struct NodeWriter NodeWriter;
129681 typedef struct Blob Blob;
129682 typedef struct NodeReader NodeReader;
129683 
129684 /*
129685 ** An instance of the following structure is used as a dynamic buffer
129686 ** to build up nodes or other blobs of data in.
129687 **
129688 ** The function blobGrowBuffer() is used to extend the allocation.
129689 */
129690 struct Blob {
129691   char *a;                        /* Pointer to allocation */
129692   int n;                          /* Number of valid bytes of data in a[] */
129693   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
129694 };
129695 
129696 /*
129697 ** This structure is used to build up buffers containing segment b-tree
129698 ** nodes (blocks).
129699 */
129700 struct NodeWriter {
129701   sqlite3_int64 iBlock;           /* Current block id */
129702   Blob key;                       /* Last key written to the current block */
129703   Blob block;                     /* Current block image */
129704 };
129705 
129706 /*
129707 ** An object of this type contains the state required to create or append
129708 ** to an appendable b-tree segment.
129709 */
129710 struct IncrmergeWriter {
129711   int nLeafEst;                   /* Space allocated for leaf blocks */
129712   int nWork;                      /* Number of leaf pages flushed */
129713   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
129714   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
129715   sqlite3_int64 iStart;           /* Block number of first allocated block */
129716   sqlite3_int64 iEnd;             /* Block number of last allocated block */
129717   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
129718 };
129719 
129720 /*
129721 ** An object of the following type is used to read data from a single
129722 ** FTS segment node. See the following functions:
129723 **
129724 **     nodeReaderInit()
129725 **     nodeReaderNext()
129726 **     nodeReaderRelease()
129727 */
129728 struct NodeReader {
129729   const char *aNode;
129730   int nNode;
129731   int iOff;                       /* Current offset within aNode[] */
129732 
129733   /* Output variables. Containing the current node entry. */
129734   sqlite3_int64 iChild;           /* Pointer to child node */
129735   Blob term;                      /* Current term */
129736   const char *aDoclist;           /* Pointer to doclist */
129737   int nDoclist;                   /* Size of doclist in bytes */
129738 };
129739 
129740 /*
129741 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
129742 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
129743 ** bytes in size, extend (realloc) it to be so.
129744 **
129745 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
129746 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
129747 ** to reflect the new size of the pBlob->a[] buffer.
129748 */
129749 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
129750   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
129751     int nAlloc = nMin;
129752     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
129753     if( a ){
129754       pBlob->nAlloc = nAlloc;
129755       pBlob->a = a;
129756     }else{
129757       *pRc = SQLITE_NOMEM;
129758     }
129759   }
129760 }
129761 
129762 /*
129763 ** Attempt to advance the node-reader object passed as the first argument to
129764 ** the next entry on the node.
129765 **
129766 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
129767 ** Otherwise return SQLITE_OK. If there is no next entry on the node
129768 ** (e.g. because the current entry is the last) set NodeReader->aNode to
129769 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
129770 ** variables for the new entry.
129771 */
129772 static int nodeReaderNext(NodeReader *p){
129773   int bFirst = (p->term.n==0);    /* True for first term on the node */
129774   int nPrefix = 0;                /* Bytes to copy from previous term */
129775   int nSuffix = 0;                /* Bytes to append to the prefix */
129776   int rc = SQLITE_OK;             /* Return code */
129777 
129778   assert( p->aNode );
129779   if( p->iChild && bFirst==0 ) p->iChild++;
129780   if( p->iOff>=p->nNode ){
129781     /* EOF */
129782     p->aNode = 0;
129783   }else{
129784     if( bFirst==0 ){
129785       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
129786     }
129787     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
129788 
129789     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
129790     if( rc==SQLITE_OK ){
129791       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
129792       p->term.n = nPrefix+nSuffix;
129793       p->iOff += nSuffix;
129794       if( p->iChild==0 ){
129795         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
129796         p->aDoclist = &p->aNode[p->iOff];
129797         p->iOff += p->nDoclist;
129798       }
129799     }
129800   }
129801 
129802   assert( p->iOff<=p->nNode );
129803 
129804   return rc;
129805 }
129806 
129807 /*
129808 ** Release all dynamic resources held by node-reader object *p.
129809 */
129810 static void nodeReaderRelease(NodeReader *p){
129811   sqlite3_free(p->term.a);
129812 }
129813 
129814 /*
129815 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
129816 **
129817 ** If successful, SQLITE_OK is returned and the NodeReader object set to
129818 ** point to the first entry on the node (if any). Otherwise, an SQLite
129819 ** error code is returned.
129820 */
129821 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
129822   memset(p, 0, sizeof(NodeReader));
129823   p->aNode = aNode;
129824   p->nNode = nNode;
129825 
129826   /* Figure out if this is a leaf or an internal node. */
129827   if( p->aNode[0] ){
129828     /* An internal node. */
129829     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
129830   }else{
129831     p->iOff = 1;
129832   }
129833 
129834   return nodeReaderNext(p);
129835 }
129836 
129837 /*
129838 ** This function is called while writing an FTS segment each time a leaf o
129839 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
129840 ** to be greater than the largest key on the node just written, but smaller
129841 ** than or equal to the first key that will be written to the next leaf
129842 ** node.
129843 **
129844 ** The block id of the leaf node just written to disk may be found in
129845 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
129846 */
129847 static int fts3IncrmergePush(
129848   Fts3Table *p,                   /* Fts3 table handle */
129849   IncrmergeWriter *pWriter,       /* Writer object */
129850   const char *zTerm,              /* Term to write to internal node */
129851   int nTerm                       /* Bytes at zTerm */
129852 ){
129853   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
129854   int iLayer;
129855 
129856   assert( nTerm>0 );
129857   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
129858     sqlite3_int64 iNextPtr = 0;
129859     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
129860     int rc = SQLITE_OK;
129861     int nPrefix;
129862     int nSuffix;
129863     int nSpace;
129864 
129865     /* Figure out how much space the key will consume if it is written to
129866     ** the current node of layer iLayer. Due to the prefix compression,
129867     ** the space required changes depending on which node the key is to
129868     ** be added to.  */
129869     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
129870     nSuffix = nTerm - nPrefix;
129871     nSpace  = sqlite3Fts3VarintLen(nPrefix);
129872     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
129873 
129874     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
129875       /* If the current node of layer iLayer contains zero keys, or if adding
129876       ** the key to it will not cause it to grow to larger than nNodeSize
129877       ** bytes in size, write the key here.  */
129878 
129879       Blob *pBlk = &pNode->block;
129880       if( pBlk->n==0 ){
129881         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
129882         if( rc==SQLITE_OK ){
129883           pBlk->a[0] = (char)iLayer;
129884           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
129885         }
129886       }
129887       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
129888       blobGrowBuffer(&pNode->key, nTerm, &rc);
129889 
129890       if( rc==SQLITE_OK ){
129891         if( pNode->key.n ){
129892           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
129893         }
129894         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
129895         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
129896         pBlk->n += nSuffix;
129897 
129898         memcpy(pNode->key.a, zTerm, nTerm);
129899         pNode->key.n = nTerm;
129900       }
129901     }else{
129902       /* Otherwise, flush the current node of layer iLayer to disk.
129903       ** Then allocate a new, empty sibling node. The key will be written
129904       ** into the parent of this node. */
129905       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
129906 
129907       assert( pNode->block.nAlloc>=p->nNodeSize );
129908       pNode->block.a[0] = (char)iLayer;
129909       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
129910 
129911       iNextPtr = pNode->iBlock;
129912       pNode->iBlock++;
129913       pNode->key.n = 0;
129914     }
129915 
129916     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
129917     iPtr = iNextPtr;
129918   }
129919 
129920   assert( 0 );
129921   return 0;
129922 }
129923 
129924 /*
129925 ** Append a term and (optionally) doclist to the FTS segment node currently
129926 ** stored in blob *pNode. The node need not contain any terms, but the
129927 ** header must be written before this function is called.
129928 **
129929 ** A node header is a single 0x00 byte for a leaf node, or a height varint
129930 ** followed by the left-hand-child varint for an internal node.
129931 **
129932 ** The term to be appended is passed via arguments zTerm/nTerm. For a
129933 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
129934 ** node, both aDoclist and nDoclist must be passed 0.
129935 **
129936 ** If the size of the value in blob pPrev is zero, then this is the first
129937 ** term written to the node. Otherwise, pPrev contains a copy of the
129938 ** previous term. Before this function returns, it is updated to contain a
129939 ** copy of zTerm/nTerm.
129940 **
129941 ** It is assumed that the buffer associated with pNode is already large
129942 ** enough to accommodate the new entry. The buffer associated with pPrev
129943 ** is extended by this function if requrired.
129944 **
129945 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
129946 ** returned. Otherwise, SQLITE_OK.
129947 */
129948 static int fts3AppendToNode(
129949   Blob *pNode,                    /* Current node image to append to */
129950   Blob *pPrev,                    /* Buffer containing previous term written */
129951   const char *zTerm,              /* New term to write */
129952   int nTerm,                      /* Size of zTerm in bytes */
129953   const char *aDoclist,           /* Doclist (or NULL) to write */
129954   int nDoclist                    /* Size of aDoclist in bytes */
129955 ){
129956   int rc = SQLITE_OK;             /* Return code */
129957   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
129958   int nPrefix;                    /* Size of term prefix in bytes */
129959   int nSuffix;                    /* Size of term suffix in bytes */
129960 
129961   /* Node must have already been started. There must be a doclist for a
129962   ** leaf node, and there must not be a doclist for an internal node.  */
129963   assert( pNode->n>0 );
129964   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
129965 
129966   blobGrowBuffer(pPrev, nTerm, &rc);
129967   if( rc!=SQLITE_OK ) return rc;
129968 
129969   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
129970   nSuffix = nTerm - nPrefix;
129971   memcpy(pPrev->a, zTerm, nTerm);
129972   pPrev->n = nTerm;
129973 
129974   if( bFirst==0 ){
129975     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
129976   }
129977   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
129978   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
129979   pNode->n += nSuffix;
129980 
129981   if( aDoclist ){
129982     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
129983     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
129984     pNode->n += nDoclist;
129985   }
129986 
129987   assert( pNode->n<=pNode->nAlloc );
129988 
129989   return SQLITE_OK;
129990 }
129991 
129992 /*
129993 ** Append the current term and doclist pointed to by cursor pCsr to the
129994 ** appendable b-tree segment opened for writing by pWriter.
129995 **
129996 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
129997 */
129998 static int fts3IncrmergeAppend(
129999   Fts3Table *p,                   /* Fts3 table handle */
130000   IncrmergeWriter *pWriter,       /* Writer object */
130001   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
130002 ){
130003   const char *zTerm = pCsr->zTerm;
130004   int nTerm = pCsr->nTerm;
130005   const char *aDoclist = pCsr->aDoclist;
130006   int nDoclist = pCsr->nDoclist;
130007   int rc = SQLITE_OK;           /* Return code */
130008   int nSpace;                   /* Total space in bytes required on leaf */
130009   int nPrefix;                  /* Size of prefix shared with previous term */
130010   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
130011   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
130012 
130013   pLeaf = &pWriter->aNodeWriter[0];
130014   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
130015   nSuffix = nTerm - nPrefix;
130016 
130017   nSpace  = sqlite3Fts3VarintLen(nPrefix);
130018   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130019   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
130020 
130021   /* If the current block is not empty, and if adding this term/doclist
130022   ** to the current block would make it larger than Fts3Table.nNodeSize
130023   ** bytes, write this block out to the database. */
130024   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
130025     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
130026     pWriter->nWork++;
130027 
130028     /* Add the current term to the parent node. The term added to the
130029     ** parent must:
130030     **
130031     **   a) be greater than the largest term on the leaf node just written
130032     **      to the database (still available in pLeaf->key), and
130033     **
130034     **   b) be less than or equal to the term about to be added to the new
130035     **      leaf node (zTerm/nTerm).
130036     **
130037     ** In other words, it must be the prefix of zTerm 1 byte longer than
130038     ** the common prefix (if any) of zTerm and pWriter->zTerm.
130039     */
130040     if( rc==SQLITE_OK ){
130041       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
130042     }
130043 
130044     /* Advance to the next output block */
130045     pLeaf->iBlock++;
130046     pLeaf->key.n = 0;
130047     pLeaf->block.n = 0;
130048 
130049     nSuffix = nTerm;
130050     nSpace  = 1;
130051     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130052     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
130053   }
130054 
130055   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
130056 
130057   if( rc==SQLITE_OK ){
130058     if( pLeaf->block.n==0 ){
130059       pLeaf->block.n = 1;
130060       pLeaf->block.a[0] = '\0';
130061     }
130062     rc = fts3AppendToNode(
130063         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
130064     );
130065   }
130066 
130067   return rc;
130068 }
130069 
130070 /*
130071 ** This function is called to release all dynamic resources held by the
130072 ** merge-writer object pWriter, and if no error has occurred, to flush
130073 ** all outstanding node buffers held by pWriter to disk.
130074 **
130075 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
130076 ** is made to write any data to disk. Instead, this function serves only
130077 ** to release outstanding resources.
130078 **
130079 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
130080 ** flushing buffers to disk, *pRc is set to an SQLite error code before
130081 ** returning.
130082 */
130083 static void fts3IncrmergeRelease(
130084   Fts3Table *p,                   /* FTS3 table handle */
130085   IncrmergeWriter *pWriter,       /* Merge-writer object */
130086   int *pRc                        /* IN/OUT: Error code */
130087 ){
130088   int i;                          /* Used to iterate through non-root layers */
130089   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
130090   NodeWriter *pRoot;              /* NodeWriter for root node */
130091   int rc = *pRc;                  /* Error code */
130092 
130093   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
130094   ** root node. If the segment fits entirely on a single leaf node, iRoot
130095   ** will be set to 0. If the root node is the parent of the leaves, iRoot
130096   ** will be 1. And so on.  */
130097   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
130098     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
130099     if( pNode->block.n>0 ) break;
130100     assert( *pRc || pNode->block.nAlloc==0 );
130101     assert( *pRc || pNode->key.nAlloc==0 );
130102     sqlite3_free(pNode->block.a);
130103     sqlite3_free(pNode->key.a);
130104   }
130105 
130106   /* Empty output segment. This is a no-op. */
130107   if( iRoot<0 ) return;
130108 
130109   /* The entire output segment fits on a single node. Normally, this means
130110   ** the node would be stored as a blob in the "root" column of the %_segdir
130111   ** table. However, this is not permitted in this case. The problem is that
130112   ** space has already been reserved in the %_segments table, and so the
130113   ** start_block and end_block fields of the %_segdir table must be populated.
130114   ** And, by design or by accident, released versions of FTS cannot handle
130115   ** segments that fit entirely on the root node with start_block!=0.
130116   **
130117   ** Instead, create a synthetic root node that contains nothing but a
130118   ** pointer to the single content node. So that the segment consists of a
130119   ** single leaf and a single interior (root) node.
130120   **
130121   ** Todo: Better might be to defer allocating space in the %_segments
130122   ** table until we are sure it is needed.
130123   */
130124   if( iRoot==0 ){
130125     Blob *pBlock = &pWriter->aNodeWriter[1].block;
130126     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
130127     if( rc==SQLITE_OK ){
130128       pBlock->a[0] = 0x01;
130129       pBlock->n = 1 + sqlite3Fts3PutVarint(
130130           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
130131       );
130132     }
130133     iRoot = 1;
130134   }
130135   pRoot = &pWriter->aNodeWriter[iRoot];
130136 
130137   /* Flush all currently outstanding nodes to disk. */
130138   for(i=0; i<iRoot; i++){
130139     NodeWriter *pNode = &pWriter->aNodeWriter[i];
130140     if( pNode->block.n>0 && rc==SQLITE_OK ){
130141       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
130142     }
130143     sqlite3_free(pNode->block.a);
130144     sqlite3_free(pNode->key.a);
130145   }
130146 
130147   /* Write the %_segdir record. */
130148   if( rc==SQLITE_OK ){
130149     rc = fts3WriteSegdir(p,
130150         pWriter->iAbsLevel+1,               /* level */
130151         pWriter->iIdx,                      /* idx */
130152         pWriter->iStart,                    /* start_block */
130153         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
130154         pWriter->iEnd,                      /* end_block */
130155         pRoot->block.a, pRoot->block.n      /* root */
130156     );
130157   }
130158   sqlite3_free(pRoot->block.a);
130159   sqlite3_free(pRoot->key.a);
130160 
130161   *pRc = rc;
130162 }
130163 
130164 /*
130165 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
130166 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
130167 ** the other, it is considered to be smaller than the other.
130168 **
130169 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
130170 ** if it is greater.
130171 */
130172 static int fts3TermCmp(
130173   const char *zLhs, int nLhs,     /* LHS of comparison */
130174   const char *zRhs, int nRhs      /* RHS of comparison */
130175 ){
130176   int nCmp = MIN(nLhs, nRhs);
130177   int res;
130178 
130179   res = memcmp(zLhs, zRhs, nCmp);
130180   if( res==0 ) res = nLhs - nRhs;
130181 
130182   return res;
130183 }
130184 
130185 
130186 /*
130187 ** Query to see if the entry in the %_segments table with blockid iEnd is
130188 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
130189 ** returning. Otherwise, set *pbRes to 0.
130190 **
130191 ** Or, if an error occurs while querying the database, return an SQLite
130192 ** error code. The final value of *pbRes is undefined in this case.
130193 **
130194 ** This is used to test if a segment is an "appendable" segment. If it
130195 ** is, then a NULL entry has been inserted into the %_segments table
130196 ** with blockid %_segdir.end_block.
130197 */
130198 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
130199   int bRes = 0;                   /* Result to set *pbRes to */
130200   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
130201   int rc;                         /* Return code */
130202 
130203   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
130204   if( rc==SQLITE_OK ){
130205     sqlite3_bind_int64(pCheck, 1, iEnd);
130206     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
130207     rc = sqlite3_reset(pCheck);
130208   }
130209 
130210   *pbRes = bRes;
130211   return rc;
130212 }
130213 
130214 /*
130215 ** This function is called when initializing an incremental-merge operation.
130216 ** It checks if the existing segment with index value iIdx at absolute level
130217 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
130218 ** merge-writer object *pWriter is initialized to write to it.
130219 **
130220 ** An existing segment can be appended to by an incremental merge if:
130221 **
130222 **   * It was initially created as an appendable segment (with all required
130223 **     space pre-allocated), and
130224 **
130225 **   * The first key read from the input (arguments zKey and nKey) is
130226 **     greater than the largest key currently stored in the potential
130227 **     output segment.
130228 */
130229 static int fts3IncrmergeLoad(
130230   Fts3Table *p,                   /* Fts3 table handle */
130231   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
130232   int iIdx,                       /* Index of candidate output segment */
130233   const char *zKey,               /* First key to write */
130234   int nKey,                       /* Number of bytes in nKey */
130235   IncrmergeWriter *pWriter        /* Populate this object */
130236 ){
130237   int rc;                         /* Return code */
130238   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
130239 
130240   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
130241   if( rc==SQLITE_OK ){
130242     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
130243     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
130244     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
130245     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
130246     int nRoot = 0;                /* Size of aRoot[] in bytes */
130247     int rc2;                      /* Return code from sqlite3_reset() */
130248     int bAppendable = 0;          /* Set to true if segment is appendable */
130249 
130250     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
130251     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
130252     sqlite3_bind_int(pSelect, 2, iIdx);
130253     if( sqlite3_step(pSelect)==SQLITE_ROW ){
130254       iStart = sqlite3_column_int64(pSelect, 1);
130255       iLeafEnd = sqlite3_column_int64(pSelect, 2);
130256       iEnd = sqlite3_column_int64(pSelect, 3);
130257       nRoot = sqlite3_column_bytes(pSelect, 4);
130258       aRoot = sqlite3_column_blob(pSelect, 4);
130259     }else{
130260       return sqlite3_reset(pSelect);
130261     }
130262 
130263     /* Check for the zero-length marker in the %_segments table */
130264     rc = fts3IsAppendable(p, iEnd, &bAppendable);
130265 
130266     /* Check that zKey/nKey is larger than the largest key the candidate */
130267     if( rc==SQLITE_OK && bAppendable ){
130268       char *aLeaf = 0;
130269       int nLeaf = 0;
130270 
130271       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
130272       if( rc==SQLITE_OK ){
130273         NodeReader reader;
130274         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
130275             rc==SQLITE_OK && reader.aNode;
130276             rc = nodeReaderNext(&reader)
130277         ){
130278           assert( reader.aNode );
130279         }
130280         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
130281           bAppendable = 0;
130282         }
130283         nodeReaderRelease(&reader);
130284       }
130285       sqlite3_free(aLeaf);
130286     }
130287 
130288     if( rc==SQLITE_OK && bAppendable ){
130289       /* It is possible to append to this segment. Set up the IncrmergeWriter
130290       ** object to do so.  */
130291       int i;
130292       int nHeight = (int)aRoot[0];
130293       NodeWriter *pNode;
130294 
130295       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
130296       pWriter->iStart = iStart;
130297       pWriter->iEnd = iEnd;
130298       pWriter->iAbsLevel = iAbsLevel;
130299       pWriter->iIdx = iIdx;
130300 
130301       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
130302         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
130303       }
130304 
130305       pNode = &pWriter->aNodeWriter[nHeight];
130306       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
130307       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
130308       if( rc==SQLITE_OK ){
130309         memcpy(pNode->block.a, aRoot, nRoot);
130310         pNode->block.n = nRoot;
130311       }
130312 
130313       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
130314         NodeReader reader;
130315         pNode = &pWriter->aNodeWriter[i];
130316 
130317         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
130318         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
130319         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
130320         if( rc==SQLITE_OK ){
130321           memcpy(pNode->key.a, reader.term.a, reader.term.n);
130322           pNode->key.n = reader.term.n;
130323           if( i>0 ){
130324             char *aBlock = 0;
130325             int nBlock = 0;
130326             pNode = &pWriter->aNodeWriter[i-1];
130327             pNode->iBlock = reader.iChild;
130328             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
130329             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
130330             if( rc==SQLITE_OK ){
130331               memcpy(pNode->block.a, aBlock, nBlock);
130332               pNode->block.n = nBlock;
130333             }
130334             sqlite3_free(aBlock);
130335           }
130336         }
130337         nodeReaderRelease(&reader);
130338       }
130339     }
130340 
130341     rc2 = sqlite3_reset(pSelect);
130342     if( rc==SQLITE_OK ) rc = rc2;
130343   }
130344 
130345   return rc;
130346 }
130347 
130348 /*
130349 ** Determine the largest segment index value that exists within absolute
130350 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
130351 ** one before returning SQLITE_OK. Or, if there are no segments at all
130352 ** within level iAbsLevel, set *piIdx to zero.
130353 **
130354 ** If an error occurs, return an SQLite error code. The final value of
130355 ** *piIdx is undefined in this case.
130356 */
130357 static int fts3IncrmergeOutputIdx(
130358   Fts3Table *p,                   /* FTS Table handle */
130359   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
130360   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
130361 ){
130362   int rc;
130363   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
130364 
130365   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
130366   if( rc==SQLITE_OK ){
130367     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
130368     sqlite3_step(pOutputIdx);
130369     *piIdx = sqlite3_column_int(pOutputIdx, 0);
130370     rc = sqlite3_reset(pOutputIdx);
130371   }
130372 
130373   return rc;
130374 }
130375 
130376 /*
130377 ** Allocate an appendable output segment on absolute level iAbsLevel+1
130378 ** with idx value iIdx.
130379 **
130380 ** In the %_segdir table, a segment is defined by the values in three
130381 ** columns:
130382 **
130383 **     start_block
130384 **     leaves_end_block
130385 **     end_block
130386 **
130387 ** When an appendable segment is allocated, it is estimated that the
130388 ** maximum number of leaf blocks that may be required is the sum of the
130389 ** number of leaf blocks consumed by the input segments, plus the number
130390 ** of input segments, multiplied by two. This value is stored in stack
130391 ** variable nLeafEst.
130392 **
130393 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
130394 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
130395 ** array of leaf nodes starts at the first block allocated. The array
130396 ** of interior nodes that are parents of the leaf nodes start at block
130397 ** (start_block + (1 + end_block - start_block) / 16). And so on.
130398 **
130399 ** In the actual code below, the value "16" is replaced with the
130400 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
130401 */
130402 static int fts3IncrmergeWriter(
130403   Fts3Table *p,                   /* Fts3 table handle */
130404   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
130405   int iIdx,                       /* Index of new output segment */
130406   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
130407   IncrmergeWriter *pWriter        /* Populate this object */
130408 ){
130409   int rc;                         /* Return Code */
130410   int i;                          /* Iterator variable */
130411   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
130412   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
130413   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
130414 
130415   /* Calculate nLeafEst. */
130416   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
130417   if( rc==SQLITE_OK ){
130418     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
130419     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
130420     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
130421       nLeafEst = sqlite3_column_int(pLeafEst, 0);
130422     }
130423     rc = sqlite3_reset(pLeafEst);
130424   }
130425   if( rc!=SQLITE_OK ) return rc;
130426 
130427   /* Calculate the first block to use in the output segment */
130428   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
130429   if( rc==SQLITE_OK ){
130430     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
130431       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
130432       pWriter->iEnd = pWriter->iStart - 1;
130433       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
130434     }
130435     rc = sqlite3_reset(pFirstBlock);
130436   }
130437   if( rc!=SQLITE_OK ) return rc;
130438 
130439   /* Insert the marker in the %_segments table to make sure nobody tries
130440   ** to steal the space just allocated. This is also used to identify
130441   ** appendable segments.  */
130442   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
130443   if( rc!=SQLITE_OK ) return rc;
130444 
130445   pWriter->iAbsLevel = iAbsLevel;
130446   pWriter->nLeafEst = nLeafEst;
130447   pWriter->iIdx = iIdx;
130448 
130449   /* Set up the array of NodeWriter objects */
130450   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
130451     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
130452   }
130453   return SQLITE_OK;
130454 }
130455 
130456 /*
130457 ** Remove an entry from the %_segdir table. This involves running the
130458 ** following two statements:
130459 **
130460 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
130461 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
130462 **
130463 ** The DELETE statement removes the specific %_segdir level. The UPDATE
130464 ** statement ensures that the remaining segments have contiguously allocated
130465 ** idx values.
130466 */
130467 static int fts3RemoveSegdirEntry(
130468   Fts3Table *p,                   /* FTS3 table handle */
130469   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
130470   int iIdx                        /* Index of %_segdir entry to delete */
130471 ){
130472   int rc;                         /* Return code */
130473   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
130474 
130475   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
130476   if( rc==SQLITE_OK ){
130477     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
130478     sqlite3_bind_int(pDelete, 2, iIdx);
130479     sqlite3_step(pDelete);
130480     rc = sqlite3_reset(pDelete);
130481   }
130482 
130483   return rc;
130484 }
130485 
130486 /*
130487 ** One or more segments have just been removed from absolute level iAbsLevel.
130488 ** Update the 'idx' values of the remaining segments in the level so that
130489 ** the idx values are a contiguous sequence starting from 0.
130490 */
130491 static int fts3RepackSegdirLevel(
130492   Fts3Table *p,                   /* FTS3 table handle */
130493   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
130494 ){
130495   int rc;                         /* Return code */
130496   int *aIdx = 0;                  /* Array of remaining idx values */
130497   int nIdx = 0;                   /* Valid entries in aIdx[] */
130498   int nAlloc = 0;                 /* Allocated size of aIdx[] */
130499   int i;                          /* Iterator variable */
130500   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
130501   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
130502 
130503   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
130504   if( rc==SQLITE_OK ){
130505     int rc2;
130506     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
130507     while( SQLITE_ROW==sqlite3_step(pSelect) ){
130508       if( nIdx>=nAlloc ){
130509         int *aNew;
130510         nAlloc += 16;
130511         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
130512         if( !aNew ){
130513           rc = SQLITE_NOMEM;
130514           break;
130515         }
130516         aIdx = aNew;
130517       }
130518       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
130519     }
130520     rc2 = sqlite3_reset(pSelect);
130521     if( rc==SQLITE_OK ) rc = rc2;
130522   }
130523 
130524   if( rc==SQLITE_OK ){
130525     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
130526   }
130527   if( rc==SQLITE_OK ){
130528     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
130529   }
130530 
130531   assert( p->bIgnoreSavepoint==0 );
130532   p->bIgnoreSavepoint = 1;
130533   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
130534     if( aIdx[i]!=i ){
130535       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
130536       sqlite3_bind_int(pUpdate, 1, i);
130537       sqlite3_step(pUpdate);
130538       rc = sqlite3_reset(pUpdate);
130539     }
130540   }
130541   p->bIgnoreSavepoint = 0;
130542 
130543   sqlite3_free(aIdx);
130544   return rc;
130545 }
130546 
130547 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
130548   pNode->a[0] = (char)iHeight;
130549   if( iChild ){
130550     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
130551     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
130552   }else{
130553     assert( pNode->nAlloc>=1 );
130554     pNode->n = 1;
130555   }
130556 }
130557 
130558 /*
130559 ** The first two arguments are a pointer to and the size of a segment b-tree
130560 ** node. The node may be a leaf or an internal node.
130561 **
130562 ** This function creates a new node image in blob object *pNew by copying
130563 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
130564 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
130565 */
130566 static int fts3TruncateNode(
130567   const char *aNode,              /* Current node image */
130568   int nNode,                      /* Size of aNode in bytes */
130569   Blob *pNew,                     /* OUT: Write new node image here */
130570   const char *zTerm,              /* Omit all terms smaller than this */
130571   int nTerm,                      /* Size of zTerm in bytes */
130572   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
130573 ){
130574   NodeReader reader;              /* Reader object */
130575   Blob prev = {0, 0, 0};          /* Previous term written to new node */
130576   int rc = SQLITE_OK;             /* Return code */
130577   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
130578 
130579   /* Allocate required output space */
130580   blobGrowBuffer(pNew, nNode, &rc);
130581   if( rc!=SQLITE_OK ) return rc;
130582   pNew->n = 0;
130583 
130584   /* Populate new node buffer */
130585   for(rc = nodeReaderInit(&reader, aNode, nNode);
130586       rc==SQLITE_OK && reader.aNode;
130587       rc = nodeReaderNext(&reader)
130588   ){
130589     if( pNew->n==0 ){
130590       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
130591       if( res<0 || (bLeaf==0 && res==0) ) continue;
130592       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
130593       *piBlock = reader.iChild;
130594     }
130595     rc = fts3AppendToNode(
130596         pNew, &prev, reader.term.a, reader.term.n,
130597         reader.aDoclist, reader.nDoclist
130598     );
130599     if( rc!=SQLITE_OK ) break;
130600   }
130601   if( pNew->n==0 ){
130602     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
130603     *piBlock = reader.iChild;
130604   }
130605   assert( pNew->n<=pNew->nAlloc );
130606 
130607   nodeReaderRelease(&reader);
130608   sqlite3_free(prev.a);
130609   return rc;
130610 }
130611 
130612 /*
130613 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
130614 ** level iAbsLevel. This may involve deleting entries from the %_segments
130615 ** table, and modifying existing entries in both the %_segments and %_segdir
130616 ** tables.
130617 **
130618 ** SQLITE_OK is returned if the segment is updated successfully. Or an
130619 ** SQLite error code otherwise.
130620 */
130621 static int fts3TruncateSegment(
130622   Fts3Table *p,                   /* FTS3 table handle */
130623   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
130624   int iIdx,                       /* Index within level of segment to modify */
130625   const char *zTerm,              /* Remove terms smaller than this */
130626   int nTerm                      /* Number of bytes in buffer zTerm */
130627 ){
130628   int rc = SQLITE_OK;             /* Return code */
130629   Blob root = {0,0,0};            /* New root page image */
130630   Blob block = {0,0,0};           /* Buffer used for any other block */
130631   sqlite3_int64 iBlock = 0;       /* Block id */
130632   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
130633   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
130634   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
130635 
130636   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
130637   if( rc==SQLITE_OK ){
130638     int rc2;                      /* sqlite3_reset() return code */
130639     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
130640     sqlite3_bind_int(pFetch, 2, iIdx);
130641     if( SQLITE_ROW==sqlite3_step(pFetch) ){
130642       const char *aRoot = sqlite3_column_blob(pFetch, 4);
130643       int nRoot = sqlite3_column_bytes(pFetch, 4);
130644       iOldStart = sqlite3_column_int64(pFetch, 1);
130645       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
130646     }
130647     rc2 = sqlite3_reset(pFetch);
130648     if( rc==SQLITE_OK ) rc = rc2;
130649   }
130650 
130651   while( rc==SQLITE_OK && iBlock ){
130652     char *aBlock = 0;
130653     int nBlock = 0;
130654     iNewStart = iBlock;
130655 
130656     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
130657     if( rc==SQLITE_OK ){
130658       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
130659     }
130660     if( rc==SQLITE_OK ){
130661       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
130662     }
130663     sqlite3_free(aBlock);
130664   }
130665 
130666   /* Variable iNewStart now contains the first valid leaf node. */
130667   if( rc==SQLITE_OK && iNewStart ){
130668     sqlite3_stmt *pDel = 0;
130669     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
130670     if( rc==SQLITE_OK ){
130671       sqlite3_bind_int64(pDel, 1, iOldStart);
130672       sqlite3_bind_int64(pDel, 2, iNewStart-1);
130673       sqlite3_step(pDel);
130674       rc = sqlite3_reset(pDel);
130675     }
130676   }
130677 
130678   if( rc==SQLITE_OK ){
130679     sqlite3_stmt *pChomp = 0;
130680     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
130681     if( rc==SQLITE_OK ){
130682       sqlite3_bind_int64(pChomp, 1, iNewStart);
130683       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
130684       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
130685       sqlite3_bind_int(pChomp, 4, iIdx);
130686       sqlite3_step(pChomp);
130687       rc = sqlite3_reset(pChomp);
130688     }
130689   }
130690 
130691   sqlite3_free(root.a);
130692   sqlite3_free(block.a);
130693   return rc;
130694 }
130695 
130696 /*
130697 ** This function is called after an incrmental-merge operation has run to
130698 ** merge (or partially merge) two or more segments from absolute level
130699 ** iAbsLevel.
130700 **
130701 ** Each input segment is either removed from the db completely (if all of
130702 ** its data was copied to the output segment by the incrmerge operation)
130703 ** or modified in place so that it no longer contains those entries that
130704 ** have been duplicated in the output segment.
130705 */
130706 static int fts3IncrmergeChomp(
130707   Fts3Table *p,                   /* FTS table handle */
130708   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
130709   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
130710   int *pnRem                      /* Number of segments not deleted */
130711 ){
130712   int i;
130713   int nRem = 0;
130714   int rc = SQLITE_OK;
130715 
130716   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
130717     Fts3SegReader *pSeg = 0;
130718     int j;
130719 
130720     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
130721     ** somewhere in the pCsr->apSegment[] array.  */
130722     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
130723       pSeg = pCsr->apSegment[j];
130724       if( pSeg->iIdx==i ) break;
130725     }
130726     assert( j<pCsr->nSegment && pSeg->iIdx==i );
130727 
130728     if( pSeg->aNode==0 ){
130729       /* Seg-reader is at EOF. Remove the entire input segment. */
130730       rc = fts3DeleteSegment(p, pSeg);
130731       if( rc==SQLITE_OK ){
130732         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
130733       }
130734       *pnRem = 0;
130735     }else{
130736       /* The incremental merge did not copy all the data from this
130737       ** segment to the upper level. The segment is modified in place
130738       ** so that it contains no keys smaller than zTerm/nTerm. */
130739       const char *zTerm = pSeg->zTerm;
130740       int nTerm = pSeg->nTerm;
130741       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
130742       nRem++;
130743     }
130744   }
130745 
130746   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
130747     rc = fts3RepackSegdirLevel(p, iAbsLevel);
130748   }
130749 
130750   *pnRem = nRem;
130751   return rc;
130752 }
130753 
130754 /*
130755 ** Store an incr-merge hint in the database.
130756 */
130757 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
130758   sqlite3_stmt *pReplace = 0;
130759   int rc;                         /* Return code */
130760 
130761   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
130762   if( rc==SQLITE_OK ){
130763     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
130764     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
130765     sqlite3_step(pReplace);
130766     rc = sqlite3_reset(pReplace);
130767   }
130768 
130769   return rc;
130770 }
130771 
130772 /*
130773 ** Load an incr-merge hint from the database. The incr-merge hint, if one
130774 ** exists, is stored in the rowid==1 row of the %_stat table.
130775 **
130776 ** If successful, populate blob *pHint with the value read from the %_stat
130777 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
130778 ** SQLite error code.
130779 */
130780 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
130781   sqlite3_stmt *pSelect = 0;
130782   int rc;
130783 
130784   pHint->n = 0;
130785   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
130786   if( rc==SQLITE_OK ){
130787     int rc2;
130788     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
130789     if( SQLITE_ROW==sqlite3_step(pSelect) ){
130790       const char *aHint = sqlite3_column_blob(pSelect, 0);
130791       int nHint = sqlite3_column_bytes(pSelect, 0);
130792       if( aHint ){
130793         blobGrowBuffer(pHint, nHint, &rc);
130794         if( rc==SQLITE_OK ){
130795           memcpy(pHint->a, aHint, nHint);
130796           pHint->n = nHint;
130797         }
130798       }
130799     }
130800     rc2 = sqlite3_reset(pSelect);
130801     if( rc==SQLITE_OK ) rc = rc2;
130802   }
130803 
130804   return rc;
130805 }
130806 
130807 /*
130808 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130809 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
130810 ** consists of two varints, the absolute level number of the input segments
130811 ** and the number of input segments.
130812 **
130813 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
130814 ** set *pRc to an SQLite error code before returning.
130815 */
130816 static void fts3IncrmergeHintPush(
130817   Blob *pHint,                    /* Hint blob to append to */
130818   i64 iAbsLevel,                  /* First varint to store in hint */
130819   int nInput,                     /* Second varint to store in hint */
130820   int *pRc                        /* IN/OUT: Error code */
130821 ){
130822   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
130823   if( *pRc==SQLITE_OK ){
130824     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
130825     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
130826   }
130827 }
130828 
130829 /*
130830 ** Read the last entry (most recently pushed) from the hint blob *pHint
130831 ** and then remove the entry. Write the two values read to *piAbsLevel and
130832 ** *pnInput before returning.
130833 **
130834 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
130835 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
130836 */
130837 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
130838   const int nHint = pHint->n;
130839   int i;
130840 
130841   i = pHint->n-2;
130842   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130843   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
130844 
130845   pHint->n = i;
130846   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
130847   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
130848   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
130849 
130850   return SQLITE_OK;
130851 }
130852 
130853 
130854 /*
130855 ** Attempt an incremental merge that writes nMerge leaf blocks.
130856 **
130857 ** Incremental merges happen nMin segments at a time. The two
130858 ** segments to be merged are the nMin oldest segments (the ones with
130859 ** the smallest indexes) in the highest level that contains at least
130860 ** nMin segments. Multiple merges might occur in an attempt to write the
130861 ** quota of nMerge leaf blocks.
130862 */
130863 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
130864   int rc;                         /* Return code */
130865   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
130866   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
130867   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
130868   IncrmergeWriter *pWriter;       /* Writer object */
130869   int nSeg = 0;                   /* Number of input segments */
130870   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
130871   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
130872   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
130873 
130874   /* Allocate space for the cursor, filter and writer objects */
130875   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
130876   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
130877   if( !pWriter ) return SQLITE_NOMEM;
130878   pFilter = (Fts3SegFilter *)&pWriter[1];
130879   pCsr = (Fts3MultiSegReader *)&pFilter[1];
130880 
130881   rc = fts3IncrmergeHintLoad(p, &hint);
130882   while( rc==SQLITE_OK && nRem>0 ){
130883     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
130884     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
130885     int bUseHint = 0;             /* True if attempting to append */
130886 
130887     /* Search the %_segdir table for the absolute level with the smallest
130888     ** relative level number that contains at least nMin segments, if any.
130889     ** If one is found, set iAbsLevel to the absolute level number and
130890     ** nSeg to nMin. If no level with at least nMin segments can be found,
130891     ** set nSeg to -1.
130892     */
130893     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
130894     sqlite3_bind_int(pFindLevel, 1, nMin);
130895     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
130896       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
130897       nSeg = nMin;
130898     }else{
130899       nSeg = -1;
130900     }
130901     rc = sqlite3_reset(pFindLevel);
130902 
130903     /* If the hint read from the %_stat table is not empty, check if the
130904     ** last entry in it specifies a relative level smaller than or equal
130905     ** to the level identified by the block above (if any). If so, this
130906     ** iteration of the loop will work on merging at the hinted level.
130907     */
130908     if( rc==SQLITE_OK && hint.n ){
130909       int nHint = hint.n;
130910       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
130911       int nHintSeg = 0;                     /* Hint number of segments */
130912 
130913       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
130914       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
130915         iAbsLevel = iHintAbsLevel;
130916         nSeg = nHintSeg;
130917         bUseHint = 1;
130918         bDirtyHint = 1;
130919       }else{
130920         /* This undoes the effect of the HintPop() above - so that no entry
130921         ** is removed from the hint blob.  */
130922         hint.n = nHint;
130923       }
130924     }
130925 
130926     /* If nSeg is less that zero, then there is no level with at least
130927     ** nMin segments and no hint in the %_stat table. No work to do.
130928     ** Exit early in this case.  */
130929     if( nSeg<0 ) break;
130930 
130931     /* Open a cursor to iterate through the contents of the oldest nSeg
130932     ** indexes of absolute level iAbsLevel. If this cursor is opened using
130933     ** the 'hint' parameters, it is possible that there are less than nSeg
130934     ** segments available in level iAbsLevel. In this case, no work is
130935     ** done on iAbsLevel - fall through to the next iteration of the loop
130936     ** to start work on some other level.  */
130937     memset(pWriter, 0, nAlloc);
130938     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
130939     if( rc==SQLITE_OK ){
130940       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
130941     }
130942     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
130943      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
130944      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
130945     ){
130946       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
130947       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
130948       if( rc==SQLITE_OK ){
130949         if( bUseHint && iIdx>0 ){
130950           const char *zKey = pCsr->zTerm;
130951           int nKey = pCsr->nTerm;
130952           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
130953         }else{
130954           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
130955         }
130956       }
130957 
130958       if( rc==SQLITE_OK && pWriter->nLeafEst ){
130959         fts3LogMerge(nSeg, iAbsLevel);
130960         do {
130961           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
130962           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
130963           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
130964         }while( rc==SQLITE_ROW );
130965 
130966         /* Update or delete the input segments */
130967         if( rc==SQLITE_OK ){
130968           nRem -= (1 + pWriter->nWork);
130969           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
130970           if( nSeg!=0 ){
130971             bDirtyHint = 1;
130972             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
130973           }
130974         }
130975       }
130976 
130977       fts3IncrmergeRelease(p, pWriter, &rc);
130978     }
130979 
130980     sqlite3Fts3SegReaderFinish(pCsr);
130981   }
130982 
130983   /* Write the hint values into the %_stat table for the next incr-merger */
130984   if( bDirtyHint && rc==SQLITE_OK ){
130985     rc = fts3IncrmergeHintStore(p, &hint);
130986   }
130987 
130988   sqlite3_free(pWriter);
130989   sqlite3_free(hint.a);
130990   return rc;
130991 }
130992 
130993 /*
130994 ** Convert the text beginning at *pz into an integer and return
130995 ** its value.  Advance *pz to point to the first character past
130996 ** the integer.
130997 */
130998 static int fts3Getint(const char **pz){
130999   const char *z = *pz;
131000   int i = 0;
131001   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
131002   *pz = z;
131003   return i;
131004 }
131005 
131006 /*
131007 ** Process statements of the form:
131008 **
131009 **    INSERT INTO table(table) VALUES('merge=A,B');
131010 **
131011 ** A and B are integers that decode to be the number of leaf pages
131012 ** written for the merge, and the minimum number of segments on a level
131013 ** before it will be selected for a merge, respectively.
131014 */
131015 static int fts3DoIncrmerge(
131016   Fts3Table *p,                   /* FTS3 table handle */
131017   const char *zParam              /* Nul-terminated string containing "A,B" */
131018 ){
131019   int rc;
131020   int nMin = (FTS3_MERGE_COUNT / 2);
131021   int nMerge = 0;
131022   const char *z = zParam;
131023 
131024   /* Read the first integer value */
131025   nMerge = fts3Getint(&z);
131026 
131027   /* If the first integer value is followed by a ',',  read the second
131028   ** integer value. */
131029   if( z[0]==',' && z[1]!='\0' ){
131030     z++;
131031     nMin = fts3Getint(&z);
131032   }
131033 
131034   if( z[0]!='\0' || nMin<2 ){
131035     rc = SQLITE_ERROR;
131036   }else{
131037     rc = SQLITE_OK;
131038     if( !p->bHasStat ){
131039       assert( p->bFts4==0 );
131040       sqlite3Fts3CreateStatTable(&rc, p);
131041     }
131042     if( rc==SQLITE_OK ){
131043       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
131044     }
131045     sqlite3Fts3SegmentsClose(p);
131046   }
131047   return rc;
131048 }
131049 
131050 /*
131051 ** Process statements of the form:
131052 **
131053 **    INSERT INTO table(table) VALUES('automerge=X');
131054 **
131055 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
131056 ** turn it on.  The setting is persistent.
131057 */
131058 static int fts3DoAutoincrmerge(
131059   Fts3Table *p,                   /* FTS3 table handle */
131060   const char *zParam              /* Nul-terminated string containing boolean */
131061 ){
131062   int rc = SQLITE_OK;
131063   sqlite3_stmt *pStmt = 0;
131064   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
131065   if( !p->bHasStat ){
131066     assert( p->bFts4==0 );
131067     sqlite3Fts3CreateStatTable(&rc, p);
131068     if( rc ) return rc;
131069   }
131070   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
131071   if( rc ) return rc;;
131072   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
131073   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
131074   sqlite3_step(pStmt);
131075   rc = sqlite3_reset(pStmt);
131076   return rc;
131077 }
131078 
131079 /*
131080 ** Return a 64-bit checksum for the FTS index entry specified by the
131081 ** arguments to this function.
131082 */
131083 static u64 fts3ChecksumEntry(
131084   const char *zTerm,              /* Pointer to buffer containing term */
131085   int nTerm,                      /* Size of zTerm in bytes */
131086   int iLangid,                    /* Language id for current row */
131087   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
131088   i64 iDocid,                     /* Docid for current row. */
131089   int iCol,                       /* Column number */
131090   int iPos                        /* Position */
131091 ){
131092   int i;
131093   u64 ret = (u64)iDocid;
131094 
131095   ret += (ret<<3) + iLangid;
131096   ret += (ret<<3) + iIndex;
131097   ret += (ret<<3) + iCol;
131098   ret += (ret<<3) + iPos;
131099   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
131100 
131101   return ret;
131102 }
131103 
131104 /*
131105 ** Return a checksum of all entries in the FTS index that correspond to
131106 ** language id iLangid. The checksum is calculated by XORing the checksums
131107 ** of each individual entry (see fts3ChecksumEntry()) together.
131108 **
131109 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
131110 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
131111 ** return value is undefined in this case.
131112 */
131113 static u64 fts3ChecksumIndex(
131114   Fts3Table *p,                   /* FTS3 table handle */
131115   int iLangid,                    /* Language id to return cksum for */
131116   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
131117   int *pRc                        /* OUT: Return code */
131118 ){
131119   Fts3SegFilter filter;
131120   Fts3MultiSegReader csr;
131121   int rc;
131122   u64 cksum = 0;
131123 
131124   assert( *pRc==SQLITE_OK );
131125 
131126   memset(&filter, 0, sizeof(filter));
131127   memset(&csr, 0, sizeof(csr));
131128   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
131129   filter.flags |= FTS3_SEGMENT_SCAN;
131130 
131131   rc = sqlite3Fts3SegReaderCursor(
131132       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
131133   );
131134   if( rc==SQLITE_OK ){
131135     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
131136   }
131137 
131138   if( rc==SQLITE_OK ){
131139     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
131140       char *pCsr = csr.aDoclist;
131141       char *pEnd = &pCsr[csr.nDoclist];
131142 
131143       i64 iDocid = 0;
131144       i64 iCol = 0;
131145       i64 iPos = 0;
131146 
131147       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
131148       while( pCsr<pEnd ){
131149         i64 iVal = 0;
131150         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
131151         if( pCsr<pEnd ){
131152           if( iVal==0 || iVal==1 ){
131153             iCol = 0;
131154             iPos = 0;
131155             if( iVal ){
131156               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
131157             }else{
131158               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
131159               iDocid += iVal;
131160             }
131161           }else{
131162             iPos += (iVal - 2);
131163             cksum = cksum ^ fts3ChecksumEntry(
131164                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
131165                 (int)iCol, (int)iPos
131166             );
131167           }
131168         }
131169       }
131170     }
131171   }
131172   sqlite3Fts3SegReaderFinish(&csr);
131173 
131174   *pRc = rc;
131175   return cksum;
131176 }
131177 
131178 /*
131179 ** Check if the contents of the FTS index match the current contents of the
131180 ** content table. If no error occurs and the contents do match, set *pbOk
131181 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
131182 ** to false before returning.
131183 **
131184 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
131185 ** code. The final value of *pbOk is undefined in this case.
131186 */
131187 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
131188   int rc = SQLITE_OK;             /* Return code */
131189   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
131190   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
131191   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
131192 
131193   /* This block calculates the checksum according to the FTS index. */
131194   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131195   if( rc==SQLITE_OK ){
131196     int rc2;
131197     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
131198     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
131199       int iLangid = sqlite3_column_int(pAllLangid, 0);
131200       int i;
131201       for(i=0; i<p->nIndex; i++){
131202         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
131203       }
131204     }
131205     rc2 = sqlite3_reset(pAllLangid);
131206     if( rc==SQLITE_OK ) rc = rc2;
131207   }
131208 
131209   /* This block calculates the checksum according to the %_content table */
131210   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131211   if( rc==SQLITE_OK ){
131212     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
131213     sqlite3_stmt *pStmt = 0;
131214     char *zSql;
131215 
131216     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
131217     if( !zSql ){
131218       rc = SQLITE_NOMEM;
131219     }else{
131220       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
131221       sqlite3_free(zSql);
131222     }
131223 
131224     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
131225       i64 iDocid = sqlite3_column_int64(pStmt, 0);
131226       int iLang = langidFromSelect(p, pStmt);
131227       int iCol;
131228 
131229       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
131230         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
131231         int nText = sqlite3_column_bytes(pStmt, iCol+1);
131232         sqlite3_tokenizer_cursor *pT = 0;
131233 
131234         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
131235         while( rc==SQLITE_OK ){
131236           char const *zToken;       /* Buffer containing token */
131237           int nToken = 0;           /* Number of bytes in token */
131238           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
131239           int iPos = 0;             /* Position of token in zText */
131240 
131241           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
131242           if( rc==SQLITE_OK ){
131243             int i;
131244             cksum2 = cksum2 ^ fts3ChecksumEntry(
131245                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
131246             );
131247             for(i=1; i<p->nIndex; i++){
131248               if( p->aIndex[i].nPrefix<=nToken ){
131249                 cksum2 = cksum2 ^ fts3ChecksumEntry(
131250                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
131251                 );
131252               }
131253             }
131254           }
131255         }
131256         if( pT ) pModule->xClose(pT);
131257         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131258       }
131259     }
131260 
131261     sqlite3_finalize(pStmt);
131262   }
131263 
131264   *pbOk = (cksum1==cksum2);
131265   return rc;
131266 }
131267 
131268 /*
131269 ** Run the integrity-check. If no error occurs and the current contents of
131270 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
131271 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
131272 **
131273 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
131274 ** error code.
131275 **
131276 ** The integrity-check works as follows. For each token and indexed token
131277 ** prefix in the document set, a 64-bit checksum is calculated (by code
131278 ** in fts3ChecksumEntry()) based on the following:
131279 **
131280 **     + The index number (0 for the main index, 1 for the first prefix
131281 **       index etc.),
131282 **     + The token (or token prefix) text itself,
131283 **     + The language-id of the row it appears in,
131284 **     + The docid of the row it appears in,
131285 **     + The column it appears in, and
131286 **     + The tokens position within that column.
131287 **
131288 ** The checksums for all entries in the index are XORed together to create
131289 ** a single checksum for the entire index.
131290 **
131291 ** The integrity-check code calculates the same checksum in two ways:
131292 **
131293 **     1. By scanning the contents of the FTS index, and
131294 **     2. By scanning and tokenizing the content table.
131295 **
131296 ** If the two checksums are identical, the integrity-check is deemed to have
131297 ** passed.
131298 */
131299 static int fts3DoIntegrityCheck(
131300   Fts3Table *p                    /* FTS3 table handle */
131301 ){
131302   int rc;
131303   int bOk = 0;
131304   rc = fts3IntegrityCheck(p, &bOk);
131305   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
131306   return rc;
131307 }
131308 
131309 /*
131310 ** Handle a 'special' INSERT of the form:
131311 **
131312 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
131313 **
131314 ** Argument pVal contains the result of <expr>. Currently the only
131315 ** meaningful value to insert is the text 'optimize'.
131316 */
131317 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
131318   int rc;                         /* Return Code */
131319   const char *zVal = (const char *)sqlite3_value_text(pVal);
131320   int nVal = sqlite3_value_bytes(pVal);
131321 
131322   if( !zVal ){
131323     return SQLITE_NOMEM;
131324   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
131325     rc = fts3DoOptimize(p, 0);
131326   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
131327     rc = fts3DoRebuild(p);
131328   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
131329     rc = fts3DoIntegrityCheck(p);
131330   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
131331     rc = fts3DoIncrmerge(p, &zVal[6]);
131332   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
131333     rc = fts3DoAutoincrmerge(p, &zVal[10]);
131334 #ifdef SQLITE_TEST
131335   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
131336     p->nNodeSize = atoi(&zVal[9]);
131337     rc = SQLITE_OK;
131338   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
131339     p->nMaxPendingData = atoi(&zVal[11]);
131340     rc = SQLITE_OK;
131341 #endif
131342   }else{
131343     rc = SQLITE_ERROR;
131344   }
131345 
131346   return rc;
131347 }
131348 
131349 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
131350 /*
131351 ** Delete all cached deferred doclists. Deferred doclists are cached
131352 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
131353 */
131354 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
131355   Fts3DeferredToken *pDef;
131356   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
131357     fts3PendingListDelete(pDef->pList);
131358     pDef->pList = 0;
131359   }
131360 }
131361 
131362 /*
131363 ** Free all entries in the pCsr->pDeffered list. Entries are added to
131364 ** this list using sqlite3Fts3DeferToken().
131365 */
131366 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
131367   Fts3DeferredToken *pDef;
131368   Fts3DeferredToken *pNext;
131369   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
131370     pNext = pDef->pNext;
131371     fts3PendingListDelete(pDef->pList);
131372     sqlite3_free(pDef);
131373   }
131374   pCsr->pDeferred = 0;
131375 }
131376 
131377 /*
131378 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
131379 ** based on the row that pCsr currently points to.
131380 **
131381 ** A deferred-doclist is like any other doclist with position information
131382 ** included, except that it only contains entries for a single row of the
131383 ** table, not for all rows.
131384 */
131385 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
131386   int rc = SQLITE_OK;             /* Return code */
131387   if( pCsr->pDeferred ){
131388     int i;                        /* Used to iterate through table columns */
131389     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
131390     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
131391 
131392     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
131393     sqlite3_tokenizer *pT = p->pTokenizer;
131394     sqlite3_tokenizer_module const *pModule = pT->pModule;
131395 
131396     assert( pCsr->isRequireSeek==0 );
131397     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
131398 
131399     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
131400       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
131401       sqlite3_tokenizer_cursor *pTC = 0;
131402 
131403       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
131404       while( rc==SQLITE_OK ){
131405         char const *zToken;       /* Buffer containing token */
131406         int nToken = 0;           /* Number of bytes in token */
131407         int iDum1 = 0, iDum2 = 0; /* Dummy variables */
131408         int iPos = 0;             /* Position of token in zText */
131409 
131410         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
131411         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
131412           Fts3PhraseToken *pPT = pDef->pToken;
131413           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
131414            && (pPT->bFirst==0 || iPos==0)
131415            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
131416            && (0==memcmp(zToken, pPT->z, pPT->n))
131417           ){
131418             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
131419           }
131420         }
131421       }
131422       if( pTC ) pModule->xClose(pTC);
131423       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131424     }
131425 
131426     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
131427       if( pDef->pList ){
131428         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
131429       }
131430     }
131431   }
131432 
131433   return rc;
131434 }
131435 
131436 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
131437   Fts3DeferredToken *p,
131438   char **ppData,
131439   int *pnData
131440 ){
131441   char *pRet;
131442   int nSkip;
131443   sqlite3_int64 dummy;
131444 
131445   *ppData = 0;
131446   *pnData = 0;
131447 
131448   if( p->pList==0 ){
131449     return SQLITE_OK;
131450   }
131451 
131452   pRet = (char *)sqlite3_malloc(p->pList->nData);
131453   if( !pRet ) return SQLITE_NOMEM;
131454 
131455   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
131456   *pnData = p->pList->nData - nSkip;
131457   *ppData = pRet;
131458 
131459   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
131460   return SQLITE_OK;
131461 }
131462 
131463 /*
131464 ** Add an entry for token pToken to the pCsr->pDeferred list.
131465 */
131466 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
131467   Fts3Cursor *pCsr,               /* Fts3 table cursor */
131468   Fts3PhraseToken *pToken,        /* Token to defer */
131469   int iCol                        /* Column that token must appear in (or -1) */
131470 ){
131471   Fts3DeferredToken *pDeferred;
131472   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
131473   if( !pDeferred ){
131474     return SQLITE_NOMEM;
131475   }
131476   memset(pDeferred, 0, sizeof(*pDeferred));
131477   pDeferred->pToken = pToken;
131478   pDeferred->pNext = pCsr->pDeferred;
131479   pDeferred->iCol = iCol;
131480   pCsr->pDeferred = pDeferred;
131481 
131482   assert( pToken->pDeferred==0 );
131483   pToken->pDeferred = pDeferred;
131484 
131485   return SQLITE_OK;
131486 }
131487 #endif
131488 
131489 /*
131490 ** SQLite value pRowid contains the rowid of a row that may or may not be
131491 ** present in the FTS3 table. If it is, delete it and adjust the contents
131492 ** of subsiduary data structures accordingly.
131493 */
131494 static int fts3DeleteByRowid(
131495   Fts3Table *p,
131496   sqlite3_value *pRowid,
131497   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
131498   u32 *aSzDel
131499 ){
131500   int rc = SQLITE_OK;             /* Return code */
131501   int bFound = 0;                 /* True if *pRowid really is in the table */
131502 
131503   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
131504   if( bFound && rc==SQLITE_OK ){
131505     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
131506     rc = fts3IsEmpty(p, pRowid, &isEmpty);
131507     if( rc==SQLITE_OK ){
131508       if( isEmpty ){
131509         /* Deleting this row means the whole table is empty. In this case
131510         ** delete the contents of all three tables and throw away any
131511         ** data in the pendingTerms hash table.  */
131512         rc = fts3DeleteAll(p, 1);
131513         *pnChng = 0;
131514         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
131515       }else{
131516         *pnChng = *pnChng - 1;
131517         if( p->zContentTbl==0 ){
131518           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
131519         }
131520         if( p->bHasDocsize ){
131521           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
131522         }
131523       }
131524     }
131525   }
131526 
131527   return rc;
131528 }
131529 
131530 /*
131531 ** This function does the work for the xUpdate method of FTS3 virtual
131532 ** tables. The schema of the virtual table being:
131533 **
131534 **     CREATE TABLE <table name>(
131535 **       <user columns>,
131536 **       <table name> HIDDEN,
131537 **       docid HIDDEN,
131538 **       <langid> HIDDEN
131539 **     );
131540 **
131541 **
131542 */
131543 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
131544   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
131545   int nArg,                       /* Size of argument array */
131546   sqlite3_value **apVal,          /* Array of arguments */
131547   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
131548 ){
131549   Fts3Table *p = (Fts3Table *)pVtab;
131550   int rc = SQLITE_OK;             /* Return Code */
131551   int isRemove = 0;               /* True for an UPDATE or DELETE */
131552   u32 *aSzIns = 0;                /* Sizes of inserted documents */
131553   u32 *aSzDel = 0;                /* Sizes of deleted documents */
131554   int nChng = 0;                  /* Net change in number of documents */
131555   int bInsertDone = 0;
131556 
131557   assert( p->pSegments==0 );
131558   assert(
131559       nArg==1                     /* DELETE operations */
131560    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
131561   );
131562 
131563   /* Check for a "special" INSERT operation. One of the form:
131564   **
131565   **   INSERT INTO xyz(xyz) VALUES('command');
131566   */
131567   if( nArg>1
131568    && sqlite3_value_type(apVal[0])==SQLITE_NULL
131569    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
131570   ){
131571     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
131572     goto update_out;
131573   }
131574 
131575   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
131576     rc = SQLITE_CONSTRAINT;
131577     goto update_out;
131578   }
131579 
131580   /* Allocate space to hold the change in document sizes */
131581   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
131582   if( aSzDel==0 ){
131583     rc = SQLITE_NOMEM;
131584     goto update_out;
131585   }
131586   aSzIns = &aSzDel[p->nColumn+1];
131587   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
131588 
131589   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
131590   ** value, then this operation requires constraint handling.
131591   **
131592   ** If the on-conflict mode is REPLACE, this means that the existing row
131593   ** should be deleted from the database before inserting the new row. Or,
131594   ** if the on-conflict mode is other than REPLACE, then this method must
131595   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
131596   ** modify the database file.
131597   */
131598   if( nArg>1 && p->zContentTbl==0 ){
131599     /* Find the value object that holds the new rowid value. */
131600     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
131601     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
131602       pNewRowid = apVal[1];
131603     }
131604 
131605     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
131606         sqlite3_value_type(apVal[0])==SQLITE_NULL
131607      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
131608     )){
131609       /* The new rowid is not NULL (in this case the rowid will be
131610       ** automatically assigned and there is no chance of a conflict), and
131611       ** the statement is either an INSERT or an UPDATE that modifies the
131612       ** rowid column. So if the conflict mode is REPLACE, then delete any
131613       ** existing row with rowid=pNewRowid.
131614       **
131615       ** Or, if the conflict mode is not REPLACE, insert the new record into
131616       ** the %_content table. If we hit the duplicate rowid constraint (or any
131617       ** other error) while doing so, return immediately.
131618       **
131619       ** This branch may also run if pNewRowid contains a value that cannot
131620       ** be losslessly converted to an integer. In this case, the eventual
131621       ** call to fts3InsertData() (either just below or further on in this
131622       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
131623       ** invoked, it will delete zero rows (since no row will have
131624       ** docid=$pNewRowid if $pNewRowid is not an integer value).
131625       */
131626       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
131627         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
131628       }else{
131629         rc = fts3InsertData(p, apVal, pRowid);
131630         bInsertDone = 1;
131631       }
131632     }
131633   }
131634   if( rc!=SQLITE_OK ){
131635     goto update_out;
131636   }
131637 
131638   /* If this is a DELETE or UPDATE operation, remove the old record. */
131639   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
131640     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
131641     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
131642     isRemove = 1;
131643   }
131644 
131645   /* If this is an INSERT or UPDATE operation, insert the new record. */
131646   if( nArg>1 && rc==SQLITE_OK ){
131647     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
131648     if( bInsertDone==0 ){
131649       rc = fts3InsertData(p, apVal, pRowid);
131650       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
131651         rc = FTS_CORRUPT_VTAB;
131652       }
131653     }
131654     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
131655       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
131656     }
131657     if( rc==SQLITE_OK ){
131658       assert( p->iPrevDocid==*pRowid );
131659       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
131660     }
131661     if( p->bHasDocsize ){
131662       fts3InsertDocsize(&rc, p, aSzIns);
131663     }
131664     nChng++;
131665   }
131666 
131667   if( p->bFts4 ){
131668     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
131669   }
131670 
131671  update_out:
131672   sqlite3_free(aSzDel);
131673   sqlite3Fts3SegmentsClose(p);
131674   return rc;
131675 }
131676 
131677 /*
131678 ** Flush any data in the pending-terms hash table to disk. If successful,
131679 ** merge all segments in the database (including the new segment, if
131680 ** there was any data to flush) into a single segment.
131681 */
131682 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
131683   int rc;
131684   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
131685   if( rc==SQLITE_OK ){
131686     rc = fts3DoOptimize(p, 1);
131687     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
131688       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131689       if( rc2!=SQLITE_OK ) rc = rc2;
131690     }else{
131691       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
131692       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
131693     }
131694   }
131695   sqlite3Fts3SegmentsClose(p);
131696   return rc;
131697 }
131698 
131699 #endif
131700 
131701 /************** End of fts3_write.c ******************************************/
131702 /************** Begin file fts3_snippet.c ************************************/
131703 /*
131704 ** 2009 Oct 23
131705 **
131706 ** The author disclaims copyright to this source code.  In place of
131707 ** a legal notice, here is a blessing:
131708 **
131709 **    May you do good and not evil.
131710 **    May you find forgiveness for yourself and forgive others.
131711 **    May you share freely, never taking more than you give.
131712 **
131713 ******************************************************************************
131714 */
131715 
131716 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131717 
131718 /* #include <string.h> */
131719 /* #include <assert.h> */
131720 
131721 /*
131722 ** Characters that may appear in the second argument to matchinfo().
131723 */
131724 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
131725 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
131726 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
131727 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
131728 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
131729 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
131730 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
131731 
131732 /*
131733 ** The default value for the second argument to matchinfo().
131734 */
131735 #define FTS3_MATCHINFO_DEFAULT   "pcx"
131736 
131737 
131738 /*
131739 ** Used as an fts3ExprIterate() context when loading phrase doclists to
131740 ** Fts3Expr.aDoclist[]/nDoclist.
131741 */
131742 typedef struct LoadDoclistCtx LoadDoclistCtx;
131743 struct LoadDoclistCtx {
131744   Fts3Cursor *pCsr;               /* FTS3 Cursor */
131745   int nPhrase;                    /* Number of phrases seen so far */
131746   int nToken;                     /* Number of tokens seen so far */
131747 };
131748 
131749 /*
131750 ** The following types are used as part of the implementation of the
131751 ** fts3BestSnippet() routine.
131752 */
131753 typedef struct SnippetIter SnippetIter;
131754 typedef struct SnippetPhrase SnippetPhrase;
131755 typedef struct SnippetFragment SnippetFragment;
131756 
131757 struct SnippetIter {
131758   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
131759   int iCol;                       /* Extract snippet from this column */
131760   int nSnippet;                   /* Requested snippet length (in tokens) */
131761   int nPhrase;                    /* Number of phrases in query */
131762   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
131763   int iCurrent;                   /* First token of current snippet */
131764 };
131765 
131766 struct SnippetPhrase {
131767   int nToken;                     /* Number of tokens in phrase */
131768   char *pList;                    /* Pointer to start of phrase position list */
131769   int iHead;                      /* Next value in position list */
131770   char *pHead;                    /* Position list data following iHead */
131771   int iTail;                      /* Next value in trailing position list */
131772   char *pTail;                    /* Position list data following iTail */
131773 };
131774 
131775 struct SnippetFragment {
131776   int iCol;                       /* Column snippet is extracted from */
131777   int iPos;                       /* Index of first token in snippet */
131778   u64 covered;                    /* Mask of query phrases covered */
131779   u64 hlmask;                     /* Mask of snippet terms to highlight */
131780 };
131781 
131782 /*
131783 ** This type is used as an fts3ExprIterate() context object while
131784 ** accumulating the data returned by the matchinfo() function.
131785 */
131786 typedef struct MatchInfo MatchInfo;
131787 struct MatchInfo {
131788   Fts3Cursor *pCursor;            /* FTS3 Cursor */
131789   int nCol;                       /* Number of columns in table */
131790   int nPhrase;                    /* Number of matchable phrases in query */
131791   sqlite3_int64 nDoc;             /* Number of docs in database */
131792   u32 *aMatchinfo;                /* Pre-allocated buffer */
131793 };
131794 
131795 
131796 
131797 /*
131798 ** The snippet() and offsets() functions both return text values. An instance
131799 ** of the following structure is used to accumulate those values while the
131800 ** functions are running. See fts3StringAppend() for details.
131801 */
131802 typedef struct StrBuffer StrBuffer;
131803 struct StrBuffer {
131804   char *z;                        /* Pointer to buffer containing string */
131805   int n;                          /* Length of z in bytes (excl. nul-term) */
131806   int nAlloc;                     /* Allocated size of buffer z in bytes */
131807 };
131808 
131809 
131810 /*
131811 ** This function is used to help iterate through a position-list. A position
131812 ** list is a list of unique integers, sorted from smallest to largest. Each
131813 ** element of the list is represented by an FTS3 varint that takes the value
131814 ** of the difference between the current element and the previous one plus
131815 ** two. For example, to store the position-list:
131816 **
131817 **     4 9 113
131818 **
131819 ** the three varints:
131820 **
131821 **     6 7 106
131822 **
131823 ** are encoded.
131824 **
131825 ** When this function is called, *pp points to the start of an element of
131826 ** the list. *piPos contains the value of the previous entry in the list.
131827 ** After it returns, *piPos contains the value of the next element of the
131828 ** list and *pp is advanced to the following varint.
131829 */
131830 static void fts3GetDeltaPosition(char **pp, int *piPos){
131831   int iVal;
131832   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
131833   *piPos += (iVal-2);
131834 }
131835 
131836 /*
131837 ** Helper function for fts3ExprIterate() (see below).
131838 */
131839 static int fts3ExprIterate2(
131840   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131841   int *piPhrase,                  /* Pointer to phrase counter */
131842   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131843   void *pCtx                      /* Second argument to pass to callback */
131844 ){
131845   int rc;                         /* Return code */
131846   int eType = pExpr->eType;       /* Type of expression node pExpr */
131847 
131848   if( eType!=FTSQUERY_PHRASE ){
131849     assert( pExpr->pLeft && pExpr->pRight );
131850     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
131851     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
131852       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
131853     }
131854   }else{
131855     rc = x(pExpr, *piPhrase, pCtx);
131856     (*piPhrase)++;
131857   }
131858   return rc;
131859 }
131860 
131861 /*
131862 ** Iterate through all phrase nodes in an FTS3 query, except those that
131863 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
131864 ** For each phrase node found, the supplied callback function is invoked.
131865 **
131866 ** If the callback function returns anything other than SQLITE_OK,
131867 ** the iteration is abandoned and the error code returned immediately.
131868 ** Otherwise, SQLITE_OK is returned after a callback has been made for
131869 ** all eligible phrase nodes.
131870 */
131871 static int fts3ExprIterate(
131872   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
131873   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
131874   void *pCtx                      /* Second argument to pass to callback */
131875 ){
131876   int iPhrase = 0;                /* Variable used as the phrase counter */
131877   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
131878 }
131879 
131880 /*
131881 ** This is an fts3ExprIterate() callback used while loading the doclists
131882 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
131883 ** fts3ExprLoadDoclists().
131884 */
131885 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
131886   int rc = SQLITE_OK;
131887   Fts3Phrase *pPhrase = pExpr->pPhrase;
131888   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
131889 
131890   UNUSED_PARAMETER(iPhrase);
131891 
131892   p->nPhrase++;
131893   p->nToken += pPhrase->nToken;
131894 
131895   return rc;
131896 }
131897 
131898 /*
131899 ** Load the doclists for each phrase in the query associated with FTS3 cursor
131900 ** pCsr.
131901 **
131902 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
131903 ** phrases in the expression (all phrases except those directly or
131904 ** indirectly descended from the right-hand-side of a NOT operator). If
131905 ** pnToken is not NULL, then it is set to the number of tokens in all
131906 ** matchable phrases of the expression.
131907 */
131908 static int fts3ExprLoadDoclists(
131909   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
131910   int *pnPhrase,                  /* OUT: Number of phrases in query */
131911   int *pnToken                    /* OUT: Number of tokens in query */
131912 ){
131913   int rc;                         /* Return Code */
131914   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
131915   sCtx.pCsr = pCsr;
131916   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
131917   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
131918   if( pnToken ) *pnToken = sCtx.nToken;
131919   return rc;
131920 }
131921 
131922 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
131923   (*(int *)ctx)++;
131924   UNUSED_PARAMETER(pExpr);
131925   UNUSED_PARAMETER(iPhrase);
131926   return SQLITE_OK;
131927 }
131928 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
131929   int nPhrase = 0;
131930   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
131931   return nPhrase;
131932 }
131933 
131934 /*
131935 ** Advance the position list iterator specified by the first two
131936 ** arguments so that it points to the first element with a value greater
131937 ** than or equal to parameter iNext.
131938 */
131939 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
131940   char *pIter = *ppIter;
131941   if( pIter ){
131942     int iIter = *piIter;
131943 
131944     while( iIter<iNext ){
131945       if( 0==(*pIter & 0xFE) ){
131946         iIter = -1;
131947         pIter = 0;
131948         break;
131949       }
131950       fts3GetDeltaPosition(&pIter, &iIter);
131951     }
131952 
131953     *piIter = iIter;
131954     *ppIter = pIter;
131955   }
131956 }
131957 
131958 /*
131959 ** Advance the snippet iterator to the next candidate snippet.
131960 */
131961 static int fts3SnippetNextCandidate(SnippetIter *pIter){
131962   int i;                          /* Loop counter */
131963 
131964   if( pIter->iCurrent<0 ){
131965     /* The SnippetIter object has just been initialized. The first snippet
131966     ** candidate always starts at offset 0 (even if this candidate has a
131967     ** score of 0.0).
131968     */
131969     pIter->iCurrent = 0;
131970 
131971     /* Advance the 'head' iterator of each phrase to the first offset that
131972     ** is greater than or equal to (iNext+nSnippet).
131973     */
131974     for(i=0; i<pIter->nPhrase; i++){
131975       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131976       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
131977     }
131978   }else{
131979     int iStart;
131980     int iEnd = 0x7FFFFFFF;
131981 
131982     for(i=0; i<pIter->nPhrase; i++){
131983       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131984       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
131985         iEnd = pPhrase->iHead;
131986       }
131987     }
131988     if( iEnd==0x7FFFFFFF ){
131989       return 1;
131990     }
131991 
131992     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
131993     for(i=0; i<pIter->nPhrase; i++){
131994       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
131995       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
131996       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
131997     }
131998   }
131999 
132000   return 0;
132001 }
132002 
132003 /*
132004 ** Retrieve information about the current candidate snippet of snippet
132005 ** iterator pIter.
132006 */
132007 static void fts3SnippetDetails(
132008   SnippetIter *pIter,             /* Snippet iterator */
132009   u64 mCovered,                   /* Bitmask of phrases already covered */
132010   int *piToken,                   /* OUT: First token of proposed snippet */
132011   int *piScore,                   /* OUT: "Score" for this snippet */
132012   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
132013   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
132014 ){
132015   int iStart = pIter->iCurrent;   /* First token of snippet */
132016   int iScore = 0;                 /* Score of this snippet */
132017   int i;                          /* Loop counter */
132018   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
132019   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
132020 
132021   for(i=0; i<pIter->nPhrase; i++){
132022     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132023     if( pPhrase->pTail ){
132024       char *pCsr = pPhrase->pTail;
132025       int iCsr = pPhrase->iTail;
132026 
132027       while( iCsr<(iStart+pIter->nSnippet) ){
132028         int j;
132029         u64 mPhrase = (u64)1 << i;
132030         u64 mPos = (u64)1 << (iCsr - iStart);
132031         assert( iCsr>=iStart );
132032         if( (mCover|mCovered)&mPhrase ){
132033           iScore++;
132034         }else{
132035           iScore += 1000;
132036         }
132037         mCover |= mPhrase;
132038 
132039         for(j=0; j<pPhrase->nToken; j++){
132040           mHighlight |= (mPos>>j);
132041         }
132042 
132043         if( 0==(*pCsr & 0x0FE) ) break;
132044         fts3GetDeltaPosition(&pCsr, &iCsr);
132045       }
132046     }
132047   }
132048 
132049   /* Set the output variables before returning. */
132050   *piToken = iStart;
132051   *piScore = iScore;
132052   *pmCover = mCover;
132053   *pmHighlight = mHighlight;
132054 }
132055 
132056 /*
132057 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
132058 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
132059 */
132060 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
132061   SnippetIter *p = (SnippetIter *)ctx;
132062   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
132063   char *pCsr;
132064   int rc;
132065 
132066   pPhrase->nToken = pExpr->pPhrase->nToken;
132067   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
132068   assert( rc==SQLITE_OK || pCsr==0 );
132069   if( pCsr ){
132070     int iFirst = 0;
132071     pPhrase->pList = pCsr;
132072     fts3GetDeltaPosition(&pCsr, &iFirst);
132073     assert( iFirst>=0 );
132074     pPhrase->pHead = pCsr;
132075     pPhrase->pTail = pCsr;
132076     pPhrase->iHead = iFirst;
132077     pPhrase->iTail = iFirst;
132078   }else{
132079     assert( rc!=SQLITE_OK || (
132080        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
132081     ));
132082   }
132083 
132084   return rc;
132085 }
132086 
132087 /*
132088 ** Select the fragment of text consisting of nFragment contiguous tokens
132089 ** from column iCol that represent the "best" snippet. The best snippet
132090 ** is the snippet with the highest score, where scores are calculated
132091 ** by adding:
132092 **
132093 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
132094 **
132095 **   (b) +1000 points for the first occurrence of each matchable phrase in
132096 **       the snippet for which the corresponding mCovered bit is not set.
132097 **
132098 ** The selected snippet parameters are stored in structure *pFragment before
132099 ** returning. The score of the selected snippet is stored in *piScore
132100 ** before returning.
132101 */
132102 static int fts3BestSnippet(
132103   int nSnippet,                   /* Desired snippet length */
132104   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
132105   int iCol,                       /* Index of column to create snippet from */
132106   u64 mCovered,                   /* Mask of phrases already covered */
132107   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
132108   SnippetFragment *pFragment,     /* OUT: Best snippet found */
132109   int *piScore                    /* OUT: Score of snippet pFragment */
132110 ){
132111   int rc;                         /* Return Code */
132112   int nList;                      /* Number of phrases in expression */
132113   SnippetIter sIter;              /* Iterates through snippet candidates */
132114   int nByte;                      /* Number of bytes of space to allocate */
132115   int iBestScore = -1;            /* Best snippet score found so far */
132116   int i;                          /* Loop counter */
132117 
132118   memset(&sIter, 0, sizeof(sIter));
132119 
132120   /* Iterate through the phrases in the expression to count them. The same
132121   ** callback makes sure the doclists are loaded for each phrase.
132122   */
132123   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
132124   if( rc!=SQLITE_OK ){
132125     return rc;
132126   }
132127 
132128   /* Now that it is known how many phrases there are, allocate and zero
132129   ** the required space using malloc().
132130   */
132131   nByte = sizeof(SnippetPhrase) * nList;
132132   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
132133   if( !sIter.aPhrase ){
132134     return SQLITE_NOMEM;
132135   }
132136   memset(sIter.aPhrase, 0, nByte);
132137 
132138   /* Initialize the contents of the SnippetIter object. Then iterate through
132139   ** the set of phrases in the expression to populate the aPhrase[] array.
132140   */
132141   sIter.pCsr = pCsr;
132142   sIter.iCol = iCol;
132143   sIter.nSnippet = nSnippet;
132144   sIter.nPhrase = nList;
132145   sIter.iCurrent = -1;
132146   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
132147 
132148   /* Set the *pmSeen output variable. */
132149   for(i=0; i<nList; i++){
132150     if( sIter.aPhrase[i].pHead ){
132151       *pmSeen |= (u64)1 << i;
132152     }
132153   }
132154 
132155   /* Loop through all candidate snippets. Store the best snippet in
132156   ** *pFragment. Store its associated 'score' in iBestScore.
132157   */
132158   pFragment->iCol = iCol;
132159   while( !fts3SnippetNextCandidate(&sIter) ){
132160     int iPos;
132161     int iScore;
132162     u64 mCover;
132163     u64 mHighlight;
132164     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
132165     assert( iScore>=0 );
132166     if( iScore>iBestScore ){
132167       pFragment->iPos = iPos;
132168       pFragment->hlmask = mHighlight;
132169       pFragment->covered = mCover;
132170       iBestScore = iScore;
132171     }
132172   }
132173 
132174   sqlite3_free(sIter.aPhrase);
132175   *piScore = iBestScore;
132176   return SQLITE_OK;
132177 }
132178 
132179 
132180 /*
132181 ** Append a string to the string-buffer passed as the first argument.
132182 **
132183 ** If nAppend is negative, then the length of the string zAppend is
132184 ** determined using strlen().
132185 */
132186 static int fts3StringAppend(
132187   StrBuffer *pStr,                /* Buffer to append to */
132188   const char *zAppend,            /* Pointer to data to append to buffer */
132189   int nAppend                     /* Size of zAppend in bytes (or -1) */
132190 ){
132191   if( nAppend<0 ){
132192     nAppend = (int)strlen(zAppend);
132193   }
132194 
132195   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
132196   ** to grow the buffer until so that it is big enough to accomadate the
132197   ** appended data.
132198   */
132199   if( pStr->n+nAppend+1>=pStr->nAlloc ){
132200     int nAlloc = pStr->nAlloc+nAppend+100;
132201     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
132202     if( !zNew ){
132203       return SQLITE_NOMEM;
132204     }
132205     pStr->z = zNew;
132206     pStr->nAlloc = nAlloc;
132207   }
132208 
132209   /* Append the data to the string buffer. */
132210   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
132211   pStr->n += nAppend;
132212   pStr->z[pStr->n] = '\0';
132213 
132214   return SQLITE_OK;
132215 }
132216 
132217 /*
132218 ** The fts3BestSnippet() function often selects snippets that end with a
132219 ** query term. That is, the final term of the snippet is always a term
132220 ** that requires highlighting. For example, if 'X' is a highlighted term
132221 ** and '.' is a non-highlighted term, BestSnippet() may select:
132222 **
132223 **     ........X.....X
132224 **
132225 ** This function "shifts" the beginning of the snippet forward in the
132226 ** document so that there are approximately the same number of
132227 ** non-highlighted terms to the right of the final highlighted term as there
132228 ** are to the left of the first highlighted term. For example, to this:
132229 **
132230 **     ....X.....X....
132231 **
132232 ** This is done as part of extracting the snippet text, not when selecting
132233 ** the snippet. Snippet selection is done based on doclists only, so there
132234 ** is no way for fts3BestSnippet() to know whether or not the document
132235 ** actually contains terms that follow the final highlighted term.
132236 */
132237 static int fts3SnippetShift(
132238   Fts3Table *pTab,                /* FTS3 table snippet comes from */
132239   int iLangid,                    /* Language id to use in tokenizing */
132240   int nSnippet,                   /* Number of tokens desired for snippet */
132241   const char *zDoc,               /* Document text to extract snippet from */
132242   int nDoc,                       /* Size of buffer zDoc in bytes */
132243   int *piPos,                     /* IN/OUT: First token of snippet */
132244   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
132245 ){
132246   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
132247 
132248   if( hlmask ){
132249     int nLeft;                    /* Tokens to the left of first highlight */
132250     int nRight;                   /* Tokens to the right of last highlight */
132251     int nDesired;                 /* Ideal number of tokens to shift forward */
132252 
132253     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
132254     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
132255     nDesired = (nLeft-nRight)/2;
132256 
132257     /* Ideally, the start of the snippet should be pushed forward in the
132258     ** document nDesired tokens. This block checks if there are actually
132259     ** nDesired tokens to the right of the snippet. If so, *piPos and
132260     ** *pHlMask are updated to shift the snippet nDesired tokens to the
132261     ** right. Otherwise, the snippet is shifted by the number of tokens
132262     ** available.
132263     */
132264     if( nDesired>0 ){
132265       int nShift;                 /* Number of tokens to shift snippet by */
132266       int iCurrent = 0;           /* Token counter */
132267       int rc;                     /* Return Code */
132268       sqlite3_tokenizer_module *pMod;
132269       sqlite3_tokenizer_cursor *pC;
132270       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
132271 
132272       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
132273       ** or more tokens in zDoc/nDoc.
132274       */
132275       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
132276       if( rc!=SQLITE_OK ){
132277         return rc;
132278       }
132279       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
132280         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
132281         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
132282       }
132283       pMod->xClose(pC);
132284       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
132285 
132286       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
132287       assert( nShift<=nDesired );
132288       if( nShift>0 ){
132289         *piPos += nShift;
132290         *pHlmask = hlmask >> nShift;
132291       }
132292     }
132293   }
132294   return SQLITE_OK;
132295 }
132296 
132297 /*
132298 ** Extract the snippet text for fragment pFragment from cursor pCsr and
132299 ** append it to string buffer pOut.
132300 */
132301 static int fts3SnippetText(
132302   Fts3Cursor *pCsr,               /* FTS3 Cursor */
132303   SnippetFragment *pFragment,     /* Snippet to extract */
132304   int iFragment,                  /* Fragment number */
132305   int isLast,                     /* True for final fragment in snippet */
132306   int nSnippet,                   /* Number of tokens in extracted snippet */
132307   const char *zOpen,              /* String inserted before highlighted term */
132308   const char *zClose,             /* String inserted after highlighted term */
132309   const char *zEllipsis,          /* String inserted between snippets */
132310   StrBuffer *pOut                 /* Write output here */
132311 ){
132312   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132313   int rc;                         /* Return code */
132314   const char *zDoc;               /* Document text to extract snippet from */
132315   int nDoc;                       /* Size of zDoc in bytes */
132316   int iCurrent = 0;               /* Current token number of document */
132317   int iEnd = 0;                   /* Byte offset of end of current token */
132318   int isShiftDone = 0;            /* True after snippet is shifted */
132319   int iPos = pFragment->iPos;     /* First token of snippet */
132320   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
132321   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
132322   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
132323   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
132324 
132325   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
132326   if( zDoc==0 ){
132327     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
132328       return SQLITE_NOMEM;
132329     }
132330     return SQLITE_OK;
132331   }
132332   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
132333 
132334   /* Open a token cursor on the document. */
132335   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
132336   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
132337   if( rc!=SQLITE_OK ){
132338     return rc;
132339   }
132340 
132341   while( rc==SQLITE_OK ){
132342     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
132343     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
132344     int iBegin = 0;               /* Offset in zDoc of start of token */
132345     int iFin = 0;                 /* Offset in zDoc of end of token */
132346     int isHighlight = 0;          /* True for highlighted terms */
132347 
132348     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
132349     ** in the FTS code the variable that the third argument to xNext points to
132350     ** is initialized to zero before the first (*but not necessarily
132351     ** subsequent*) call to xNext(). This is done for a particular application
132352     ** that needs to know whether or not the tokenizer is being used for
132353     ** snippet generation or for some other purpose.
132354     **
132355     ** Extreme care is required when writing code to depend on this
132356     ** initialization. It is not a documented part of the tokenizer interface.
132357     ** If a tokenizer is used directly by any code outside of FTS, this
132358     ** convention might not be respected.  */
132359     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
132360     if( rc!=SQLITE_OK ){
132361       if( rc==SQLITE_DONE ){
132362         /* Special case - the last token of the snippet is also the last token
132363         ** of the column. Append any punctuation that occurred between the end
132364         ** of the previous token and the end of the document to the output.
132365         ** Then break out of the loop. */
132366         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
132367       }
132368       break;
132369     }
132370     if( iCurrent<iPos ){ continue; }
132371 
132372     if( !isShiftDone ){
132373       int n = nDoc - iBegin;
132374       rc = fts3SnippetShift(
132375           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
132376       );
132377       isShiftDone = 1;
132378 
132379       /* Now that the shift has been done, check if the initial "..." are
132380       ** required. They are required if (a) this is not the first fragment,
132381       ** or (b) this fragment does not begin at position 0 of its column.
132382       */
132383       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
132384         rc = fts3StringAppend(pOut, zEllipsis, -1);
132385       }
132386       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
132387     }
132388 
132389     if( iCurrent>=(iPos+nSnippet) ){
132390       if( isLast ){
132391         rc = fts3StringAppend(pOut, zEllipsis, -1);
132392       }
132393       break;
132394     }
132395 
132396     /* Set isHighlight to true if this term should be highlighted. */
132397     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
132398 
132399     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
132400     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
132401     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
132402     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
132403 
132404     iEnd = iFin;
132405   }
132406 
132407   pMod->xClose(pC);
132408   return rc;
132409 }
132410 
132411 
132412 /*
132413 ** This function is used to count the entries in a column-list (a
132414 ** delta-encoded list of term offsets within a single column of a single
132415 ** row). When this function is called, *ppCollist should point to the
132416 ** beginning of the first varint in the column-list (the varint that
132417 ** contains the position of the first matching term in the column data).
132418 ** Before returning, *ppCollist is set to point to the first byte after
132419 ** the last varint in the column-list (either the 0x00 signifying the end
132420 ** of the position-list, or the 0x01 that precedes the column number of
132421 ** the next column in the position-list).
132422 **
132423 ** The number of elements in the column-list is returned.
132424 */
132425 static int fts3ColumnlistCount(char **ppCollist){
132426   char *pEnd = *ppCollist;
132427   char c = 0;
132428   int nEntry = 0;
132429 
132430   /* A column-list is terminated by either a 0x01 or 0x00. */
132431   while( 0xFE & (*pEnd | c) ){
132432     c = *pEnd++ & 0x80;
132433     if( !c ) nEntry++;
132434   }
132435 
132436   *ppCollist = pEnd;
132437   return nEntry;
132438 }
132439 
132440 /*
132441 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
132442 ** for a single query.
132443 **
132444 ** fts3ExprIterate() callback to load the 'global' elements of a
132445 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
132446 ** of the matchinfo array that are constant for all rows returned by the
132447 ** current query.
132448 **
132449 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
132450 ** function populates Matchinfo.aMatchinfo[] as follows:
132451 **
132452 **   for(iCol=0; iCol<nCol; iCol++){
132453 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
132454 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
132455 **   }
132456 **
132457 ** where X is the number of matches for phrase iPhrase is column iCol of all
132458 ** rows of the table. Y is the number of rows for which column iCol contains
132459 ** at least one instance of phrase iPhrase.
132460 **
132461 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
132462 ** Y values are set to nDoc, where nDoc is the number of documents in the
132463 ** file system. This is done because the full-text index doclist is required
132464 ** to calculate these values properly, and the full-text index doclist is
132465 ** not available for deferred tokens.
132466 */
132467 static int fts3ExprGlobalHitsCb(
132468   Fts3Expr *pExpr,                /* Phrase expression node */
132469   int iPhrase,                    /* Phrase number (numbered from zero) */
132470   void *pCtx                      /* Pointer to MatchInfo structure */
132471 ){
132472   MatchInfo *p = (MatchInfo *)pCtx;
132473   return sqlite3Fts3EvalPhraseStats(
132474       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
132475   );
132476 }
132477 
132478 /*
132479 ** fts3ExprIterate() callback used to collect the "local" part of the
132480 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
132481 ** array that are different for each row returned by the query.
132482 */
132483 static int fts3ExprLocalHitsCb(
132484   Fts3Expr *pExpr,                /* Phrase expression node */
132485   int iPhrase,                    /* Phrase number */
132486   void *pCtx                      /* Pointer to MatchInfo structure */
132487 ){
132488   int rc = SQLITE_OK;
132489   MatchInfo *p = (MatchInfo *)pCtx;
132490   int iStart = iPhrase * p->nCol * 3;
132491   int i;
132492 
132493   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
132494     char *pCsr;
132495     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
132496     if( pCsr ){
132497       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
132498     }else{
132499       p->aMatchinfo[iStart+i*3] = 0;
132500     }
132501   }
132502 
132503   return rc;
132504 }
132505 
132506 static int fts3MatchinfoCheck(
132507   Fts3Table *pTab,
132508   char cArg,
132509   char **pzErr
132510 ){
132511   if( (cArg==FTS3_MATCHINFO_NPHRASE)
132512    || (cArg==FTS3_MATCHINFO_NCOL)
132513    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
132514    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
132515    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
132516    || (cArg==FTS3_MATCHINFO_LCS)
132517    || (cArg==FTS3_MATCHINFO_HITS)
132518   ){
132519     return SQLITE_OK;
132520   }
132521   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
132522   return SQLITE_ERROR;
132523 }
132524 
132525 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
132526   int nVal;                       /* Number of integers output by cArg */
132527 
132528   switch( cArg ){
132529     case FTS3_MATCHINFO_NDOC:
132530     case FTS3_MATCHINFO_NPHRASE:
132531     case FTS3_MATCHINFO_NCOL:
132532       nVal = 1;
132533       break;
132534 
132535     case FTS3_MATCHINFO_AVGLENGTH:
132536     case FTS3_MATCHINFO_LENGTH:
132537     case FTS3_MATCHINFO_LCS:
132538       nVal = pInfo->nCol;
132539       break;
132540 
132541     default:
132542       assert( cArg==FTS3_MATCHINFO_HITS );
132543       nVal = pInfo->nCol * pInfo->nPhrase * 3;
132544       break;
132545   }
132546 
132547   return nVal;
132548 }
132549 
132550 static int fts3MatchinfoSelectDoctotal(
132551   Fts3Table *pTab,
132552   sqlite3_stmt **ppStmt,
132553   sqlite3_int64 *pnDoc,
132554   const char **paLen
132555 ){
132556   sqlite3_stmt *pStmt;
132557   const char *a;
132558   sqlite3_int64 nDoc;
132559 
132560   if( !*ppStmt ){
132561     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
132562     if( rc!=SQLITE_OK ) return rc;
132563   }
132564   pStmt = *ppStmt;
132565   assert( sqlite3_data_count(pStmt)==1 );
132566 
132567   a = sqlite3_column_blob(pStmt, 0);
132568   a += sqlite3Fts3GetVarint(a, &nDoc);
132569   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
132570   *pnDoc = (u32)nDoc;
132571 
132572   if( paLen ) *paLen = a;
132573   return SQLITE_OK;
132574 }
132575 
132576 /*
132577 ** An instance of the following structure is used to store state while
132578 ** iterating through a multi-column position-list corresponding to the
132579 ** hits for a single phrase on a single row in order to calculate the
132580 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
132581 */
132582 typedef struct LcsIterator LcsIterator;
132583 struct LcsIterator {
132584   Fts3Expr *pExpr;                /* Pointer to phrase expression */
132585   int iPosOffset;                 /* Tokens count up to end of this phrase */
132586   char *pRead;                    /* Cursor used to iterate through aDoclist */
132587   int iPos;                       /* Current position */
132588 };
132589 
132590 /*
132591 ** If LcsIterator.iCol is set to the following value, the iterator has
132592 ** finished iterating through all offsets for all columns.
132593 */
132594 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
132595 
132596 static int fts3MatchinfoLcsCb(
132597   Fts3Expr *pExpr,                /* Phrase expression node */
132598   int iPhrase,                    /* Phrase number (numbered from zero) */
132599   void *pCtx                      /* Pointer to MatchInfo structure */
132600 ){
132601   LcsIterator *aIter = (LcsIterator *)pCtx;
132602   aIter[iPhrase].pExpr = pExpr;
132603   return SQLITE_OK;
132604 }
132605 
132606 /*
132607 ** Advance the iterator passed as an argument to the next position. Return
132608 ** 1 if the iterator is at EOF or if it now points to the start of the
132609 ** position list for the next column.
132610 */
132611 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
132612   char *pRead = pIter->pRead;
132613   sqlite3_int64 iRead;
132614   int rc = 0;
132615 
132616   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
132617   if( iRead==0 || iRead==1 ){
132618     pRead = 0;
132619     rc = 1;
132620   }else{
132621     pIter->iPos += (int)(iRead-2);
132622   }
132623 
132624   pIter->pRead = pRead;
132625   return rc;
132626 }
132627 
132628 /*
132629 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
132630 **
132631 ** If the call is successful, the longest-common-substring lengths for each
132632 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
132633 ** array before returning. SQLITE_OK is returned in this case.
132634 **
132635 ** Otherwise, if an error occurs, an SQLite error code is returned and the
132636 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
132637 ** undefined.
132638 */
132639 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
132640   LcsIterator *aIter;
132641   int i;
132642   int iCol;
132643   int nToken = 0;
132644 
132645   /* Allocate and populate the array of LcsIterator objects. The array
132646   ** contains one element for each matchable phrase in the query.
132647   **/
132648   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
132649   if( !aIter ) return SQLITE_NOMEM;
132650   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
132651   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
132652 
132653   for(i=0; i<pInfo->nPhrase; i++){
132654     LcsIterator *pIter = &aIter[i];
132655     nToken -= pIter->pExpr->pPhrase->nToken;
132656     pIter->iPosOffset = nToken;
132657   }
132658 
132659   for(iCol=0; iCol<pInfo->nCol; iCol++){
132660     int nLcs = 0;                 /* LCS value for this column */
132661     int nLive = 0;                /* Number of iterators in aIter not at EOF */
132662 
132663     for(i=0; i<pInfo->nPhrase; i++){
132664       int rc;
132665       LcsIterator *pIt = &aIter[i];
132666       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
132667       if( rc!=SQLITE_OK ) return rc;
132668       if( pIt->pRead ){
132669         pIt->iPos = pIt->iPosOffset;
132670         fts3LcsIteratorAdvance(&aIter[i]);
132671         nLive++;
132672       }
132673     }
132674 
132675     while( nLive>0 ){
132676       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
132677       int nThisLcs = 0;           /* LCS for the current iterator positions */
132678 
132679       for(i=0; i<pInfo->nPhrase; i++){
132680         LcsIterator *pIter = &aIter[i];
132681         if( pIter->pRead==0 ){
132682           /* This iterator is already at EOF for this column. */
132683           nThisLcs = 0;
132684         }else{
132685           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
132686             pAdv = pIter;
132687           }
132688           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
132689             nThisLcs++;
132690           }else{
132691             nThisLcs = 1;
132692           }
132693           if( nThisLcs>nLcs ) nLcs = nThisLcs;
132694         }
132695       }
132696       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
132697     }
132698 
132699     pInfo->aMatchinfo[iCol] = nLcs;
132700   }
132701 
132702   sqlite3_free(aIter);
132703   return SQLITE_OK;
132704 }
132705 
132706 /*
132707 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
132708 ** be returned by the matchinfo() function. Argument zArg contains the
132709 ** format string passed as the second argument to matchinfo (or the
132710 ** default value "pcx" if no second argument was specified). The format
132711 ** string has already been validated and the pInfo->aMatchinfo[] array
132712 ** is guaranteed to be large enough for the output.
132713 **
132714 ** If bGlobal is true, then populate all fields of the matchinfo() output.
132715 ** If it is false, then assume that those fields that do not change between
132716 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
132717 ** have already been populated.
132718 **
132719 ** Return SQLITE_OK if successful, or an SQLite error code if an error
132720 ** occurs. If a value other than SQLITE_OK is returned, the state the
132721 ** pInfo->aMatchinfo[] buffer is left in is undefined.
132722 */
132723 static int fts3MatchinfoValues(
132724   Fts3Cursor *pCsr,               /* FTS3 cursor object */
132725   int bGlobal,                    /* True to grab the global stats */
132726   MatchInfo *pInfo,               /* Matchinfo context object */
132727   const char *zArg                /* Matchinfo format string */
132728 ){
132729   int rc = SQLITE_OK;
132730   int i;
132731   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132732   sqlite3_stmt *pSelect = 0;
132733 
132734   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
132735 
132736     switch( zArg[i] ){
132737       case FTS3_MATCHINFO_NPHRASE:
132738         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
132739         break;
132740 
132741       case FTS3_MATCHINFO_NCOL:
132742         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
132743         break;
132744 
132745       case FTS3_MATCHINFO_NDOC:
132746         if( bGlobal ){
132747           sqlite3_int64 nDoc = 0;
132748           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
132749           pInfo->aMatchinfo[0] = (u32)nDoc;
132750         }
132751         break;
132752 
132753       case FTS3_MATCHINFO_AVGLENGTH:
132754         if( bGlobal ){
132755           sqlite3_int64 nDoc;     /* Number of rows in table */
132756           const char *a;          /* Aggregate column length array */
132757 
132758           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
132759           if( rc==SQLITE_OK ){
132760             int iCol;
132761             for(iCol=0; iCol<pInfo->nCol; iCol++){
132762               u32 iVal;
132763               sqlite3_int64 nToken;
132764               a += sqlite3Fts3GetVarint(a, &nToken);
132765               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
132766               pInfo->aMatchinfo[iCol] = iVal;
132767             }
132768           }
132769         }
132770         break;
132771 
132772       case FTS3_MATCHINFO_LENGTH: {
132773         sqlite3_stmt *pSelectDocsize = 0;
132774         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
132775         if( rc==SQLITE_OK ){
132776           int iCol;
132777           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
132778           for(iCol=0; iCol<pInfo->nCol; iCol++){
132779             sqlite3_int64 nToken;
132780             a += sqlite3Fts3GetVarint(a, &nToken);
132781             pInfo->aMatchinfo[iCol] = (u32)nToken;
132782           }
132783         }
132784         sqlite3_reset(pSelectDocsize);
132785         break;
132786       }
132787 
132788       case FTS3_MATCHINFO_LCS:
132789         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132790         if( rc==SQLITE_OK ){
132791           rc = fts3MatchinfoLcs(pCsr, pInfo);
132792         }
132793         break;
132794 
132795       default: {
132796         Fts3Expr *pExpr;
132797         assert( zArg[i]==FTS3_MATCHINFO_HITS );
132798         pExpr = pCsr->pExpr;
132799         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
132800         if( rc!=SQLITE_OK ) break;
132801         if( bGlobal ){
132802           if( pCsr->pDeferred ){
132803             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
132804             if( rc!=SQLITE_OK ) break;
132805           }
132806           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
132807           if( rc!=SQLITE_OK ) break;
132808         }
132809         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
132810         break;
132811       }
132812     }
132813 
132814     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
132815   }
132816 
132817   sqlite3_reset(pSelect);
132818   return rc;
132819 }
132820 
132821 
132822 /*
132823 ** Populate pCsr->aMatchinfo[] with data for the current row. The
132824 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
132825 */
132826 static int fts3GetMatchinfo(
132827   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
132828   const char *zArg                /* Second argument to matchinfo() function */
132829 ){
132830   MatchInfo sInfo;
132831   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132832   int rc = SQLITE_OK;
132833   int bGlobal = 0;                /* Collect 'global' stats as well as local */
132834 
132835   memset(&sInfo, 0, sizeof(MatchInfo));
132836   sInfo.pCursor = pCsr;
132837   sInfo.nCol = pTab->nColumn;
132838 
132839   /* If there is cached matchinfo() data, but the format string for the
132840   ** cache does not match the format string for this request, discard
132841   ** the cached data. */
132842   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
132843     assert( pCsr->aMatchinfo );
132844     sqlite3_free(pCsr->aMatchinfo);
132845     pCsr->zMatchinfo = 0;
132846     pCsr->aMatchinfo = 0;
132847   }
132848 
132849   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
132850   ** matchinfo function has been called for this query. In this case
132851   ** allocate the array used to accumulate the matchinfo data and
132852   ** initialize those elements that are constant for every row.
132853   */
132854   if( pCsr->aMatchinfo==0 ){
132855     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
132856     int nArg;                     /* Bytes in zArg */
132857     int i;                        /* Used to iterate through zArg */
132858 
132859     /* Determine the number of phrases in the query */
132860     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
132861     sInfo.nPhrase = pCsr->nPhrase;
132862 
132863     /* Determine the number of integers in the buffer returned by this call. */
132864     for(i=0; zArg[i]; i++){
132865       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
132866     }
132867 
132868     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
132869     nArg = (int)strlen(zArg);
132870     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
132871     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
132872 
132873     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
132874     pCsr->nMatchinfo = nMatchinfo;
132875     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
132876     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
132877     pCsr->isMatchinfoNeeded = 1;
132878     bGlobal = 1;
132879   }
132880 
132881   sInfo.aMatchinfo = pCsr->aMatchinfo;
132882   sInfo.nPhrase = pCsr->nPhrase;
132883   if( pCsr->isMatchinfoNeeded ){
132884     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
132885     pCsr->isMatchinfoNeeded = 0;
132886   }
132887 
132888   return rc;
132889 }
132890 
132891 /*
132892 ** Implementation of snippet() function.
132893 */
132894 SQLITE_PRIVATE void sqlite3Fts3Snippet(
132895   sqlite3_context *pCtx,          /* SQLite function call context */
132896   Fts3Cursor *pCsr,               /* Cursor object */
132897   const char *zStart,             /* Snippet start text - "<b>" */
132898   const char *zEnd,               /* Snippet end text - "</b>" */
132899   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
132900   int iCol,                       /* Extract snippet from this column */
132901   int nToken                      /* Approximate number of tokens in snippet */
132902 ){
132903   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
132904   int rc = SQLITE_OK;
132905   int i;
132906   StrBuffer res = {0, 0, 0};
132907 
132908   /* The returned text includes up to four fragments of text extracted from
132909   ** the data in the current row. The first iteration of the for(...) loop
132910   ** below attempts to locate a single fragment of text nToken tokens in
132911   ** size that contains at least one instance of all phrases in the query
132912   ** expression that appear in the current row. If such a fragment of text
132913   ** cannot be found, the second iteration of the loop attempts to locate
132914   ** a pair of fragments, and so on.
132915   */
132916   int nSnippet = 0;               /* Number of fragments in this snippet */
132917   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
132918   int nFToken = -1;               /* Number of tokens in each fragment */
132919 
132920   if( !pCsr->pExpr ){
132921     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
132922     return;
132923   }
132924 
132925   for(nSnippet=1; 1; nSnippet++){
132926 
132927     int iSnip;                    /* Loop counter 0..nSnippet-1 */
132928     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
132929     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
132930 
132931     if( nToken>=0 ){
132932       nFToken = (nToken+nSnippet-1) / nSnippet;
132933     }else{
132934       nFToken = -1 * nToken;
132935     }
132936 
132937     for(iSnip=0; iSnip<nSnippet; iSnip++){
132938       int iBestScore = -1;        /* Best score of columns checked so far */
132939       int iRead;                  /* Used to iterate through columns */
132940       SnippetFragment *pFragment = &aSnippet[iSnip];
132941 
132942       memset(pFragment, 0, sizeof(*pFragment));
132943 
132944       /* Loop through all columns of the table being considered for snippets.
132945       ** If the iCol argument to this function was negative, this means all
132946       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
132947       */
132948       for(iRead=0; iRead<pTab->nColumn; iRead++){
132949         SnippetFragment sF = {0, 0, 0, 0};
132950         int iS;
132951         if( iCol>=0 && iRead!=iCol ) continue;
132952 
132953         /* Find the best snippet of nFToken tokens in column iRead. */
132954         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
132955         if( rc!=SQLITE_OK ){
132956           goto snippet_out;
132957         }
132958         if( iS>iBestScore ){
132959           *pFragment = sF;
132960           iBestScore = iS;
132961         }
132962       }
132963 
132964       mCovered |= pFragment->covered;
132965     }
132966 
132967     /* If all query phrases seen by fts3BestSnippet() are present in at least
132968     ** one of the nSnippet snippet fragments, break out of the loop.
132969     */
132970     assert( (mCovered&mSeen)==mCovered );
132971     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
132972   }
132973 
132974   assert( nFToken>0 );
132975 
132976   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
132977     rc = fts3SnippetText(pCsr, &aSnippet[i],
132978         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
132979     );
132980   }
132981 
132982  snippet_out:
132983   sqlite3Fts3SegmentsClose(pTab);
132984   if( rc!=SQLITE_OK ){
132985     sqlite3_result_error_code(pCtx, rc);
132986     sqlite3_free(res.z);
132987   }else{
132988     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
132989   }
132990 }
132991 
132992 
132993 typedef struct TermOffset TermOffset;
132994 typedef struct TermOffsetCtx TermOffsetCtx;
132995 
132996 struct TermOffset {
132997   char *pList;                    /* Position-list */
132998   int iPos;                       /* Position just read from pList */
132999   int iOff;                       /* Offset of this term from read positions */
133000 };
133001 
133002 struct TermOffsetCtx {
133003   Fts3Cursor *pCsr;
133004   int iCol;                       /* Column of table to populate aTerm for */
133005   int iTerm;
133006   sqlite3_int64 iDocid;
133007   TermOffset *aTerm;
133008 };
133009 
133010 /*
133011 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
133012 */
133013 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
133014   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
133015   int nTerm;                      /* Number of tokens in phrase */
133016   int iTerm;                      /* For looping through nTerm phrase terms */
133017   char *pList;                    /* Pointer to position list for phrase */
133018   int iPos = 0;                   /* First position in position-list */
133019   int rc;
133020 
133021   UNUSED_PARAMETER(iPhrase);
133022   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
133023   nTerm = pExpr->pPhrase->nToken;
133024   if( pList ){
133025     fts3GetDeltaPosition(&pList, &iPos);
133026     assert( iPos>=0 );
133027   }
133028 
133029   for(iTerm=0; iTerm<nTerm; iTerm++){
133030     TermOffset *pT = &p->aTerm[p->iTerm++];
133031     pT->iOff = nTerm-iTerm-1;
133032     pT->pList = pList;
133033     pT->iPos = iPos;
133034   }
133035 
133036   return rc;
133037 }
133038 
133039 /*
133040 ** Implementation of offsets() function.
133041 */
133042 SQLITE_PRIVATE void sqlite3Fts3Offsets(
133043   sqlite3_context *pCtx,          /* SQLite function call context */
133044   Fts3Cursor *pCsr                /* Cursor object */
133045 ){
133046   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133047   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
133048   int rc;                         /* Return Code */
133049   int nToken;                     /* Number of tokens in query */
133050   int iCol;                       /* Column currently being processed */
133051   StrBuffer res = {0, 0, 0};      /* Result string */
133052   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
133053 
133054   if( !pCsr->pExpr ){
133055     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
133056     return;
133057   }
133058 
133059   memset(&sCtx, 0, sizeof(sCtx));
133060   assert( pCsr->isRequireSeek==0 );
133061 
133062   /* Count the number of terms in the query */
133063   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
133064   if( rc!=SQLITE_OK ) goto offsets_out;
133065 
133066   /* Allocate the array of TermOffset iterators. */
133067   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
133068   if( 0==sCtx.aTerm ){
133069     rc = SQLITE_NOMEM;
133070     goto offsets_out;
133071   }
133072   sCtx.iDocid = pCsr->iPrevId;
133073   sCtx.pCsr = pCsr;
133074 
133075   /* Loop through the table columns, appending offset information to
133076   ** string-buffer res for each column.
133077   */
133078   for(iCol=0; iCol<pTab->nColumn; iCol++){
133079     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
133080     const char *ZDUMMY;           /* Dummy argument used with xNext() */
133081     int NDUMMY = 0;               /* Dummy argument used with xNext() */
133082     int iStart = 0;
133083     int iEnd = 0;
133084     int iCurrent = 0;
133085     const char *zDoc;
133086     int nDoc;
133087 
133088     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
133089     ** no way that this operation can fail, so the return code from
133090     ** fts3ExprIterate() can be discarded.
133091     */
133092     sCtx.iCol = iCol;
133093     sCtx.iTerm = 0;
133094     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
133095 
133096     /* Retreive the text stored in column iCol. If an SQL NULL is stored
133097     ** in column iCol, jump immediately to the next iteration of the loop.
133098     ** If an OOM occurs while retrieving the data (this can happen if SQLite
133099     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
133100     ** to the caller.
133101     */
133102     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
133103     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
133104     if( zDoc==0 ){
133105       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
133106         continue;
133107       }
133108       rc = SQLITE_NOMEM;
133109       goto offsets_out;
133110     }
133111 
133112     /* Initialize a tokenizer iterator to iterate through column iCol. */
133113     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
133114         zDoc, nDoc, &pC
133115     );
133116     if( rc!=SQLITE_OK ) goto offsets_out;
133117 
133118     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
133119     while( rc==SQLITE_OK ){
133120       int i;                      /* Used to loop through terms */
133121       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
133122       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
133123 
133124       for(i=0; i<nToken; i++){
133125         TermOffset *pT = &sCtx.aTerm[i];
133126         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
133127           iMinPos = pT->iPos-pT->iOff;
133128           pTerm = pT;
133129         }
133130       }
133131 
133132       if( !pTerm ){
133133         /* All offsets for this column have been gathered. */
133134         rc = SQLITE_DONE;
133135       }else{
133136         assert( iCurrent<=iMinPos );
133137         if( 0==(0xFE&*pTerm->pList) ){
133138           pTerm->pList = 0;
133139         }else{
133140           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
133141         }
133142         while( rc==SQLITE_OK && iCurrent<iMinPos ){
133143           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
133144         }
133145         if( rc==SQLITE_OK ){
133146           char aBuffer[64];
133147           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
133148               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
133149           );
133150           rc = fts3StringAppend(&res, aBuffer, -1);
133151         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
133152           rc = FTS_CORRUPT_VTAB;
133153         }
133154       }
133155     }
133156     if( rc==SQLITE_DONE ){
133157       rc = SQLITE_OK;
133158     }
133159 
133160     pMod->xClose(pC);
133161     if( rc!=SQLITE_OK ) goto offsets_out;
133162   }
133163 
133164  offsets_out:
133165   sqlite3_free(sCtx.aTerm);
133166   assert( rc!=SQLITE_DONE );
133167   sqlite3Fts3SegmentsClose(pTab);
133168   if( rc!=SQLITE_OK ){
133169     sqlite3_result_error_code(pCtx,  rc);
133170     sqlite3_free(res.z);
133171   }else{
133172     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
133173   }
133174   return;
133175 }
133176 
133177 /*
133178 ** Implementation of matchinfo() function.
133179 */
133180 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
133181   sqlite3_context *pContext,      /* Function call context */
133182   Fts3Cursor *pCsr,               /* FTS3 table cursor */
133183   const char *zArg                /* Second arg to matchinfo() function */
133184 ){
133185   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133186   int rc;
133187   int i;
133188   const char *zFormat;
133189 
133190   if( zArg ){
133191     for(i=0; zArg[i]; i++){
133192       char *zErr = 0;
133193       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
133194         sqlite3_result_error(pContext, zErr, -1);
133195         sqlite3_free(zErr);
133196         return;
133197       }
133198     }
133199     zFormat = zArg;
133200   }else{
133201     zFormat = FTS3_MATCHINFO_DEFAULT;
133202   }
133203 
133204   if( !pCsr->pExpr ){
133205     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
133206     return;
133207   }
133208 
133209   /* Retrieve matchinfo() data. */
133210   rc = fts3GetMatchinfo(pCsr, zFormat);
133211   sqlite3Fts3SegmentsClose(pTab);
133212 
133213   if( rc!=SQLITE_OK ){
133214     sqlite3_result_error_code(pContext, rc);
133215   }else{
133216     int n = pCsr->nMatchinfo * sizeof(u32);
133217     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
133218   }
133219 }
133220 
133221 #endif
133222 
133223 /************** End of fts3_snippet.c ****************************************/
133224 /************** Begin file fts3_unicode.c ************************************/
133225 /*
133226 ** 2012 May 24
133227 **
133228 ** The author disclaims copyright to this source code.  In place of
133229 ** a legal notice, here is a blessing:
133230 **
133231 **    May you do good and not evil.
133232 **    May you find forgiveness for yourself and forgive others.
133233 **    May you share freely, never taking more than you give.
133234 **
133235 ******************************************************************************
133236 **
133237 ** Implementation of the "unicode" full-text-search tokenizer.
133238 */
133239 
133240 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
133241 
133242 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133243 
133244 /* #include <assert.h> */
133245 /* #include <stdlib.h> */
133246 /* #include <stdio.h> */
133247 /* #include <string.h> */
133248 
133249 
133250 /*
133251 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
133252 ** from the sqlite3 source file utf.c. If this file is compiled as part
133253 ** of the amalgamation, they are not required.
133254 */
133255 #ifndef SQLITE_AMALGAMATION
133256 
133257 static const unsigned char sqlite3Utf8Trans1[] = {
133258   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133259   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
133260   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
133261   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
133262   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133263   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
133264   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
133265   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
133266 };
133267 
133268 #define READ_UTF8(zIn, zTerm, c)                           \
133269   c = *(zIn++);                                            \
133270   if( c>=0xc0 ){                                           \
133271     c = sqlite3Utf8Trans1[c-0xc0];                         \
133272     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
133273       c = (c<<6) + (0x3f & *(zIn++));                      \
133274     }                                                      \
133275     if( c<0x80                                             \
133276         || (c&0xFFFFF800)==0xD800                          \
133277         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
133278   }
133279 
133280 #define WRITE_UTF8(zOut, c) {                          \
133281   if( c<0x00080 ){                                     \
133282     *zOut++ = (u8)(c&0xFF);                            \
133283   }                                                    \
133284   else if( c<0x00800 ){                                \
133285     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
133286     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133287   }                                                    \
133288   else if( c<0x10000 ){                                \
133289     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
133290     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
133291     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133292   }else{                                               \
133293     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
133294     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
133295     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
133296     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
133297   }                                                    \
133298 }
133299 
133300 #endif /* ifndef SQLITE_AMALGAMATION */
133301 
133302 typedef struct unicode_tokenizer unicode_tokenizer;
133303 typedef struct unicode_cursor unicode_cursor;
133304 
133305 struct unicode_tokenizer {
133306   sqlite3_tokenizer base;
133307   int bRemoveDiacritic;
133308   int nException;
133309   int *aiException;
133310 };
133311 
133312 struct unicode_cursor {
133313   sqlite3_tokenizer_cursor base;
133314   const unsigned char *aInput;    /* Input text being tokenized */
133315   int nInput;                     /* Size of aInput[] in bytes */
133316   int iOff;                       /* Current offset within aInput[] */
133317   int iToken;                     /* Index of next token to be returned */
133318   char *zToken;                   /* storage for current token */
133319   int nAlloc;                     /* space allocated at zToken */
133320 };
133321 
133322 
133323 /*
133324 ** Destroy a tokenizer allocated by unicodeCreate().
133325 */
133326 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
133327   if( pTokenizer ){
133328     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
133329     sqlite3_free(p->aiException);
133330     sqlite3_free(p);
133331   }
133332   return SQLITE_OK;
133333 }
133334 
133335 /*
133336 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
133337 ** statement has specified that the tokenizer for this table shall consider
133338 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
133339 ** token characters (if bAlnum==1).
133340 **
133341 ** For each codepoint in the zIn/nIn string, this function checks if the
133342 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
133343 ** If so, no action is taken. Otherwise, the codepoint is added to the
133344 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
133345 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
133346 ** codepoints in the aiException[] array.
133347 **
133348 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
133349 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
133350 ** It is not possible to change the behavior of the tokenizer with respect
133351 ** to these codepoints.
133352 */
133353 static int unicodeAddExceptions(
133354   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
133355   int bAlnum,                     /* Replace Isalnum() return value with this */
133356   const char *zIn,                /* Array of characters to make exceptions */
133357   int nIn                         /* Length of z in bytes */
133358 ){
133359   const unsigned char *z = (const unsigned char *)zIn;
133360   const unsigned char *zTerm = &z[nIn];
133361   int iCode;
133362   int nEntry = 0;
133363 
133364   assert( bAlnum==0 || bAlnum==1 );
133365 
133366   while( z<zTerm ){
133367     READ_UTF8(z, zTerm, iCode);
133368     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
133369     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
133370      && sqlite3FtsUnicodeIsdiacritic(iCode)==0
133371     ){
133372       nEntry++;
133373     }
133374   }
133375 
133376   if( nEntry ){
133377     int *aNew;                    /* New aiException[] array */
133378     int nNew;                     /* Number of valid entries in array aNew[] */
133379 
133380     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
133381     if( aNew==0 ) return SQLITE_NOMEM;
133382     nNew = p->nException;
133383 
133384     z = (const unsigned char *)zIn;
133385     while( z<zTerm ){
133386       READ_UTF8(z, zTerm, iCode);
133387       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
133388        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
133389       ){
133390         int i, j;
133391         for(i=0; i<nNew && aNew[i]<iCode; i++);
133392         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
133393         aNew[i] = iCode;
133394         nNew++;
133395       }
133396     }
133397     p->aiException = aNew;
133398     p->nException = nNew;
133399   }
133400 
133401   return SQLITE_OK;
133402 }
133403 
133404 /*
133405 ** Return true if the p->aiException[] array contains the value iCode.
133406 */
133407 static int unicodeIsException(unicode_tokenizer *p, int iCode){
133408   if( p->nException>0 ){
133409     int *a = p->aiException;
133410     int iLo = 0;
133411     int iHi = p->nException-1;
133412 
133413     while( iHi>=iLo ){
133414       int iTest = (iHi + iLo) / 2;
133415       if( iCode==a[iTest] ){
133416         return 1;
133417       }else if( iCode>a[iTest] ){
133418         iLo = iTest+1;
133419       }else{
133420         iHi = iTest-1;
133421       }
133422     }
133423   }
133424 
133425   return 0;
133426 }
133427 
133428 /*
133429 ** Return true if, for the purposes of tokenization, codepoint iCode is
133430 ** considered a token character (not a separator).
133431 */
133432 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
133433   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
133434   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
133435 }
133436 
133437 /*
133438 ** Create a new tokenizer instance.
133439 */
133440 static int unicodeCreate(
133441   int nArg,                       /* Size of array argv[] */
133442   const char * const *azArg,      /* Tokenizer creation arguments */
133443   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
133444 ){
133445   unicode_tokenizer *pNew;        /* New tokenizer object */
133446   int i;
133447   int rc = SQLITE_OK;
133448 
133449   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
133450   if( pNew==NULL ) return SQLITE_NOMEM;
133451   memset(pNew, 0, sizeof(unicode_tokenizer));
133452   pNew->bRemoveDiacritic = 1;
133453 
133454   for(i=0; rc==SQLITE_OK && i<nArg; i++){
133455     const char *z = azArg[i];
133456     int n = strlen(z);
133457 
133458     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
133459       pNew->bRemoveDiacritic = 1;
133460     }
133461     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
133462       pNew->bRemoveDiacritic = 0;
133463     }
133464     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
133465       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
133466     }
133467     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
133468       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
133469     }
133470     else{
133471       /* Unrecognized argument */
133472       rc  = SQLITE_ERROR;
133473     }
133474   }
133475 
133476   if( rc!=SQLITE_OK ){
133477     unicodeDestroy((sqlite3_tokenizer *)pNew);
133478     pNew = 0;
133479   }
133480   *pp = (sqlite3_tokenizer *)pNew;
133481   return rc;
133482 }
133483 
133484 /*
133485 ** Prepare to begin tokenizing a particular string.  The input
133486 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
133487 ** used to incrementally tokenize this string is returned in
133488 ** *ppCursor.
133489 */
133490 static int unicodeOpen(
133491   sqlite3_tokenizer *p,           /* The tokenizer */
133492   const char *aInput,             /* Input string */
133493   int nInput,                     /* Size of string aInput in bytes */
133494   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
133495 ){
133496   unicode_cursor *pCsr;
133497 
133498   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
133499   if( pCsr==0 ){
133500     return SQLITE_NOMEM;
133501   }
133502   memset(pCsr, 0, sizeof(unicode_cursor));
133503 
133504   pCsr->aInput = (const unsigned char *)aInput;
133505   if( aInput==0 ){
133506     pCsr->nInput = 0;
133507   }else if( nInput<0 ){
133508     pCsr->nInput = (int)strlen(aInput);
133509   }else{
133510     pCsr->nInput = nInput;
133511   }
133512 
133513   *pp = &pCsr->base;
133514   UNUSED_PARAMETER(p);
133515   return SQLITE_OK;
133516 }
133517 
133518 /*
133519 ** Close a tokenization cursor previously opened by a call to
133520 ** simpleOpen() above.
133521 */
133522 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
133523   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
133524   sqlite3_free(pCsr->zToken);
133525   sqlite3_free(pCsr);
133526   return SQLITE_OK;
133527 }
133528 
133529 /*
133530 ** Extract the next token from a tokenization cursor.  The cursor must
133531 ** have been opened by a prior call to simpleOpen().
133532 */
133533 static int unicodeNext(
133534   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
133535   const char **paToken,           /* OUT: Token text */
133536   int *pnToken,                   /* OUT: Number of bytes at *paToken */
133537   int *piStart,                   /* OUT: Starting offset of token */
133538   int *piEnd,                     /* OUT: Ending offset of token */
133539   int *piPos                      /* OUT: Position integer of token */
133540 ){
133541   unicode_cursor *pCsr = (unicode_cursor *)pC;
133542   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
133543   int iCode;
133544   char *zOut;
133545   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
133546   const unsigned char *zStart = z;
133547   const unsigned char *zEnd;
133548   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
133549 
133550   /* Scan past any delimiter characters before the start of the next token.
133551   ** Return SQLITE_DONE early if this takes us all the way to the end of
133552   ** the input.  */
133553   while( z<zTerm ){
133554     READ_UTF8(z, zTerm, iCode);
133555     if( unicodeIsAlnum(p, iCode) ) break;
133556     zStart = z;
133557   }
133558   if( zStart>=zTerm ) return SQLITE_DONE;
133559 
133560   zOut = pCsr->zToken;
133561   do {
133562     int iOut;
133563 
133564     /* Grow the output buffer if required. */
133565     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
133566       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
133567       if( !zNew ) return SQLITE_NOMEM;
133568       zOut = &zNew[zOut - pCsr->zToken];
133569       pCsr->zToken = zNew;
133570       pCsr->nAlloc += 64;
133571     }
133572 
133573     /* Write the folded case of the last character read to the output */
133574     zEnd = z;
133575     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
133576     if( iOut ){
133577       WRITE_UTF8(zOut, iOut);
133578     }
133579 
133580     /* If the cursor is not at EOF, read the next character */
133581     if( z>=zTerm ) break;
133582     READ_UTF8(z, zTerm, iCode);
133583   }while( unicodeIsAlnum(p, iCode)
133584        || sqlite3FtsUnicodeIsdiacritic(iCode)
133585   );
133586 
133587   /* Set the output variables and return. */
133588   pCsr->iOff = (z - pCsr->aInput);
133589   *paToken = pCsr->zToken;
133590   *pnToken = zOut - pCsr->zToken;
133591   *piStart = (zStart - pCsr->aInput);
133592   *piEnd = (zEnd - pCsr->aInput);
133593   *piPos = pCsr->iToken++;
133594   return SQLITE_OK;
133595 }
133596 
133597 /*
133598 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
133599 ** structure for the unicode tokenizer.
133600 */
133601 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
133602   static const sqlite3_tokenizer_module module = {
133603     0,
133604     unicodeCreate,
133605     unicodeDestroy,
133606     unicodeOpen,
133607     unicodeClose,
133608     unicodeNext,
133609     0,
133610   };
133611   *ppModule = &module;
133612 }
133613 
133614 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133615 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
133616 
133617 /************** End of fts3_unicode.c ****************************************/
133618 /************** Begin file fts3_unicode2.c ***********************************/
133619 /*
133620 ** 2012 May 25
133621 **
133622 ** The author disclaims copyright to this source code.  In place of
133623 ** a legal notice, here is a blessing:
133624 **
133625 **    May you do good and not evil.
133626 **    May you find forgiveness for yourself and forgive others.
133627 **    May you share freely, never taking more than you give.
133628 **
133629 ******************************************************************************
133630 */
133631 
133632 /*
133633 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
133634 */
133635 
133636 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
133637 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
133638 
133639 /* #include <assert.h> */
133640 
133641 /*
133642 ** Return true if the argument corresponds to a unicode codepoint
133643 ** classified as either a letter or a number. Otherwise false.
133644 **
133645 ** The results are undefined if the value passed to this function
133646 ** is less than zero.
133647 */
133648 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
133649   /* Each unsigned integer in the following array corresponds to a contiguous
133650   ** range of unicode codepoints that are not either letters or numbers (i.e.
133651   ** codepoints for which this function should return 0).
133652   **
133653   ** The most significant 22 bits in each 32-bit value contain the first
133654   ** codepoint in the range. The least significant 10 bits are used to store
133655   ** the size of the range (always at least 1). In other words, the value
133656   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
133657   ** C. It is not possible to represent a range larger than 1023 codepoints
133658   ** using this format.
133659   */
133660   const static unsigned int aEntry[] = {
133661     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
133662     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
133663     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
133664     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
133665     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
133666     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
133667     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
133668     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
133669     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
133670     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
133671     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
133672     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
133673     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
133674     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
133675     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
133676     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
133677     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
133678     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
133679     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
133680     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
133681     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
133682     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
133683     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
133684     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
133685     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
133686     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
133687     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
133688     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
133689     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
133690     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
133691     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
133692     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
133693     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
133694     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
133695     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
133696     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
133697     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
133698     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
133699     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
133700     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
133701     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
133702     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
133703     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
133704     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
133705     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
133706     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
133707     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
133708     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
133709     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
133710     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
133711     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
133712     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
133713     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
133714     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
133715     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
133716     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
133717     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
133718     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
133719     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
133720     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
133721     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
133722     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
133723     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
133724     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
133725     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
133726     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
133727     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
133728     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
133729     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
133730     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
133731     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
133732     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
133733     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
133734     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
133735     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
133736     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
133737     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
133738     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
133739     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
133740     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
133741     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
133742     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
133743     0x43FFF401,
133744   };
133745   static const unsigned int aAscii[4] = {
133746     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
133747   };
133748 
133749   if( c<128 ){
133750     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
133751   }else if( c<(1<<22) ){
133752     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
133753     int iRes;
133754     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133755     int iLo = 0;
133756     while( iHi>=iLo ){
133757       int iTest = (iHi + iLo) / 2;
133758       if( key >= aEntry[iTest] ){
133759         iRes = iTest;
133760         iLo = iTest+1;
133761       }else{
133762         iHi = iTest-1;
133763       }
133764     }
133765     assert( aEntry[0]<key );
133766     assert( key>=aEntry[iRes] );
133767     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
133768   }
133769   return 1;
133770 }
133771 
133772 
133773 /*
133774 ** If the argument is a codepoint corresponding to a lowercase letter
133775 ** in the ASCII range with a diacritic added, return the codepoint
133776 ** of the ASCII letter only. For example, if passed 235 - "LATIN
133777 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
133778 ** E"). The resuls of passing a codepoint that corresponds to an
133779 ** uppercase letter are undefined.
133780 */
133781 static int remove_diacritic(int c){
133782   unsigned short aDia[] = {
133783         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
133784      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
133785      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
133786      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
133787      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
133788      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
133789      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
133790      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
133791     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
133792     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
133793     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
133794     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
133795     62924, 63050, 63082, 63274, 63390,
133796   };
133797   char aChar[] = {
133798     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
133799     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
133800     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
133801     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
133802     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
133803     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
133804     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
133805     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
133806     'e',  'i',  'o',  'u',  'y',
133807   };
133808 
133809   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
133810   int iRes = 0;
133811   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
133812   int iLo = 0;
133813   while( iHi>=iLo ){
133814     int iTest = (iHi + iLo) / 2;
133815     if( key >= aDia[iTest] ){
133816       iRes = iTest;
133817       iLo = iTest+1;
133818     }else{
133819       iHi = iTest-1;
133820     }
133821   }
133822   assert( key>=aDia[iRes] );
133823   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
133824 };
133825 
133826 
133827 /*
133828 ** Return true if the argument interpreted as a unicode codepoint
133829 ** is a diacritical modifier character.
133830 */
133831 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
133832   unsigned int mask0 = 0x08029FDF;
133833   unsigned int mask1 = 0x000361F8;
133834   if( c<768 || c>817 ) return 0;
133835   return (c < 768+32) ?
133836       (mask0 & (1 << (c-768))) :
133837       (mask1 & (1 << (c-768-32)));
133838 }
133839 
133840 
133841 /*
133842 ** Interpret the argument as a unicode codepoint. If the codepoint
133843 ** is an upper case character that has a lower case equivalent,
133844 ** return the codepoint corresponding to the lower case version.
133845 ** Otherwise, return a copy of the argument.
133846 **
133847 ** The results are undefined if the value passed to this function
133848 ** is less than zero.
133849 */
133850 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
133851   /* Each entry in the following array defines a rule for folding a range
133852   ** of codepoints to lower case. The rule applies to a range of nRange
133853   ** codepoints starting at codepoint iCode.
133854   **
133855   ** If the least significant bit in flags is clear, then the rule applies
133856   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
133857   ** need to be folded). Or, if it is set, then the rule only applies to
133858   ** every second codepoint in the range, starting with codepoint C.
133859   **
133860   ** The 7 most significant bits in flags are an index into the aiOff[]
133861   ** array. If a specific codepoint C does require folding, then its lower
133862   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
133863   **
133864   ** The contents of this array are generated by parsing the CaseFolding.txt
133865   ** file distributed as part of the "Unicode Character Database". See
133866   ** http://www.unicode.org for details.
133867   */
133868   static const struct TableEntry {
133869     unsigned short iCode;
133870     unsigned char flags;
133871     unsigned char nRange;
133872   } aEntry[] = {
133873     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
133874     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
133875     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
133876     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
133877     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
133878     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
133879     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
133880     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
133881     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
133882     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
133883     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
133884     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
133885     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
133886     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
133887     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
133888     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
133889     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
133890     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
133891     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
133892     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
133893     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
133894     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
133895     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
133896     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
133897     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
133898     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
133899     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
133900     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
133901     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
133902     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
133903     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
133904     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
133905     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
133906     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
133907     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
133908     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
133909     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
133910     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
133911     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
133912     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
133913     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
133914     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
133915     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
133916     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
133917     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
133918     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
133919     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
133920     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
133921     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
133922     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
133923     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
133924     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
133925     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
133926     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
133927     {65313, 14, 26},
133928   };
133929   static const unsigned short aiOff[] = {
133930    1,     2,     8,     15,    16,    26,    28,    32,
133931    37,    38,    40,    48,    63,    64,    69,    71,
133932    79,    80,    116,   202,   203,   205,   206,   207,
133933    209,   210,   211,   213,   214,   217,   218,   219,
133934    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
133935    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
133936    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
133937    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
133938    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
133939    65514, 65521, 65527, 65528, 65529,
133940   };
133941 
133942   int ret = c;
133943 
133944   assert( c>=0 );
133945   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
133946 
133947   if( c<128 ){
133948     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
133949   }else if( c<65536 ){
133950     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
133951     int iLo = 0;
133952     int iRes = -1;
133953 
133954     while( iHi>=iLo ){
133955       int iTest = (iHi + iLo) / 2;
133956       int cmp = (c - aEntry[iTest].iCode);
133957       if( cmp>=0 ){
133958         iRes = iTest;
133959         iLo = iTest+1;
133960       }else{
133961         iHi = iTest-1;
133962       }
133963     }
133964     assert( iRes<0 || c>=aEntry[iRes].iCode );
133965 
133966     if( iRes>=0 ){
133967       const struct TableEntry *p = &aEntry[iRes];
133968       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
133969         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
133970         assert( ret>0 );
133971       }
133972     }
133973 
133974     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
133975   }
133976 
133977   else if( c>=66560 && c<66600 ){
133978     ret = c + 40;
133979   }
133980 
133981   return ret;
133982 }
133983 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
133984 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
133985 
133986 /************** End of fts3_unicode2.c ***************************************/
133987 /************** Begin file rtree.c *******************************************/
133988 /*
133989 ** 2001 September 15
133990 **
133991 ** The author disclaims copyright to this source code.  In place of
133992 ** a legal notice, here is a blessing:
133993 **
133994 **    May you do good and not evil.
133995 **    May you find forgiveness for yourself and forgive others.
133996 **    May you share freely, never taking more than you give.
133997 **
133998 *************************************************************************
133999 ** This file contains code for implementations of the r-tree and r*-tree
134000 ** algorithms packaged as an SQLite virtual table module.
134001 */
134002 
134003 /*
134004 ** Database Format of R-Tree Tables
134005 ** --------------------------------
134006 **
134007 ** The data structure for a single virtual r-tree table is stored in three
134008 ** native SQLite tables declared as follows. In each case, the '%' character
134009 ** in the table name is replaced with the user-supplied name of the r-tree
134010 ** table.
134011 **
134012 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
134013 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
134014 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
134015 **
134016 ** The data for each node of the r-tree structure is stored in the %_node
134017 ** table. For each node that is not the root node of the r-tree, there is
134018 ** an entry in the %_parent table associating the node with its parent.
134019 ** And for each row of data in the table, there is an entry in the %_rowid
134020 ** table that maps from the entries rowid to the id of the node that it
134021 ** is stored on.
134022 **
134023 ** The root node of an r-tree always exists, even if the r-tree table is
134024 ** empty. The nodeno of the root node is always 1. All other nodes in the
134025 ** table must be the same size as the root node. The content of each node
134026 ** is formatted as follows:
134027 **
134028 **   1. If the node is the root node (node 1), then the first 2 bytes
134029 **      of the node contain the tree depth as a big-endian integer.
134030 **      For non-root nodes, the first 2 bytes are left unused.
134031 **
134032 **   2. The next 2 bytes contain the number of entries currently
134033 **      stored in the node.
134034 **
134035 **   3. The remainder of the node contains the node entries. Each entry
134036 **      consists of a single 8-byte integer followed by an even number
134037 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
134038 **      of a record. For internal nodes it is the node number of a
134039 **      child page.
134040 */
134041 
134042 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
134043 
134044 /*
134045 ** This file contains an implementation of a couple of different variants
134046 ** of the r-tree algorithm. See the README file for further details. The
134047 ** same data-structure is used for all, but the algorithms for insert and
134048 ** delete operations vary. The variants used are selected at compile time
134049 ** by defining the following symbols:
134050 */
134051 
134052 /* Either, both or none of the following may be set to activate
134053 ** r*tree variant algorithms.
134054 */
134055 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
134056 #define VARIANT_RSTARTREE_REINSERT      1
134057 
134058 /*
134059 ** Exactly one of the following must be set to 1.
134060 */
134061 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
134062 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
134063 #define VARIANT_RSTARTREE_SPLIT         1
134064 
134065 #define VARIANT_GUTTMAN_SPLIT \
134066         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
134067 
134068 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
134069   #define PickNext QuadraticPickNext
134070   #define PickSeeds QuadraticPickSeeds
134071   #define AssignCells splitNodeGuttman
134072 #endif
134073 #if VARIANT_GUTTMAN_LINEAR_SPLIT
134074   #define PickNext LinearPickNext
134075   #define PickSeeds LinearPickSeeds
134076   #define AssignCells splitNodeGuttman
134077 #endif
134078 #if VARIANT_RSTARTREE_SPLIT
134079   #define AssignCells splitNodeStartree
134080 #endif
134081 
134082 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
134083 # define NDEBUG 1
134084 #endif
134085 
134086 #ifndef SQLITE_CORE
134087   SQLITE_EXTENSION_INIT1
134088 #else
134089 #endif
134090 
134091 /* #include <string.h> */
134092 /* #include <assert.h> */
134093 
134094 #ifndef SQLITE_AMALGAMATION
134095 #include "sqlite3rtree.h"
134096 typedef sqlite3_int64 i64;
134097 typedef unsigned char u8;
134098 typedef unsigned int u32;
134099 #endif
134100 
134101 /*  The following macro is used to suppress compiler warnings.
134102 */
134103 #ifndef UNUSED_PARAMETER
134104 # define UNUSED_PARAMETER(x) (void)(x)
134105 #endif
134106 
134107 typedef struct Rtree Rtree;
134108 typedef struct RtreeCursor RtreeCursor;
134109 typedef struct RtreeNode RtreeNode;
134110 typedef struct RtreeCell RtreeCell;
134111 typedef struct RtreeConstraint RtreeConstraint;
134112 typedef struct RtreeMatchArg RtreeMatchArg;
134113 typedef struct RtreeGeomCallback RtreeGeomCallback;
134114 typedef union RtreeCoord RtreeCoord;
134115 
134116 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
134117 #define RTREE_MAX_DIMENSIONS 5
134118 
134119 /* Size of hash table Rtree.aHash. This hash table is not expected to
134120 ** ever contain very many entries, so a fixed number of buckets is
134121 ** used.
134122 */
134123 #define HASHSIZE 128
134124 
134125 /*
134126 ** An rtree virtual-table object.
134127 */
134128 struct Rtree {
134129   sqlite3_vtab base;
134130   sqlite3 *db;                /* Host database connection */
134131   int iNodeSize;              /* Size in bytes of each node in the node table */
134132   int nDim;                   /* Number of dimensions */
134133   int nBytesPerCell;          /* Bytes consumed per cell */
134134   int iDepth;                 /* Current depth of the r-tree structure */
134135   char *zDb;                  /* Name of database containing r-tree table */
134136   char *zName;                /* Name of r-tree table */
134137   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
134138   int nBusy;                  /* Current number of users of this structure */
134139 
134140   /* List of nodes removed during a CondenseTree operation. List is
134141   ** linked together via the pointer normally used for hash chains -
134142   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
134143   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
134144   */
134145   RtreeNode *pDeleted;
134146   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
134147 
134148   /* Statements to read/write/delete a record from xxx_node */
134149   sqlite3_stmt *pReadNode;
134150   sqlite3_stmt *pWriteNode;
134151   sqlite3_stmt *pDeleteNode;
134152 
134153   /* Statements to read/write/delete a record from xxx_rowid */
134154   sqlite3_stmt *pReadRowid;
134155   sqlite3_stmt *pWriteRowid;
134156   sqlite3_stmt *pDeleteRowid;
134157 
134158   /* Statements to read/write/delete a record from xxx_parent */
134159   sqlite3_stmt *pReadParent;
134160   sqlite3_stmt *pWriteParent;
134161   sqlite3_stmt *pDeleteParent;
134162 
134163   int eCoordType;
134164 };
134165 
134166 /* Possible values for eCoordType: */
134167 #define RTREE_COORD_REAL32 0
134168 #define RTREE_COORD_INT32  1
134169 
134170 /*
134171 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
134172 ** only deal with integer coordinates.  No floating point operations
134173 ** will be done.
134174 */
134175 #ifdef SQLITE_RTREE_INT_ONLY
134176   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
134177   typedef int RtreeValue;                  /* Low accuracy coordinate */
134178 #else
134179   typedef double RtreeDValue;              /* High accuracy coordinate */
134180   typedef float RtreeValue;                /* Low accuracy coordinate */
134181 #endif
134182 
134183 /*
134184 ** The minimum number of cells allowed for a node is a third of the
134185 ** maximum. In Gutman's notation:
134186 **
134187 **     m = M/3
134188 **
134189 ** If an R*-tree "Reinsert" operation is required, the same number of
134190 ** cells are removed from the overfull node and reinserted into the tree.
134191 */
134192 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
134193 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
134194 #define RTREE_MAXCELLS 51
134195 
134196 /*
134197 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
134198 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
134199 ** Therefore all non-root nodes must contain at least 3 entries. Since
134200 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
134201 ** 40 or less.
134202 */
134203 #define RTREE_MAX_DEPTH 40
134204 
134205 /*
134206 ** An rtree cursor object.
134207 */
134208 struct RtreeCursor {
134209   sqlite3_vtab_cursor base;
134210   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
134211   int iCell;                        /* Index of current cell in pNode */
134212   int iStrategy;                    /* Copy of idxNum search parameter */
134213   int nConstraint;                  /* Number of entries in aConstraint */
134214   RtreeConstraint *aConstraint;     /* Search constraints. */
134215 };
134216 
134217 union RtreeCoord {
134218   RtreeValue f;
134219   int i;
134220 };
134221 
134222 /*
134223 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
134224 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
134225 ** variable pRtree points to the Rtree structure associated with the
134226 ** RtreeCoord.
134227 */
134228 #ifdef SQLITE_RTREE_INT_ONLY
134229 # define DCOORD(coord) ((RtreeDValue)coord.i)
134230 #else
134231 # define DCOORD(coord) (                           \
134232     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
134233       ((double)coord.f) :                           \
134234       ((double)coord.i)                             \
134235   )
134236 #endif
134237 
134238 /*
134239 ** A search constraint.
134240 */
134241 struct RtreeConstraint {
134242   int iCoord;                     /* Index of constrained coordinate */
134243   int op;                         /* Constraining operation */
134244   RtreeDValue rValue;             /* Constraint value. */
134245   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
134246   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
134247 };
134248 
134249 /* Possible values for RtreeConstraint.op */
134250 #define RTREE_EQ    0x41
134251 #define RTREE_LE    0x42
134252 #define RTREE_LT    0x43
134253 #define RTREE_GE    0x44
134254 #define RTREE_GT    0x45
134255 #define RTREE_MATCH 0x46
134256 
134257 /*
134258 ** An rtree structure node.
134259 */
134260 struct RtreeNode {
134261   RtreeNode *pParent;               /* Parent node */
134262   i64 iNode;
134263   int nRef;
134264   int isDirty;
134265   u8 *zData;
134266   RtreeNode *pNext;                 /* Next node in this hash chain */
134267 };
134268 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
134269 
134270 /*
134271 ** Structure to store a deserialized rtree record.
134272 */
134273 struct RtreeCell {
134274   i64 iRowid;
134275   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
134276 };
134277 
134278 
134279 /*
134280 ** Value for the first field of every RtreeMatchArg object. The MATCH
134281 ** operator tests that the first field of a blob operand matches this
134282 ** value to avoid operating on invalid blobs (which could cause a segfault).
134283 */
134284 #define RTREE_GEOMETRY_MAGIC 0x891245AB
134285 
134286 /*
134287 ** An instance of this structure must be supplied as a blob argument to
134288 ** the right-hand-side of an SQL MATCH operator used to constrain an
134289 ** r-tree query.
134290 */
134291 struct RtreeMatchArg {
134292   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
134293   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
134294   void *pContext;
134295   int nParam;
134296   RtreeDValue aParam[1];
134297 };
134298 
134299 /*
134300 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
134301 ** a single instance of the following structure is allocated. It is used
134302 ** as the context for the user-function created by by s_r_g_c(). The object
134303 ** is eventually deleted by the destructor mechanism provided by
134304 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
134305 ** the geometry callback function).
134306 */
134307 struct RtreeGeomCallback {
134308   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
134309   void *pContext;
134310 };
134311 
134312 #ifndef MAX
134313 # define MAX(x,y) ((x) < (y) ? (y) : (x))
134314 #endif
134315 #ifndef MIN
134316 # define MIN(x,y) ((x) > (y) ? (y) : (x))
134317 #endif
134318 
134319 /*
134320 ** Functions to deserialize a 16 bit integer, 32 bit real number and
134321 ** 64 bit integer. The deserialized value is returned.
134322 */
134323 static int readInt16(u8 *p){
134324   return (p[0]<<8) + p[1];
134325 }
134326 static void readCoord(u8 *p, RtreeCoord *pCoord){
134327   u32 i = (
134328     (((u32)p[0]) << 24) +
134329     (((u32)p[1]) << 16) +
134330     (((u32)p[2]) <<  8) +
134331     (((u32)p[3]) <<  0)
134332   );
134333   *(u32 *)pCoord = i;
134334 }
134335 static i64 readInt64(u8 *p){
134336   return (
134337     (((i64)p[0]) << 56) +
134338     (((i64)p[1]) << 48) +
134339     (((i64)p[2]) << 40) +
134340     (((i64)p[3]) << 32) +
134341     (((i64)p[4]) << 24) +
134342     (((i64)p[5]) << 16) +
134343     (((i64)p[6]) <<  8) +
134344     (((i64)p[7]) <<  0)
134345   );
134346 }
134347 
134348 /*
134349 ** Functions to serialize a 16 bit integer, 32 bit real number and
134350 ** 64 bit integer. The value returned is the number of bytes written
134351 ** to the argument buffer (always 2, 4 and 8 respectively).
134352 */
134353 static int writeInt16(u8 *p, int i){
134354   p[0] = (i>> 8)&0xFF;
134355   p[1] = (i>> 0)&0xFF;
134356   return 2;
134357 }
134358 static int writeCoord(u8 *p, RtreeCoord *pCoord){
134359   u32 i;
134360   assert( sizeof(RtreeCoord)==4 );
134361   assert( sizeof(u32)==4 );
134362   i = *(u32 *)pCoord;
134363   p[0] = (i>>24)&0xFF;
134364   p[1] = (i>>16)&0xFF;
134365   p[2] = (i>> 8)&0xFF;
134366   p[3] = (i>> 0)&0xFF;
134367   return 4;
134368 }
134369 static int writeInt64(u8 *p, i64 i){
134370   p[0] = (i>>56)&0xFF;
134371   p[1] = (i>>48)&0xFF;
134372   p[2] = (i>>40)&0xFF;
134373   p[3] = (i>>32)&0xFF;
134374   p[4] = (i>>24)&0xFF;
134375   p[5] = (i>>16)&0xFF;
134376   p[6] = (i>> 8)&0xFF;
134377   p[7] = (i>> 0)&0xFF;
134378   return 8;
134379 }
134380 
134381 /*
134382 ** Increment the reference count of node p.
134383 */
134384 static void nodeReference(RtreeNode *p){
134385   if( p ){
134386     p->nRef++;
134387   }
134388 }
134389 
134390 /*
134391 ** Clear the content of node p (set all bytes to 0x00).
134392 */
134393 static void nodeZero(Rtree *pRtree, RtreeNode *p){
134394   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
134395   p->isDirty = 1;
134396 }
134397 
134398 /*
134399 ** Given a node number iNode, return the corresponding key to use
134400 ** in the Rtree.aHash table.
134401 */
134402 static int nodeHash(i64 iNode){
134403   return (
134404     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
134405     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
134406   ) % HASHSIZE;
134407 }
134408 
134409 /*
134410 ** Search the node hash table for node iNode. If found, return a pointer
134411 ** to it. Otherwise, return 0.
134412 */
134413 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
134414   RtreeNode *p;
134415   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
134416   return p;
134417 }
134418 
134419 /*
134420 ** Add node pNode to the node hash table.
134421 */
134422 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
134423   int iHash;
134424   assert( pNode->pNext==0 );
134425   iHash = nodeHash(pNode->iNode);
134426   pNode->pNext = pRtree->aHash[iHash];
134427   pRtree->aHash[iHash] = pNode;
134428 }
134429 
134430 /*
134431 ** Remove node pNode from the node hash table.
134432 */
134433 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
134434   RtreeNode **pp;
134435   if( pNode->iNode!=0 ){
134436     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
134437     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
134438     *pp = pNode->pNext;
134439     pNode->pNext = 0;
134440   }
134441 }
134442 
134443 /*
134444 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
134445 ** indicating that node has not yet been assigned a node number. It is
134446 ** assigned a node number when nodeWrite() is called to write the
134447 ** node contents out to the database.
134448 */
134449 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
134450   RtreeNode *pNode;
134451   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
134452   if( pNode ){
134453     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
134454     pNode->zData = (u8 *)&pNode[1];
134455     pNode->nRef = 1;
134456     pNode->pParent = pParent;
134457     pNode->isDirty = 1;
134458     nodeReference(pParent);
134459   }
134460   return pNode;
134461 }
134462 
134463 /*
134464 ** Obtain a reference to an r-tree node.
134465 */
134466 static int
134467 nodeAcquire(
134468   Rtree *pRtree,             /* R-tree structure */
134469   i64 iNode,                 /* Node number to load */
134470   RtreeNode *pParent,        /* Either the parent node or NULL */
134471   RtreeNode **ppNode         /* OUT: Acquired node */
134472 ){
134473   int rc;
134474   int rc2 = SQLITE_OK;
134475   RtreeNode *pNode;
134476 
134477   /* Check if the requested node is already in the hash table. If so,
134478   ** increase its reference count and return it.
134479   */
134480   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
134481     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
134482     if( pParent && !pNode->pParent ){
134483       nodeReference(pParent);
134484       pNode->pParent = pParent;
134485     }
134486     pNode->nRef++;
134487     *ppNode = pNode;
134488     return SQLITE_OK;
134489   }
134490 
134491   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
134492   rc = sqlite3_step(pRtree->pReadNode);
134493   if( rc==SQLITE_ROW ){
134494     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
134495     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
134496       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
134497       if( !pNode ){
134498         rc2 = SQLITE_NOMEM;
134499       }else{
134500         pNode->pParent = pParent;
134501         pNode->zData = (u8 *)&pNode[1];
134502         pNode->nRef = 1;
134503         pNode->iNode = iNode;
134504         pNode->isDirty = 0;
134505         pNode->pNext = 0;
134506         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
134507         nodeReference(pParent);
134508       }
134509     }
134510   }
134511   rc = sqlite3_reset(pRtree->pReadNode);
134512   if( rc==SQLITE_OK ) rc = rc2;
134513 
134514   /* If the root node was just loaded, set pRtree->iDepth to the height
134515   ** of the r-tree structure. A height of zero means all data is stored on
134516   ** the root node. A height of one means the children of the root node
134517   ** are the leaves, and so on. If the depth as specified on the root node
134518   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
134519   */
134520   if( pNode && iNode==1 ){
134521     pRtree->iDepth = readInt16(pNode->zData);
134522     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
134523       rc = SQLITE_CORRUPT_VTAB;
134524     }
134525   }
134526 
134527   /* If no error has occurred so far, check if the "number of entries"
134528   ** field on the node is too large. If so, set the return code to
134529   ** SQLITE_CORRUPT_VTAB.
134530   */
134531   if( pNode && rc==SQLITE_OK ){
134532     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
134533       rc = SQLITE_CORRUPT_VTAB;
134534     }
134535   }
134536 
134537   if( rc==SQLITE_OK ){
134538     if( pNode!=0 ){
134539       nodeHashInsert(pRtree, pNode);
134540     }else{
134541       rc = SQLITE_CORRUPT_VTAB;
134542     }
134543     *ppNode = pNode;
134544   }else{
134545     sqlite3_free(pNode);
134546     *ppNode = 0;
134547   }
134548 
134549   return rc;
134550 }
134551 
134552 /*
134553 ** Overwrite cell iCell of node pNode with the contents of pCell.
134554 */
134555 static void nodeOverwriteCell(
134556   Rtree *pRtree,
134557   RtreeNode *pNode,
134558   RtreeCell *pCell,
134559   int iCell
134560 ){
134561   int ii;
134562   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
134563   p += writeInt64(p, pCell->iRowid);
134564   for(ii=0; ii<(pRtree->nDim*2); ii++){
134565     p += writeCoord(p, &pCell->aCoord[ii]);
134566   }
134567   pNode->isDirty = 1;
134568 }
134569 
134570 /*
134571 ** Remove cell the cell with index iCell from node pNode.
134572 */
134573 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
134574   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
134575   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
134576   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
134577   memmove(pDst, pSrc, nByte);
134578   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
134579   pNode->isDirty = 1;
134580 }
134581 
134582 /*
134583 ** Insert the contents of cell pCell into node pNode. If the insert
134584 ** is successful, return SQLITE_OK.
134585 **
134586 ** If there is not enough free space in pNode, return SQLITE_FULL.
134587 */
134588 static int
134589 nodeInsertCell(
134590   Rtree *pRtree,
134591   RtreeNode *pNode,
134592   RtreeCell *pCell
134593 ){
134594   int nCell;                    /* Current number of cells in pNode */
134595   int nMaxCell;                 /* Maximum number of cells for pNode */
134596 
134597   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
134598   nCell = NCELL(pNode);
134599 
134600   assert( nCell<=nMaxCell );
134601   if( nCell<nMaxCell ){
134602     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
134603     writeInt16(&pNode->zData[2], nCell+1);
134604     pNode->isDirty = 1;
134605   }
134606 
134607   return (nCell==nMaxCell);
134608 }
134609 
134610 /*
134611 ** If the node is dirty, write it out to the database.
134612 */
134613 static int
134614 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
134615   int rc = SQLITE_OK;
134616   if( pNode->isDirty ){
134617     sqlite3_stmt *p = pRtree->pWriteNode;
134618     if( pNode->iNode ){
134619       sqlite3_bind_int64(p, 1, pNode->iNode);
134620     }else{
134621       sqlite3_bind_null(p, 1);
134622     }
134623     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
134624     sqlite3_step(p);
134625     pNode->isDirty = 0;
134626     rc = sqlite3_reset(p);
134627     if( pNode->iNode==0 && rc==SQLITE_OK ){
134628       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
134629       nodeHashInsert(pRtree, pNode);
134630     }
134631   }
134632   return rc;
134633 }
134634 
134635 /*
134636 ** Release a reference to a node. If the node is dirty and the reference
134637 ** count drops to zero, the node data is written to the database.
134638 */
134639 static int
134640 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
134641   int rc = SQLITE_OK;
134642   if( pNode ){
134643     assert( pNode->nRef>0 );
134644     pNode->nRef--;
134645     if( pNode->nRef==0 ){
134646       if( pNode->iNode==1 ){
134647         pRtree->iDepth = -1;
134648       }
134649       if( pNode->pParent ){
134650         rc = nodeRelease(pRtree, pNode->pParent);
134651       }
134652       if( rc==SQLITE_OK ){
134653         rc = nodeWrite(pRtree, pNode);
134654       }
134655       nodeHashDelete(pRtree, pNode);
134656       sqlite3_free(pNode);
134657     }
134658   }
134659   return rc;
134660 }
134661 
134662 /*
134663 ** Return the 64-bit integer value associated with cell iCell of
134664 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
134665 ** an internal node, then the 64-bit integer is a child page number.
134666 */
134667 static i64 nodeGetRowid(
134668   Rtree *pRtree,
134669   RtreeNode *pNode,
134670   int iCell
134671 ){
134672   assert( iCell<NCELL(pNode) );
134673   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
134674 }
134675 
134676 /*
134677 ** Return coordinate iCoord from cell iCell in node pNode.
134678 */
134679 static void nodeGetCoord(
134680   Rtree *pRtree,
134681   RtreeNode *pNode,
134682   int iCell,
134683   int iCoord,
134684   RtreeCoord *pCoord           /* Space to write result to */
134685 ){
134686   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
134687 }
134688 
134689 /*
134690 ** Deserialize cell iCell of node pNode. Populate the structure pointed
134691 ** to by pCell with the results.
134692 */
134693 static void nodeGetCell(
134694   Rtree *pRtree,
134695   RtreeNode *pNode,
134696   int iCell,
134697   RtreeCell *pCell
134698 ){
134699   int ii;
134700   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
134701   for(ii=0; ii<pRtree->nDim*2; ii++){
134702     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
134703   }
134704 }
134705 
134706 
134707 /* Forward declaration for the function that does the work of
134708 ** the virtual table module xCreate() and xConnect() methods.
134709 */
134710 static int rtreeInit(
134711   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
134712 );
134713 
134714 /*
134715 ** Rtree virtual table module xCreate method.
134716 */
134717 static int rtreeCreate(
134718   sqlite3 *db,
134719   void *pAux,
134720   int argc, const char *const*argv,
134721   sqlite3_vtab **ppVtab,
134722   char **pzErr
134723 ){
134724   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
134725 }
134726 
134727 /*
134728 ** Rtree virtual table module xConnect method.
134729 */
134730 static int rtreeConnect(
134731   sqlite3 *db,
134732   void *pAux,
134733   int argc, const char *const*argv,
134734   sqlite3_vtab **ppVtab,
134735   char **pzErr
134736 ){
134737   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
134738 }
134739 
134740 /*
134741 ** Increment the r-tree reference count.
134742 */
134743 static void rtreeReference(Rtree *pRtree){
134744   pRtree->nBusy++;
134745 }
134746 
134747 /*
134748 ** Decrement the r-tree reference count. When the reference count reaches
134749 ** zero the structure is deleted.
134750 */
134751 static void rtreeRelease(Rtree *pRtree){
134752   pRtree->nBusy--;
134753   if( pRtree->nBusy==0 ){
134754     sqlite3_finalize(pRtree->pReadNode);
134755     sqlite3_finalize(pRtree->pWriteNode);
134756     sqlite3_finalize(pRtree->pDeleteNode);
134757     sqlite3_finalize(pRtree->pReadRowid);
134758     sqlite3_finalize(pRtree->pWriteRowid);
134759     sqlite3_finalize(pRtree->pDeleteRowid);
134760     sqlite3_finalize(pRtree->pReadParent);
134761     sqlite3_finalize(pRtree->pWriteParent);
134762     sqlite3_finalize(pRtree->pDeleteParent);
134763     sqlite3_free(pRtree);
134764   }
134765 }
134766 
134767 /*
134768 ** Rtree virtual table module xDisconnect method.
134769 */
134770 static int rtreeDisconnect(sqlite3_vtab *pVtab){
134771   rtreeRelease((Rtree *)pVtab);
134772   return SQLITE_OK;
134773 }
134774 
134775 /*
134776 ** Rtree virtual table module xDestroy method.
134777 */
134778 static int rtreeDestroy(sqlite3_vtab *pVtab){
134779   Rtree *pRtree = (Rtree *)pVtab;
134780   int rc;
134781   char *zCreate = sqlite3_mprintf(
134782     "DROP TABLE '%q'.'%q_node';"
134783     "DROP TABLE '%q'.'%q_rowid';"
134784     "DROP TABLE '%q'.'%q_parent';",
134785     pRtree->zDb, pRtree->zName,
134786     pRtree->zDb, pRtree->zName,
134787     pRtree->zDb, pRtree->zName
134788   );
134789   if( !zCreate ){
134790     rc = SQLITE_NOMEM;
134791   }else{
134792     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
134793     sqlite3_free(zCreate);
134794   }
134795   if( rc==SQLITE_OK ){
134796     rtreeRelease(pRtree);
134797   }
134798 
134799   return rc;
134800 }
134801 
134802 /*
134803 ** Rtree virtual table module xOpen method.
134804 */
134805 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
134806   int rc = SQLITE_NOMEM;
134807   RtreeCursor *pCsr;
134808 
134809   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
134810   if( pCsr ){
134811     memset(pCsr, 0, sizeof(RtreeCursor));
134812     pCsr->base.pVtab = pVTab;
134813     rc = SQLITE_OK;
134814   }
134815   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
134816 
134817   return rc;
134818 }
134819 
134820 
134821 /*
134822 ** Free the RtreeCursor.aConstraint[] array and its contents.
134823 */
134824 static void freeCursorConstraints(RtreeCursor *pCsr){
134825   if( pCsr->aConstraint ){
134826     int i;                        /* Used to iterate through constraint array */
134827     for(i=0; i<pCsr->nConstraint; i++){
134828       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
134829       if( pGeom ){
134830         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
134831         sqlite3_free(pGeom);
134832       }
134833     }
134834     sqlite3_free(pCsr->aConstraint);
134835     pCsr->aConstraint = 0;
134836   }
134837 }
134838 
134839 /*
134840 ** Rtree virtual table module xClose method.
134841 */
134842 static int rtreeClose(sqlite3_vtab_cursor *cur){
134843   Rtree *pRtree = (Rtree *)(cur->pVtab);
134844   int rc;
134845   RtreeCursor *pCsr = (RtreeCursor *)cur;
134846   freeCursorConstraints(pCsr);
134847   rc = nodeRelease(pRtree, pCsr->pNode);
134848   sqlite3_free(pCsr);
134849   return rc;
134850 }
134851 
134852 /*
134853 ** Rtree virtual table module xEof method.
134854 **
134855 ** Return non-zero if the cursor does not currently point to a valid
134856 ** record (i.e if the scan has finished), or zero otherwise.
134857 */
134858 static int rtreeEof(sqlite3_vtab_cursor *cur){
134859   RtreeCursor *pCsr = (RtreeCursor *)cur;
134860   return (pCsr->pNode==0);
134861 }
134862 
134863 /*
134864 ** The r-tree constraint passed as the second argument to this function is
134865 ** guaranteed to be a MATCH constraint.
134866 */
134867 static int testRtreeGeom(
134868   Rtree *pRtree,                  /* R-Tree object */
134869   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
134870   RtreeCell *pCell,               /* Cell to test */
134871   int *pbRes                      /* OUT: Test result */
134872 ){
134873   int i;
134874   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
134875   int nCoord = pRtree->nDim*2;
134876 
134877   assert( pConstraint->op==RTREE_MATCH );
134878   assert( pConstraint->pGeom );
134879 
134880   for(i=0; i<nCoord; i++){
134881     aCoord[i] = DCOORD(pCell->aCoord[i]);
134882   }
134883   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
134884 }
134885 
134886 /*
134887 ** Cursor pCursor currently points to a cell in a non-leaf page.
134888 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
134889 ** (excluded) by the constraints in the pCursor->aConstraint[]
134890 ** array, or false otherwise.
134891 **
134892 ** Return SQLITE_OK if successful or an SQLite error code if an error
134893 ** occurs within a geometry callback.
134894 */
134895 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
134896   RtreeCell cell;
134897   int ii;
134898   int bRes = 0;
134899   int rc = SQLITE_OK;
134900 
134901   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
134902   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
134903     RtreeConstraint *p = &pCursor->aConstraint[ii];
134904     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
134905     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
134906 
134907     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
134908         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
134909     );
134910 
134911     switch( p->op ){
134912       case RTREE_LE: case RTREE_LT:
134913         bRes = p->rValue<cell_min;
134914         break;
134915 
134916       case RTREE_GE: case RTREE_GT:
134917         bRes = p->rValue>cell_max;
134918         break;
134919 
134920       case RTREE_EQ:
134921         bRes = (p->rValue>cell_max || p->rValue<cell_min);
134922         break;
134923 
134924       default: {
134925         assert( p->op==RTREE_MATCH );
134926         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
134927         bRes = !bRes;
134928         break;
134929       }
134930     }
134931   }
134932 
134933   *pbEof = bRes;
134934   return rc;
134935 }
134936 
134937 /*
134938 ** Test if the cell that cursor pCursor currently points to
134939 ** would be filtered (excluded) by the constraints in the
134940 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
134941 ** returning. If the cell is not filtered (excluded) by the constraints,
134942 ** set pbEof to zero.
134943 **
134944 ** Return SQLITE_OK if successful or an SQLite error code if an error
134945 ** occurs within a geometry callback.
134946 **
134947 ** This function assumes that the cell is part of a leaf node.
134948 */
134949 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
134950   RtreeCell cell;
134951   int ii;
134952   *pbEof = 0;
134953 
134954   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
134955   for(ii=0; ii<pCursor->nConstraint; ii++){
134956     RtreeConstraint *p = &pCursor->aConstraint[ii];
134957     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
134958     int res;
134959     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
134960         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
134961     );
134962     switch( p->op ){
134963       case RTREE_LE: res = (coord<=p->rValue); break;
134964       case RTREE_LT: res = (coord<p->rValue);  break;
134965       case RTREE_GE: res = (coord>=p->rValue); break;
134966       case RTREE_GT: res = (coord>p->rValue);  break;
134967       case RTREE_EQ: res = (coord==p->rValue); break;
134968       default: {
134969         int rc;
134970         assert( p->op==RTREE_MATCH );
134971         rc = testRtreeGeom(pRtree, p, &cell, &res);
134972         if( rc!=SQLITE_OK ){
134973           return rc;
134974         }
134975         break;
134976       }
134977     }
134978 
134979     if( !res ){
134980       *pbEof = 1;
134981       return SQLITE_OK;
134982     }
134983   }
134984 
134985   return SQLITE_OK;
134986 }
134987 
134988 /*
134989 ** Cursor pCursor currently points at a node that heads a sub-tree of
134990 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
134991 ** to point to the left-most cell of the sub-tree that matches the
134992 ** configured constraints.
134993 */
134994 static int descendToCell(
134995   Rtree *pRtree,
134996   RtreeCursor *pCursor,
134997   int iHeight,
134998   int *pEof                 /* OUT: Set to true if cannot descend */
134999 ){
135000   int isEof;
135001   int rc;
135002   int ii;
135003   RtreeNode *pChild;
135004   sqlite3_int64 iRowid;
135005 
135006   RtreeNode *pSavedNode = pCursor->pNode;
135007   int iSavedCell = pCursor->iCell;
135008 
135009   assert( iHeight>=0 );
135010 
135011   if( iHeight==0 ){
135012     rc = testRtreeEntry(pRtree, pCursor, &isEof);
135013   }else{
135014     rc = testRtreeCell(pRtree, pCursor, &isEof);
135015   }
135016   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
135017     goto descend_to_cell_out;
135018   }
135019 
135020   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
135021   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
135022   if( rc!=SQLITE_OK ){
135023     goto descend_to_cell_out;
135024   }
135025 
135026   nodeRelease(pRtree, pCursor->pNode);
135027   pCursor->pNode = pChild;
135028   isEof = 1;
135029   for(ii=0; isEof && ii<NCELL(pChild); ii++){
135030     pCursor->iCell = ii;
135031     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
135032     if( rc!=SQLITE_OK ){
135033       goto descend_to_cell_out;
135034     }
135035   }
135036 
135037   if( isEof ){
135038     assert( pCursor->pNode==pChild );
135039     nodeReference(pSavedNode);
135040     nodeRelease(pRtree, pChild);
135041     pCursor->pNode = pSavedNode;
135042     pCursor->iCell = iSavedCell;
135043   }
135044 
135045 descend_to_cell_out:
135046   *pEof = isEof;
135047   return rc;
135048 }
135049 
135050 /*
135051 ** One of the cells in node pNode is guaranteed to have a 64-bit
135052 ** integer value equal to iRowid. Return the index of this cell.
135053 */
135054 static int nodeRowidIndex(
135055   Rtree *pRtree,
135056   RtreeNode *pNode,
135057   i64 iRowid,
135058   int *piIndex
135059 ){
135060   int ii;
135061   int nCell = NCELL(pNode);
135062   for(ii=0; ii<nCell; ii++){
135063     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
135064       *piIndex = ii;
135065       return SQLITE_OK;
135066     }
135067   }
135068   return SQLITE_CORRUPT_VTAB;
135069 }
135070 
135071 /*
135072 ** Return the index of the cell containing a pointer to node pNode
135073 ** in its parent. If pNode is the root node, return -1.
135074 */
135075 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
135076   RtreeNode *pParent = pNode->pParent;
135077   if( pParent ){
135078     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
135079   }
135080   *piIndex = -1;
135081   return SQLITE_OK;
135082 }
135083 
135084 /*
135085 ** Rtree virtual table module xNext method.
135086 */
135087 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
135088   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
135089   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135090   int rc = SQLITE_OK;
135091 
135092   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
135093   ** already at EOF. It is against the rules to call the xNext() method of
135094   ** a cursor that has already reached EOF.
135095   */
135096   assert( pCsr->pNode );
135097 
135098   if( pCsr->iStrategy==1 ){
135099     /* This "scan" is a direct lookup by rowid. There is no next entry. */
135100     nodeRelease(pRtree, pCsr->pNode);
135101     pCsr->pNode = 0;
135102   }else{
135103     /* Move to the next entry that matches the configured constraints. */
135104     int iHeight = 0;
135105     while( pCsr->pNode ){
135106       RtreeNode *pNode = pCsr->pNode;
135107       int nCell = NCELL(pNode);
135108       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
135109         int isEof;
135110         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
135111         if( rc!=SQLITE_OK || !isEof ){
135112           return rc;
135113         }
135114       }
135115       pCsr->pNode = pNode->pParent;
135116       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
135117       if( rc!=SQLITE_OK ){
135118         return rc;
135119       }
135120       nodeReference(pCsr->pNode);
135121       nodeRelease(pRtree, pNode);
135122       iHeight++;
135123     }
135124   }
135125 
135126   return rc;
135127 }
135128 
135129 /*
135130 ** Rtree virtual table module xRowid method.
135131 */
135132 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
135133   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
135134   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135135 
135136   assert(pCsr->pNode);
135137   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
135138 
135139   return SQLITE_OK;
135140 }
135141 
135142 /*
135143 ** Rtree virtual table module xColumn method.
135144 */
135145 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
135146   Rtree *pRtree = (Rtree *)cur->pVtab;
135147   RtreeCursor *pCsr = (RtreeCursor *)cur;
135148 
135149   if( i==0 ){
135150     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
135151     sqlite3_result_int64(ctx, iRowid);
135152   }else{
135153     RtreeCoord c;
135154     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
135155 #ifndef SQLITE_RTREE_INT_ONLY
135156     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135157       sqlite3_result_double(ctx, c.f);
135158     }else
135159 #endif
135160     {
135161       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
135162       sqlite3_result_int(ctx, c.i);
135163     }
135164   }
135165 
135166   return SQLITE_OK;
135167 }
135168 
135169 /*
135170 ** Use nodeAcquire() to obtain the leaf node containing the record with
135171 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
135172 ** return SQLITE_OK. If there is no such record in the table, set
135173 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
135174 ** to zero and return an SQLite error code.
135175 */
135176 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
135177   int rc;
135178   *ppLeaf = 0;
135179   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
135180   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
135181     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
135182     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
135183     sqlite3_reset(pRtree->pReadRowid);
135184   }else{
135185     rc = sqlite3_reset(pRtree->pReadRowid);
135186   }
135187   return rc;
135188 }
135189 
135190 /*
135191 ** This function is called to configure the RtreeConstraint object passed
135192 ** as the second argument for a MATCH constraint. The value passed as the
135193 ** first argument to this function is the right-hand operand to the MATCH
135194 ** operator.
135195 */
135196 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
135197   RtreeMatchArg *p;
135198   sqlite3_rtree_geometry *pGeom;
135199   int nBlob;
135200 
135201   /* Check that value is actually a blob. */
135202   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
135203 
135204   /* Check that the blob is roughly the right size. */
135205   nBlob = sqlite3_value_bytes(pValue);
135206   if( nBlob<(int)sizeof(RtreeMatchArg)
135207    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
135208   ){
135209     return SQLITE_ERROR;
135210   }
135211 
135212   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
135213       sizeof(sqlite3_rtree_geometry) + nBlob
135214   );
135215   if( !pGeom ) return SQLITE_NOMEM;
135216   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
135217   p = (RtreeMatchArg *)&pGeom[1];
135218 
135219   memcpy(p, sqlite3_value_blob(pValue), nBlob);
135220   if( p->magic!=RTREE_GEOMETRY_MAGIC
135221    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
135222   ){
135223     sqlite3_free(pGeom);
135224     return SQLITE_ERROR;
135225   }
135226 
135227   pGeom->pContext = p->pContext;
135228   pGeom->nParam = p->nParam;
135229   pGeom->aParam = p->aParam;
135230 
135231   pCons->xGeom = p->xGeom;
135232   pCons->pGeom = pGeom;
135233   return SQLITE_OK;
135234 }
135235 
135236 /*
135237 ** Rtree virtual table module xFilter method.
135238 */
135239 static int rtreeFilter(
135240   sqlite3_vtab_cursor *pVtabCursor,
135241   int idxNum, const char *idxStr,
135242   int argc, sqlite3_value **argv
135243 ){
135244   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
135245   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
135246 
135247   RtreeNode *pRoot = 0;
135248   int ii;
135249   int rc = SQLITE_OK;
135250 
135251   rtreeReference(pRtree);
135252 
135253   freeCursorConstraints(pCsr);
135254   pCsr->iStrategy = idxNum;
135255 
135256   if( idxNum==1 ){
135257     /* Special case - lookup by rowid. */
135258     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
135259     i64 iRowid = sqlite3_value_int64(argv[0]);
135260     rc = findLeafNode(pRtree, iRowid, &pLeaf);
135261     pCsr->pNode = pLeaf;
135262     if( pLeaf ){
135263       assert( rc==SQLITE_OK );
135264       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
135265     }
135266   }else{
135267     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
135268     ** with the configured constraints.
135269     */
135270     if( argc>0 ){
135271       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
135272       pCsr->nConstraint = argc;
135273       if( !pCsr->aConstraint ){
135274         rc = SQLITE_NOMEM;
135275       }else{
135276         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
135277         assert( (idxStr==0 && argc==0)
135278                 || (idxStr && (int)strlen(idxStr)==argc*2) );
135279         for(ii=0; ii<argc; ii++){
135280           RtreeConstraint *p = &pCsr->aConstraint[ii];
135281           p->op = idxStr[ii*2];
135282           p->iCoord = idxStr[ii*2+1]-'a';
135283           if( p->op==RTREE_MATCH ){
135284             /* A MATCH operator. The right-hand-side must be a blob that
135285             ** can be cast into an RtreeMatchArg object. One created using
135286             ** an sqlite3_rtree_geometry_callback() SQL user function.
135287             */
135288             rc = deserializeGeometry(argv[ii], p);
135289             if( rc!=SQLITE_OK ){
135290               break;
135291             }
135292           }else{
135293 #ifdef SQLITE_RTREE_INT_ONLY
135294             p->rValue = sqlite3_value_int64(argv[ii]);
135295 #else
135296             p->rValue = sqlite3_value_double(argv[ii]);
135297 #endif
135298           }
135299         }
135300       }
135301     }
135302 
135303     if( rc==SQLITE_OK ){
135304       pCsr->pNode = 0;
135305       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
135306     }
135307     if( rc==SQLITE_OK ){
135308       int isEof = 1;
135309       int nCell = NCELL(pRoot);
135310       pCsr->pNode = pRoot;
135311       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
135312         assert( pCsr->pNode==pRoot );
135313         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
135314         if( !isEof ){
135315           break;
135316         }
135317       }
135318       if( rc==SQLITE_OK && isEof ){
135319         assert( pCsr->pNode==pRoot );
135320         nodeRelease(pRtree, pRoot);
135321         pCsr->pNode = 0;
135322       }
135323       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
135324     }
135325   }
135326 
135327   rtreeRelease(pRtree);
135328   return rc;
135329 }
135330 
135331 /*
135332 ** Rtree virtual table module xBestIndex method. There are three
135333 ** table scan strategies to choose from (in order from most to
135334 ** least desirable):
135335 **
135336 **   idxNum     idxStr        Strategy
135337 **   ------------------------------------------------
135338 **     1        Unused        Direct lookup by rowid.
135339 **     2        See below     R-tree query or full-table scan.
135340 **   ------------------------------------------------
135341 **
135342 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
135343 ** 2 is used, idxStr is formatted to contain 2 bytes for each
135344 ** constraint used. The first two bytes of idxStr correspond to
135345 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
135346 ** (argvIndex==1) etc.
135347 **
135348 ** The first of each pair of bytes in idxStr identifies the constraint
135349 ** operator as follows:
135350 **
135351 **   Operator    Byte Value
135352 **   ----------------------
135353 **      =        0x41 ('A')
135354 **     <=        0x42 ('B')
135355 **      <        0x43 ('C')
135356 **     >=        0x44 ('D')
135357 **      >        0x45 ('E')
135358 **   MATCH       0x46 ('F')
135359 **   ----------------------
135360 **
135361 ** The second of each pair of bytes identifies the coordinate column
135362 ** to which the constraint applies. The leftmost coordinate column
135363 ** is 'a', the second from the left 'b' etc.
135364 */
135365 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
135366   int rc = SQLITE_OK;
135367   int ii;
135368 
135369   int iIdx = 0;
135370   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
135371   memset(zIdxStr, 0, sizeof(zIdxStr));
135372   UNUSED_PARAMETER(tab);
135373 
135374   assert( pIdxInfo->idxStr==0 );
135375   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
135376     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
135377 
135378     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
135379       /* We have an equality constraint on the rowid. Use strategy 1. */
135380       int jj;
135381       for(jj=0; jj<ii; jj++){
135382         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
135383         pIdxInfo->aConstraintUsage[jj].omit = 0;
135384       }
135385       pIdxInfo->idxNum = 1;
135386       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
135387       pIdxInfo->aConstraintUsage[jj].omit = 1;
135388 
135389       /* This strategy involves a two rowid lookups on an B-Tree structures
135390       ** and then a linear search of an R-Tree node. This should be
135391       ** considered almost as quick as a direct rowid lookup (for which
135392       ** sqlite uses an internal cost of 0.0).
135393       */
135394       pIdxInfo->estimatedCost = 10.0;
135395       return SQLITE_OK;
135396     }
135397 
135398     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
135399       u8 op;
135400       switch( p->op ){
135401         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
135402         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
135403         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
135404         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
135405         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
135406         default:
135407           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
135408           op = RTREE_MATCH;
135409           break;
135410       }
135411       zIdxStr[iIdx++] = op;
135412       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
135413       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
135414       pIdxInfo->aConstraintUsage[ii].omit = 1;
135415     }
135416   }
135417 
135418   pIdxInfo->idxNum = 2;
135419   pIdxInfo->needToFreeIdxStr = 1;
135420   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
135421     return SQLITE_NOMEM;
135422   }
135423   assert( iIdx>=0 );
135424   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
135425   return rc;
135426 }
135427 
135428 /*
135429 ** Return the N-dimensional volumn of the cell stored in *p.
135430 */
135431 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
135432   RtreeDValue area = (RtreeDValue)1;
135433   int ii;
135434   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135435     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
135436   }
135437   return area;
135438 }
135439 
135440 /*
135441 ** Return the margin length of cell p. The margin length is the sum
135442 ** of the objects size in each dimension.
135443 */
135444 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
135445   RtreeDValue margin = (RtreeDValue)0;
135446   int ii;
135447   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135448     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
135449   }
135450   return margin;
135451 }
135452 
135453 /*
135454 ** Store the union of cells p1 and p2 in p1.
135455 */
135456 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
135457   int ii;
135458   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
135459     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135460       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
135461       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
135462     }
135463   }else{
135464     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135465       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
135466       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
135467     }
135468   }
135469 }
135470 
135471 /*
135472 ** Return true if the area covered by p2 is a subset of the area covered
135473 ** by p1. False otherwise.
135474 */
135475 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
135476   int ii;
135477   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
135478   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
135479     RtreeCoord *a1 = &p1->aCoord[ii];
135480     RtreeCoord *a2 = &p2->aCoord[ii];
135481     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
135482      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
135483     ){
135484       return 0;
135485     }
135486   }
135487   return 1;
135488 }
135489 
135490 /*
135491 ** Return the amount cell p would grow by if it were unioned with pCell.
135492 */
135493 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
135494   RtreeDValue area;
135495   RtreeCell cell;
135496   memcpy(&cell, p, sizeof(RtreeCell));
135497   area = cellArea(pRtree, &cell);
135498   cellUnion(pRtree, &cell, pCell);
135499   return (cellArea(pRtree, &cell)-area);
135500 }
135501 
135502 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
135503 static RtreeDValue cellOverlap(
135504   Rtree *pRtree,
135505   RtreeCell *p,
135506   RtreeCell *aCell,
135507   int nCell,
135508   int iExclude
135509 ){
135510   int ii;
135511   RtreeDValue overlap = 0.0;
135512   for(ii=0; ii<nCell; ii++){
135513 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135514     if( ii!=iExclude )
135515 #else
135516     assert( iExclude==-1 );
135517     UNUSED_PARAMETER(iExclude);
135518 #endif
135519     {
135520       int jj;
135521       RtreeDValue o = (RtreeDValue)1;
135522       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
135523         RtreeDValue x1, x2;
135524 
135525         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
135526         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
135527 
135528         if( x2<x1 ){
135529           o = 0.0;
135530           break;
135531         }else{
135532           o = o * (x2-x1);
135533         }
135534       }
135535       overlap += o;
135536     }
135537   }
135538   return overlap;
135539 }
135540 #endif
135541 
135542 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135543 static RtreeDValue cellOverlapEnlargement(
135544   Rtree *pRtree,
135545   RtreeCell *p,
135546   RtreeCell *pInsert,
135547   RtreeCell *aCell,
135548   int nCell,
135549   int iExclude
135550 ){
135551   RtreeDValue before, after;
135552   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
135553   cellUnion(pRtree, p, pInsert);
135554   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
135555   return (after-before);
135556 }
135557 #endif
135558 
135559 
135560 /*
135561 ** This function implements the ChooseLeaf algorithm from Gutman[84].
135562 ** ChooseSubTree in r*tree terminology.
135563 */
135564 static int ChooseLeaf(
135565   Rtree *pRtree,               /* Rtree table */
135566   RtreeCell *pCell,            /* Cell to insert into rtree */
135567   int iHeight,                 /* Height of sub-tree rooted at pCell */
135568   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
135569 ){
135570   int rc;
135571   int ii;
135572   RtreeNode *pNode;
135573   rc = nodeAcquire(pRtree, 1, 0, &pNode);
135574 
135575   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
135576     int iCell;
135577     sqlite3_int64 iBest = 0;
135578 
135579     RtreeDValue fMinGrowth = 0.0;
135580     RtreeDValue fMinArea = 0.0;
135581 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135582     RtreeDValue fMinOverlap = 0.0;
135583     RtreeDValue overlap;
135584 #endif
135585 
135586     int nCell = NCELL(pNode);
135587     RtreeCell cell;
135588     RtreeNode *pChild;
135589 
135590     RtreeCell *aCell = 0;
135591 
135592 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135593     if( ii==(pRtree->iDepth-1) ){
135594       int jj;
135595       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
135596       if( !aCell ){
135597         rc = SQLITE_NOMEM;
135598         nodeRelease(pRtree, pNode);
135599         pNode = 0;
135600         continue;
135601       }
135602       for(jj=0; jj<nCell; jj++){
135603         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
135604       }
135605     }
135606 #endif
135607 
135608     /* Select the child node which will be enlarged the least if pCell
135609     ** is inserted into it. Resolve ties by choosing the entry with
135610     ** the smallest area.
135611     */
135612     for(iCell=0; iCell<nCell; iCell++){
135613       int bBest = 0;
135614       RtreeDValue growth;
135615       RtreeDValue area;
135616       nodeGetCell(pRtree, pNode, iCell, &cell);
135617       growth = cellGrowth(pRtree, &cell, pCell);
135618       area = cellArea(pRtree, &cell);
135619 
135620 #if VARIANT_RSTARTREE_CHOOSESUBTREE
135621       if( ii==(pRtree->iDepth-1) ){
135622         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
135623       }else{
135624         overlap = 0.0;
135625       }
135626       if( (iCell==0)
135627        || (overlap<fMinOverlap)
135628        || (overlap==fMinOverlap && growth<fMinGrowth)
135629        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
135630       ){
135631         bBest = 1;
135632         fMinOverlap = overlap;
135633       }
135634 #else
135635       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
135636         bBest = 1;
135637       }
135638 #endif
135639       if( bBest ){
135640         fMinGrowth = growth;
135641         fMinArea = area;
135642         iBest = cell.iRowid;
135643       }
135644     }
135645 
135646     sqlite3_free(aCell);
135647     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
135648     nodeRelease(pRtree, pNode);
135649     pNode = pChild;
135650   }
135651 
135652   *ppLeaf = pNode;
135653   return rc;
135654 }
135655 
135656 /*
135657 ** A cell with the same content as pCell has just been inserted into
135658 ** the node pNode. This function updates the bounding box cells in
135659 ** all ancestor elements.
135660 */
135661 static int AdjustTree(
135662   Rtree *pRtree,                    /* Rtree table */
135663   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
135664   RtreeCell *pCell                  /* This cell was just inserted */
135665 ){
135666   RtreeNode *p = pNode;
135667   while( p->pParent ){
135668     RtreeNode *pParent = p->pParent;
135669     RtreeCell cell;
135670     int iCell;
135671 
135672     if( nodeParentIndex(pRtree, p, &iCell) ){
135673       return SQLITE_CORRUPT_VTAB;
135674     }
135675 
135676     nodeGetCell(pRtree, pParent, iCell, &cell);
135677     if( !cellContains(pRtree, &cell, pCell) ){
135678       cellUnion(pRtree, &cell, pCell);
135679       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
135680     }
135681 
135682     p = pParent;
135683   }
135684   return SQLITE_OK;
135685 }
135686 
135687 /*
135688 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
135689 */
135690 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
135691   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
135692   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
135693   sqlite3_step(pRtree->pWriteRowid);
135694   return sqlite3_reset(pRtree->pWriteRowid);
135695 }
135696 
135697 /*
135698 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
135699 */
135700 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
135701   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
135702   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
135703   sqlite3_step(pRtree->pWriteParent);
135704   return sqlite3_reset(pRtree->pWriteParent);
135705 }
135706 
135707 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
135708 
135709 #if VARIANT_GUTTMAN_LINEAR_SPLIT
135710 /*
135711 ** Implementation of the linear variant of the PickNext() function from
135712 ** Guttman[84].
135713 */
135714 static RtreeCell *LinearPickNext(
135715   Rtree *pRtree,
135716   RtreeCell *aCell,
135717   int nCell,
135718   RtreeCell *pLeftBox,
135719   RtreeCell *pRightBox,
135720   int *aiUsed
135721 ){
135722   int ii;
135723   for(ii=0; aiUsed[ii]; ii++);
135724   aiUsed[ii] = 1;
135725   return &aCell[ii];
135726 }
135727 
135728 /*
135729 ** Implementation of the linear variant of the PickSeeds() function from
135730 ** Guttman[84].
135731 */
135732 static void LinearPickSeeds(
135733   Rtree *pRtree,
135734   RtreeCell *aCell,
135735   int nCell,
135736   int *piLeftSeed,
135737   int *piRightSeed
135738 ){
135739   int i;
135740   int iLeftSeed = 0;
135741   int iRightSeed = 1;
135742   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
135743 
135744   /* Pick two "seed" cells from the array of cells. The algorithm used
135745   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
135746   ** indices of the two seed cells in the array are stored in local
135747   ** variables iLeftSeek and iRightSeed.
135748   */
135749   for(i=0; i<pRtree->nDim; i++){
135750     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
135751     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
135752     RtreeDValue x3 = x1;
135753     RtreeDValue x4 = x2;
135754     int jj;
135755 
135756     int iCellLeft = 0;
135757     int iCellRight = 0;
135758 
135759     for(jj=1; jj<nCell; jj++){
135760       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
135761       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
135762 
135763       if( left<x1 ) x1 = left;
135764       if( right>x4 ) x4 = right;
135765       if( left>x3 ){
135766         x3 = left;
135767         iCellRight = jj;
135768       }
135769       if( right<x2 ){
135770         x2 = right;
135771         iCellLeft = jj;
135772       }
135773     }
135774 
135775     if( x4!=x1 ){
135776       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
135777       if( normalwidth>maxNormalInnerWidth ){
135778         iLeftSeed = iCellLeft;
135779         iRightSeed = iCellRight;
135780       }
135781     }
135782   }
135783 
135784   *piLeftSeed = iLeftSeed;
135785   *piRightSeed = iRightSeed;
135786 }
135787 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
135788 
135789 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
135790 /*
135791 ** Implementation of the quadratic variant of the PickNext() function from
135792 ** Guttman[84].
135793 */
135794 static RtreeCell *QuadraticPickNext(
135795   Rtree *pRtree,
135796   RtreeCell *aCell,
135797   int nCell,
135798   RtreeCell *pLeftBox,
135799   RtreeCell *pRightBox,
135800   int *aiUsed
135801 ){
135802   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
135803 
135804   int iSelect = -1;
135805   RtreeDValue fDiff;
135806   int ii;
135807   for(ii=0; ii<nCell; ii++){
135808     if( aiUsed[ii]==0 ){
135809       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135810       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
135811       RtreeDValue diff = FABS(right-left);
135812       if( iSelect<0 || diff>fDiff ){
135813         fDiff = diff;
135814         iSelect = ii;
135815       }
135816     }
135817   }
135818   aiUsed[iSelect] = 1;
135819   return &aCell[iSelect];
135820 }
135821 
135822 /*
135823 ** Implementation of the quadratic variant of the PickSeeds() function from
135824 ** Guttman[84].
135825 */
135826 static void QuadraticPickSeeds(
135827   Rtree *pRtree,
135828   RtreeCell *aCell,
135829   int nCell,
135830   int *piLeftSeed,
135831   int *piRightSeed
135832 ){
135833   int ii;
135834   int jj;
135835 
135836   int iLeftSeed = 0;
135837   int iRightSeed = 1;
135838   RtreeDValue fWaste = 0.0;
135839 
135840   for(ii=0; ii<nCell; ii++){
135841     for(jj=ii+1; jj<nCell; jj++){
135842       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
135843       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
135844       RtreeDValue waste = growth - right;
135845 
135846       if( waste>fWaste ){
135847         iLeftSeed = ii;
135848         iRightSeed = jj;
135849         fWaste = waste;
135850       }
135851     }
135852   }
135853 
135854   *piLeftSeed = iLeftSeed;
135855   *piRightSeed = iRightSeed;
135856 }
135857 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
135858 
135859 /*
135860 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
135861 ** nIdx. The aIdx array contains the set of integers from 0 to
135862 ** (nIdx-1) in no particular order. This function sorts the values
135863 ** in aIdx according to the indexed values in aDistance. For
135864 ** example, assuming the inputs:
135865 **
135866 **   aIdx      = { 0,   1,   2,   3 }
135867 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
135868 **
135869 ** this function sets the aIdx array to contain:
135870 **
135871 **   aIdx      = { 0,   1,   2,   3 }
135872 **
135873 ** The aSpare array is used as temporary working space by the
135874 ** sorting algorithm.
135875 */
135876 static void SortByDistance(
135877   int *aIdx,
135878   int nIdx,
135879   RtreeDValue *aDistance,
135880   int *aSpare
135881 ){
135882   if( nIdx>1 ){
135883     int iLeft = 0;
135884     int iRight = 0;
135885 
135886     int nLeft = nIdx/2;
135887     int nRight = nIdx-nLeft;
135888     int *aLeft = aIdx;
135889     int *aRight = &aIdx[nLeft];
135890 
135891     SortByDistance(aLeft, nLeft, aDistance, aSpare);
135892     SortByDistance(aRight, nRight, aDistance, aSpare);
135893 
135894     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
135895     aLeft = aSpare;
135896 
135897     while( iLeft<nLeft || iRight<nRight ){
135898       if( iLeft==nLeft ){
135899         aIdx[iLeft+iRight] = aRight[iRight];
135900         iRight++;
135901       }else if( iRight==nRight ){
135902         aIdx[iLeft+iRight] = aLeft[iLeft];
135903         iLeft++;
135904       }else{
135905         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
135906         RtreeDValue fRight = aDistance[aRight[iRight]];
135907         if( fLeft<fRight ){
135908           aIdx[iLeft+iRight] = aLeft[iLeft];
135909           iLeft++;
135910         }else{
135911           aIdx[iLeft+iRight] = aRight[iRight];
135912           iRight++;
135913         }
135914       }
135915     }
135916 
135917 #if 0
135918     /* Check that the sort worked */
135919     {
135920       int jj;
135921       for(jj=1; jj<nIdx; jj++){
135922         RtreeDValue left = aDistance[aIdx[jj-1]];
135923         RtreeDValue right = aDistance[aIdx[jj]];
135924         assert( left<=right );
135925       }
135926     }
135927 #endif
135928   }
135929 }
135930 
135931 /*
135932 ** Arguments aIdx, aCell and aSpare all point to arrays of size
135933 ** nIdx. The aIdx array contains the set of integers from 0 to
135934 ** (nIdx-1) in no particular order. This function sorts the values
135935 ** in aIdx according to dimension iDim of the cells in aCell. The
135936 ** minimum value of dimension iDim is considered first, the
135937 ** maximum used to break ties.
135938 **
135939 ** The aSpare array is used as temporary working space by the
135940 ** sorting algorithm.
135941 */
135942 static void SortByDimension(
135943   Rtree *pRtree,
135944   int *aIdx,
135945   int nIdx,
135946   int iDim,
135947   RtreeCell *aCell,
135948   int *aSpare
135949 ){
135950   if( nIdx>1 ){
135951 
135952     int iLeft = 0;
135953     int iRight = 0;
135954 
135955     int nLeft = nIdx/2;
135956     int nRight = nIdx-nLeft;
135957     int *aLeft = aIdx;
135958     int *aRight = &aIdx[nLeft];
135959 
135960     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
135961     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
135962 
135963     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
135964     aLeft = aSpare;
135965     while( iLeft<nLeft || iRight<nRight ){
135966       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
135967       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
135968       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
135969       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
135970       if( (iLeft!=nLeft) && ((iRight==nRight)
135971        || (xleft1<xright1)
135972        || (xleft1==xright1 && xleft2<xright2)
135973       )){
135974         aIdx[iLeft+iRight] = aLeft[iLeft];
135975         iLeft++;
135976       }else{
135977         aIdx[iLeft+iRight] = aRight[iRight];
135978         iRight++;
135979       }
135980     }
135981 
135982 #if 0
135983     /* Check that the sort worked */
135984     {
135985       int jj;
135986       for(jj=1; jj<nIdx; jj++){
135987         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
135988         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
135989         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
135990         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
135991         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
135992       }
135993     }
135994 #endif
135995   }
135996 }
135997 
135998 #if VARIANT_RSTARTREE_SPLIT
135999 /*
136000 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
136001 */
136002 static int splitNodeStartree(
136003   Rtree *pRtree,
136004   RtreeCell *aCell,
136005   int nCell,
136006   RtreeNode *pLeft,
136007   RtreeNode *pRight,
136008   RtreeCell *pBboxLeft,
136009   RtreeCell *pBboxRight
136010 ){
136011   int **aaSorted;
136012   int *aSpare;
136013   int ii;
136014 
136015   int iBestDim = 0;
136016   int iBestSplit = 0;
136017   RtreeDValue fBestMargin = 0.0;
136018 
136019   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
136020 
136021   aaSorted = (int **)sqlite3_malloc(nByte);
136022   if( !aaSorted ){
136023     return SQLITE_NOMEM;
136024   }
136025 
136026   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
136027   memset(aaSorted, 0, nByte);
136028   for(ii=0; ii<pRtree->nDim; ii++){
136029     int jj;
136030     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
136031     for(jj=0; jj<nCell; jj++){
136032       aaSorted[ii][jj] = jj;
136033     }
136034     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
136035   }
136036 
136037   for(ii=0; ii<pRtree->nDim; ii++){
136038     RtreeDValue margin = 0.0;
136039     RtreeDValue fBestOverlap = 0.0;
136040     RtreeDValue fBestArea = 0.0;
136041     int iBestLeft = 0;
136042     int nLeft;
136043 
136044     for(
136045       nLeft=RTREE_MINCELLS(pRtree);
136046       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
136047       nLeft++
136048     ){
136049       RtreeCell left;
136050       RtreeCell right;
136051       int kk;
136052       RtreeDValue overlap;
136053       RtreeDValue area;
136054 
136055       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
136056       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
136057       for(kk=1; kk<(nCell-1); kk++){
136058         if( kk<nLeft ){
136059           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
136060         }else{
136061           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
136062         }
136063       }
136064       margin += cellMargin(pRtree, &left);
136065       margin += cellMargin(pRtree, &right);
136066       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
136067       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
136068       if( (nLeft==RTREE_MINCELLS(pRtree))
136069        || (overlap<fBestOverlap)
136070        || (overlap==fBestOverlap && area<fBestArea)
136071       ){
136072         iBestLeft = nLeft;
136073         fBestOverlap = overlap;
136074         fBestArea = area;
136075       }
136076     }
136077 
136078     if( ii==0 || margin<fBestMargin ){
136079       iBestDim = ii;
136080       fBestMargin = margin;
136081       iBestSplit = iBestLeft;
136082     }
136083   }
136084 
136085   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
136086   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
136087   for(ii=0; ii<nCell; ii++){
136088     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
136089     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
136090     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
136091     nodeInsertCell(pRtree, pTarget, pCell);
136092     cellUnion(pRtree, pBbox, pCell);
136093   }
136094 
136095   sqlite3_free(aaSorted);
136096   return SQLITE_OK;
136097 }
136098 #endif
136099 
136100 #if VARIANT_GUTTMAN_SPLIT
136101 /*
136102 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
136103 */
136104 static int splitNodeGuttman(
136105   Rtree *pRtree,
136106   RtreeCell *aCell,
136107   int nCell,
136108   RtreeNode *pLeft,
136109   RtreeNode *pRight,
136110   RtreeCell *pBboxLeft,
136111   RtreeCell *pBboxRight
136112 ){
136113   int iLeftSeed = 0;
136114   int iRightSeed = 1;
136115   int *aiUsed;
136116   int i;
136117 
136118   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
136119   if( !aiUsed ){
136120     return SQLITE_NOMEM;
136121   }
136122   memset(aiUsed, 0, sizeof(int)*nCell);
136123 
136124   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
136125 
136126   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
136127   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
136128   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
136129   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
136130   aiUsed[iLeftSeed] = 1;
136131   aiUsed[iRightSeed] = 1;
136132 
136133   for(i=nCell-2; i>0; i--){
136134     RtreeCell *pNext;
136135     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
136136     RtreeDValue diff =
136137       cellGrowth(pRtree, pBboxLeft, pNext) -
136138       cellGrowth(pRtree, pBboxRight, pNext)
136139     ;
136140     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
136141      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
136142     ){
136143       nodeInsertCell(pRtree, pRight, pNext);
136144       cellUnion(pRtree, pBboxRight, pNext);
136145     }else{
136146       nodeInsertCell(pRtree, pLeft, pNext);
136147       cellUnion(pRtree, pBboxLeft, pNext);
136148     }
136149   }
136150 
136151   sqlite3_free(aiUsed);
136152   return SQLITE_OK;
136153 }
136154 #endif
136155 
136156 static int updateMapping(
136157   Rtree *pRtree,
136158   i64 iRowid,
136159   RtreeNode *pNode,
136160   int iHeight
136161 ){
136162   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
136163   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
136164   if( iHeight>0 ){
136165     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
136166     if( pChild ){
136167       nodeRelease(pRtree, pChild->pParent);
136168       nodeReference(pNode);
136169       pChild->pParent = pNode;
136170     }
136171   }
136172   return xSetMapping(pRtree, iRowid, pNode->iNode);
136173 }
136174 
136175 static int SplitNode(
136176   Rtree *pRtree,
136177   RtreeNode *pNode,
136178   RtreeCell *pCell,
136179   int iHeight
136180 ){
136181   int i;
136182   int newCellIsRight = 0;
136183 
136184   int rc = SQLITE_OK;
136185   int nCell = NCELL(pNode);
136186   RtreeCell *aCell;
136187   int *aiUsed;
136188 
136189   RtreeNode *pLeft = 0;
136190   RtreeNode *pRight = 0;
136191 
136192   RtreeCell leftbbox;
136193   RtreeCell rightbbox;
136194 
136195   /* Allocate an array and populate it with a copy of pCell and
136196   ** all cells from node pLeft. Then zero the original node.
136197   */
136198   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
136199   if( !aCell ){
136200     rc = SQLITE_NOMEM;
136201     goto splitnode_out;
136202   }
136203   aiUsed = (int *)&aCell[nCell+1];
136204   memset(aiUsed, 0, sizeof(int)*(nCell+1));
136205   for(i=0; i<nCell; i++){
136206     nodeGetCell(pRtree, pNode, i, &aCell[i]);
136207   }
136208   nodeZero(pRtree, pNode);
136209   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
136210   nCell++;
136211 
136212   if( pNode->iNode==1 ){
136213     pRight = nodeNew(pRtree, pNode);
136214     pLeft = nodeNew(pRtree, pNode);
136215     pRtree->iDepth++;
136216     pNode->isDirty = 1;
136217     writeInt16(pNode->zData, pRtree->iDepth);
136218   }else{
136219     pLeft = pNode;
136220     pRight = nodeNew(pRtree, pLeft->pParent);
136221     nodeReference(pLeft);
136222   }
136223 
136224   if( !pLeft || !pRight ){
136225     rc = SQLITE_NOMEM;
136226     goto splitnode_out;
136227   }
136228 
136229   memset(pLeft->zData, 0, pRtree->iNodeSize);
136230   memset(pRight->zData, 0, pRtree->iNodeSize);
136231 
136232   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
136233   if( rc!=SQLITE_OK ){
136234     goto splitnode_out;
136235   }
136236 
136237   /* Ensure both child nodes have node numbers assigned to them by calling
136238   ** nodeWrite(). Node pRight always needs a node number, as it was created
136239   ** by nodeNew() above. But node pLeft sometimes already has a node number.
136240   ** In this case avoid the all to nodeWrite().
136241   */
136242   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
136243    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
136244   ){
136245     goto splitnode_out;
136246   }
136247 
136248   rightbbox.iRowid = pRight->iNode;
136249   leftbbox.iRowid = pLeft->iNode;
136250 
136251   if( pNode->iNode==1 ){
136252     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
136253     if( rc!=SQLITE_OK ){
136254       goto splitnode_out;
136255     }
136256   }else{
136257     RtreeNode *pParent = pLeft->pParent;
136258     int iCell;
136259     rc = nodeParentIndex(pRtree, pLeft, &iCell);
136260     if( rc==SQLITE_OK ){
136261       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
136262       rc = AdjustTree(pRtree, pParent, &leftbbox);
136263     }
136264     if( rc!=SQLITE_OK ){
136265       goto splitnode_out;
136266     }
136267   }
136268   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
136269     goto splitnode_out;
136270   }
136271 
136272   for(i=0; i<NCELL(pRight); i++){
136273     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
136274     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
136275     if( iRowid==pCell->iRowid ){
136276       newCellIsRight = 1;
136277     }
136278     if( rc!=SQLITE_OK ){
136279       goto splitnode_out;
136280     }
136281   }
136282   if( pNode->iNode==1 ){
136283     for(i=0; i<NCELL(pLeft); i++){
136284       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
136285       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
136286       if( rc!=SQLITE_OK ){
136287         goto splitnode_out;
136288       }
136289     }
136290   }else if( newCellIsRight==0 ){
136291     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
136292   }
136293 
136294   if( rc==SQLITE_OK ){
136295     rc = nodeRelease(pRtree, pRight);
136296     pRight = 0;
136297   }
136298   if( rc==SQLITE_OK ){
136299     rc = nodeRelease(pRtree, pLeft);
136300     pLeft = 0;
136301   }
136302 
136303 splitnode_out:
136304   nodeRelease(pRtree, pRight);
136305   nodeRelease(pRtree, pLeft);
136306   sqlite3_free(aCell);
136307   return rc;
136308 }
136309 
136310 /*
136311 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
136312 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
136313 ** the pLeaf->pParent chain all the way up to the root node.
136314 **
136315 ** This operation is required when a row is deleted (or updated - an update
136316 ** is implemented as a delete followed by an insert). SQLite provides the
136317 ** rowid of the row to delete, which can be used to find the leaf on which
136318 ** the entry resides (argument pLeaf). Once the leaf is located, this
136319 ** function is called to determine its ancestry.
136320 */
136321 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
136322   int rc = SQLITE_OK;
136323   RtreeNode *pChild = pLeaf;
136324   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
136325     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
136326     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
136327     rc = sqlite3_step(pRtree->pReadParent);
136328     if( rc==SQLITE_ROW ){
136329       RtreeNode *pTest;           /* Used to test for reference loops */
136330       i64 iNode;                  /* Node number of parent node */
136331 
136332       /* Before setting pChild->pParent, test that we are not creating a
136333       ** loop of references (as we would if, say, pChild==pParent). We don't
136334       ** want to do this as it leads to a memory leak when trying to delete
136335       ** the referenced counted node structures.
136336       */
136337       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
136338       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
136339       if( !pTest ){
136340         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
136341       }
136342     }
136343     rc = sqlite3_reset(pRtree->pReadParent);
136344     if( rc==SQLITE_OK ) rc = rc2;
136345     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
136346     pChild = pChild->pParent;
136347   }
136348   return rc;
136349 }
136350 
136351 static int deleteCell(Rtree *, RtreeNode *, int, int);
136352 
136353 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
136354   int rc;
136355   int rc2;
136356   RtreeNode *pParent = 0;
136357   int iCell;
136358 
136359   assert( pNode->nRef==1 );
136360 
136361   /* Remove the entry in the parent cell. */
136362   rc = nodeParentIndex(pRtree, pNode, &iCell);
136363   if( rc==SQLITE_OK ){
136364     pParent = pNode->pParent;
136365     pNode->pParent = 0;
136366     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
136367   }
136368   rc2 = nodeRelease(pRtree, pParent);
136369   if( rc==SQLITE_OK ){
136370     rc = rc2;
136371   }
136372   if( rc!=SQLITE_OK ){
136373     return rc;
136374   }
136375 
136376   /* Remove the xxx_node entry. */
136377   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
136378   sqlite3_step(pRtree->pDeleteNode);
136379   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
136380     return rc;
136381   }
136382 
136383   /* Remove the xxx_parent entry. */
136384   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
136385   sqlite3_step(pRtree->pDeleteParent);
136386   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
136387     return rc;
136388   }
136389 
136390   /* Remove the node from the in-memory hash table and link it into
136391   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
136392   */
136393   nodeHashDelete(pRtree, pNode);
136394   pNode->iNode = iHeight;
136395   pNode->pNext = pRtree->pDeleted;
136396   pNode->nRef++;
136397   pRtree->pDeleted = pNode;
136398 
136399   return SQLITE_OK;
136400 }
136401 
136402 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
136403   RtreeNode *pParent = pNode->pParent;
136404   int rc = SQLITE_OK;
136405   if( pParent ){
136406     int ii;
136407     int nCell = NCELL(pNode);
136408     RtreeCell box;                            /* Bounding box for pNode */
136409     nodeGetCell(pRtree, pNode, 0, &box);
136410     for(ii=1; ii<nCell; ii++){
136411       RtreeCell cell;
136412       nodeGetCell(pRtree, pNode, ii, &cell);
136413       cellUnion(pRtree, &box, &cell);
136414     }
136415     box.iRowid = pNode->iNode;
136416     rc = nodeParentIndex(pRtree, pNode, &ii);
136417     if( rc==SQLITE_OK ){
136418       nodeOverwriteCell(pRtree, pParent, &box, ii);
136419       rc = fixBoundingBox(pRtree, pParent);
136420     }
136421   }
136422   return rc;
136423 }
136424 
136425 /*
136426 ** Delete the cell at index iCell of node pNode. After removing the
136427 ** cell, adjust the r-tree data structure if required.
136428 */
136429 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
136430   RtreeNode *pParent;
136431   int rc;
136432 
136433   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
136434     return rc;
136435   }
136436 
136437   /* Remove the cell from the node. This call just moves bytes around
136438   ** the in-memory node image, so it cannot fail.
136439   */
136440   nodeDeleteCell(pRtree, pNode, iCell);
136441 
136442   /* If the node is not the tree root and now has less than the minimum
136443   ** number of cells, remove it from the tree. Otherwise, update the
136444   ** cell in the parent node so that it tightly contains the updated
136445   ** node.
136446   */
136447   pParent = pNode->pParent;
136448   assert( pParent || pNode->iNode==1 );
136449   if( pParent ){
136450     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
136451       rc = removeNode(pRtree, pNode, iHeight);
136452     }else{
136453       rc = fixBoundingBox(pRtree, pNode);
136454     }
136455   }
136456 
136457   return rc;
136458 }
136459 
136460 static int Reinsert(
136461   Rtree *pRtree,
136462   RtreeNode *pNode,
136463   RtreeCell *pCell,
136464   int iHeight
136465 ){
136466   int *aOrder;
136467   int *aSpare;
136468   RtreeCell *aCell;
136469   RtreeDValue *aDistance;
136470   int nCell;
136471   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
136472   int iDim;
136473   int ii;
136474   int rc = SQLITE_OK;
136475   int n;
136476 
136477   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
136478 
136479   nCell = NCELL(pNode)+1;
136480   n = (nCell+1)&(~1);
136481 
136482   /* Allocate the buffers used by this operation. The allocation is
136483   ** relinquished before this function returns.
136484   */
136485   aCell = (RtreeCell *)sqlite3_malloc(n * (
136486     sizeof(RtreeCell)     +         /* aCell array */
136487     sizeof(int)           +         /* aOrder array */
136488     sizeof(int)           +         /* aSpare array */
136489     sizeof(RtreeDValue)             /* aDistance array */
136490   ));
136491   if( !aCell ){
136492     return SQLITE_NOMEM;
136493   }
136494   aOrder    = (int *)&aCell[n];
136495   aSpare    = (int *)&aOrder[n];
136496   aDistance = (RtreeDValue *)&aSpare[n];
136497 
136498   for(ii=0; ii<nCell; ii++){
136499     if( ii==(nCell-1) ){
136500       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
136501     }else{
136502       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
136503     }
136504     aOrder[ii] = ii;
136505     for(iDim=0; iDim<pRtree->nDim; iDim++){
136506       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
136507       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
136508     }
136509   }
136510   for(iDim=0; iDim<pRtree->nDim; iDim++){
136511     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
136512   }
136513 
136514   for(ii=0; ii<nCell; ii++){
136515     aDistance[ii] = 0.0;
136516     for(iDim=0; iDim<pRtree->nDim; iDim++){
136517       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
136518                                DCOORD(aCell[ii].aCoord[iDim*2]));
136519       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
136520     }
136521   }
136522 
136523   SortByDistance(aOrder, nCell, aDistance, aSpare);
136524   nodeZero(pRtree, pNode);
136525 
136526   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
136527     RtreeCell *p = &aCell[aOrder[ii]];
136528     nodeInsertCell(pRtree, pNode, p);
136529     if( p->iRowid==pCell->iRowid ){
136530       if( iHeight==0 ){
136531         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
136532       }else{
136533         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
136534       }
136535     }
136536   }
136537   if( rc==SQLITE_OK ){
136538     rc = fixBoundingBox(pRtree, pNode);
136539   }
136540   for(; rc==SQLITE_OK && ii<nCell; ii++){
136541     /* Find a node to store this cell in. pNode->iNode currently contains
136542     ** the height of the sub-tree headed by the cell.
136543     */
136544     RtreeNode *pInsert;
136545     RtreeCell *p = &aCell[aOrder[ii]];
136546     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
136547     if( rc==SQLITE_OK ){
136548       int rc2;
136549       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
136550       rc2 = nodeRelease(pRtree, pInsert);
136551       if( rc==SQLITE_OK ){
136552         rc = rc2;
136553       }
136554     }
136555   }
136556 
136557   sqlite3_free(aCell);
136558   return rc;
136559 }
136560 
136561 /*
136562 ** Insert cell pCell into node pNode. Node pNode is the head of a
136563 ** subtree iHeight high (leaf nodes have iHeight==0).
136564 */
136565 static int rtreeInsertCell(
136566   Rtree *pRtree,
136567   RtreeNode *pNode,
136568   RtreeCell *pCell,
136569   int iHeight
136570 ){
136571   int rc = SQLITE_OK;
136572   if( iHeight>0 ){
136573     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
136574     if( pChild ){
136575       nodeRelease(pRtree, pChild->pParent);
136576       nodeReference(pNode);
136577       pChild->pParent = pNode;
136578     }
136579   }
136580   if( nodeInsertCell(pRtree, pNode, pCell) ){
136581 #if VARIANT_RSTARTREE_REINSERT
136582     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
136583       rc = SplitNode(pRtree, pNode, pCell, iHeight);
136584     }else{
136585       pRtree->iReinsertHeight = iHeight;
136586       rc = Reinsert(pRtree, pNode, pCell, iHeight);
136587     }
136588 #else
136589     rc = SplitNode(pRtree, pNode, pCell, iHeight);
136590 #endif
136591   }else{
136592     rc = AdjustTree(pRtree, pNode, pCell);
136593     if( rc==SQLITE_OK ){
136594       if( iHeight==0 ){
136595         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
136596       }else{
136597         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
136598       }
136599     }
136600   }
136601   return rc;
136602 }
136603 
136604 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
136605   int ii;
136606   int rc = SQLITE_OK;
136607   int nCell = NCELL(pNode);
136608 
136609   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
136610     RtreeNode *pInsert;
136611     RtreeCell cell;
136612     nodeGetCell(pRtree, pNode, ii, &cell);
136613 
136614     /* Find a node to store this cell in. pNode->iNode currently contains
136615     ** the height of the sub-tree headed by the cell.
136616     */
136617     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
136618     if( rc==SQLITE_OK ){
136619       int rc2;
136620       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
136621       rc2 = nodeRelease(pRtree, pInsert);
136622       if( rc==SQLITE_OK ){
136623         rc = rc2;
136624       }
136625     }
136626   }
136627   return rc;
136628 }
136629 
136630 /*
136631 ** Select a currently unused rowid for a new r-tree record.
136632 */
136633 static int newRowid(Rtree *pRtree, i64 *piRowid){
136634   int rc;
136635   sqlite3_bind_null(pRtree->pWriteRowid, 1);
136636   sqlite3_bind_null(pRtree->pWriteRowid, 2);
136637   sqlite3_step(pRtree->pWriteRowid);
136638   rc = sqlite3_reset(pRtree->pWriteRowid);
136639   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
136640   return rc;
136641 }
136642 
136643 /*
136644 ** Remove the entry with rowid=iDelete from the r-tree structure.
136645 */
136646 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
136647   int rc;                         /* Return code */
136648   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
136649   int iCell;                      /* Index of iDelete cell in pLeaf */
136650   RtreeNode *pRoot;               /* Root node of rtree structure */
136651 
136652 
136653   /* Obtain a reference to the root node to initialize Rtree.iDepth */
136654   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
136655 
136656   /* Obtain a reference to the leaf node that contains the entry
136657   ** about to be deleted.
136658   */
136659   if( rc==SQLITE_OK ){
136660     rc = findLeafNode(pRtree, iDelete, &pLeaf);
136661   }
136662 
136663   /* Delete the cell in question from the leaf node. */
136664   if( rc==SQLITE_OK ){
136665     int rc2;
136666     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
136667     if( rc==SQLITE_OK ){
136668       rc = deleteCell(pRtree, pLeaf, iCell, 0);
136669     }
136670     rc2 = nodeRelease(pRtree, pLeaf);
136671     if( rc==SQLITE_OK ){
136672       rc = rc2;
136673     }
136674   }
136675 
136676   /* Delete the corresponding entry in the <rtree>_rowid table. */
136677   if( rc==SQLITE_OK ){
136678     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
136679     sqlite3_step(pRtree->pDeleteRowid);
136680     rc = sqlite3_reset(pRtree->pDeleteRowid);
136681   }
136682 
136683   /* Check if the root node now has exactly one child. If so, remove
136684   ** it, schedule the contents of the child for reinsertion and
136685   ** reduce the tree height by one.
136686   **
136687   ** This is equivalent to copying the contents of the child into
136688   ** the root node (the operation that Gutman's paper says to perform
136689   ** in this scenario).
136690   */
136691   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
136692     int rc2;
136693     RtreeNode *pChild;
136694     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
136695     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
136696     if( rc==SQLITE_OK ){
136697       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
136698     }
136699     rc2 = nodeRelease(pRtree, pChild);
136700     if( rc==SQLITE_OK ) rc = rc2;
136701     if( rc==SQLITE_OK ){
136702       pRtree->iDepth--;
136703       writeInt16(pRoot->zData, pRtree->iDepth);
136704       pRoot->isDirty = 1;
136705     }
136706   }
136707 
136708   /* Re-insert the contents of any underfull nodes removed from the tree. */
136709   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
136710     if( rc==SQLITE_OK ){
136711       rc = reinsertNodeContent(pRtree, pLeaf);
136712     }
136713     pRtree->pDeleted = pLeaf->pNext;
136714     sqlite3_free(pLeaf);
136715   }
136716 
136717   /* Release the reference to the root node. */
136718   if( rc==SQLITE_OK ){
136719     rc = nodeRelease(pRtree, pRoot);
136720   }else{
136721     nodeRelease(pRtree, pRoot);
136722   }
136723 
136724   return rc;
136725 }
136726 
136727 /*
136728 ** Rounding constants for float->double conversion.
136729 */
136730 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
136731 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
136732 
136733 #if !defined(SQLITE_RTREE_INT_ONLY)
136734 /*
136735 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
136736 ** while taking care to round toward negative or positive, respectively.
136737 */
136738 static RtreeValue rtreeValueDown(sqlite3_value *v){
136739   double d = sqlite3_value_double(v);
136740   float f = (float)d;
136741   if( f>d ){
136742     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
136743   }
136744   return f;
136745 }
136746 static RtreeValue rtreeValueUp(sqlite3_value *v){
136747   double d = sqlite3_value_double(v);
136748   float f = (float)d;
136749   if( f<d ){
136750     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
136751   }
136752   return f;
136753 }
136754 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
136755 
136756 
136757 /*
136758 ** The xUpdate method for rtree module virtual tables.
136759 */
136760 static int rtreeUpdate(
136761   sqlite3_vtab *pVtab,
136762   int nData,
136763   sqlite3_value **azData,
136764   sqlite_int64 *pRowid
136765 ){
136766   Rtree *pRtree = (Rtree *)pVtab;
136767   int rc = SQLITE_OK;
136768   RtreeCell cell;                 /* New cell to insert if nData>1 */
136769   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
136770 
136771   rtreeReference(pRtree);
136772   assert(nData>=1);
136773 
136774   /* Constraint handling. A write operation on an r-tree table may return
136775   ** SQLITE_CONSTRAINT for two reasons:
136776   **
136777   **   1. A duplicate rowid value, or
136778   **   2. The supplied data violates the "x2>=x1" constraint.
136779   **
136780   ** In the first case, if the conflict-handling mode is REPLACE, then
136781   ** the conflicting row can be removed before proceeding. In the second
136782   ** case, SQLITE_CONSTRAINT must be returned regardless of the
136783   ** conflict-handling mode specified by the user.
136784   */
136785   if( nData>1 ){
136786     int ii;
136787 
136788     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
136789     assert( nData==(pRtree->nDim*2 + 3) );
136790 #ifndef SQLITE_RTREE_INT_ONLY
136791     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
136792       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136793         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
136794         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
136795         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
136796           rc = SQLITE_CONSTRAINT;
136797           goto constraint;
136798         }
136799       }
136800     }else
136801 #endif
136802     {
136803       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136804         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
136805         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
136806         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
136807           rc = SQLITE_CONSTRAINT;
136808           goto constraint;
136809         }
136810       }
136811     }
136812 
136813     /* If a rowid value was supplied, check if it is already present in
136814     ** the table. If so, the constraint has failed. */
136815     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
136816       cell.iRowid = sqlite3_value_int64(azData[2]);
136817       if( sqlite3_value_type(azData[0])==SQLITE_NULL
136818        || sqlite3_value_int64(azData[0])!=cell.iRowid
136819       ){
136820         int steprc;
136821         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
136822         steprc = sqlite3_step(pRtree->pReadRowid);
136823         rc = sqlite3_reset(pRtree->pReadRowid);
136824         if( SQLITE_ROW==steprc ){
136825           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
136826             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
136827           }else{
136828             rc = SQLITE_CONSTRAINT;
136829             goto constraint;
136830           }
136831         }
136832       }
136833       bHaveRowid = 1;
136834     }
136835   }
136836 
136837   /* If azData[0] is not an SQL NULL value, it is the rowid of a
136838   ** record to delete from the r-tree table. The following block does
136839   ** just that.
136840   */
136841   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
136842     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
136843   }
136844 
136845   /* If the azData[] array contains more than one element, elements
136846   ** (azData[2]..azData[argc-1]) contain a new record to insert into
136847   ** the r-tree structure.
136848   */
136849   if( rc==SQLITE_OK && nData>1 ){
136850     /* Insert the new record into the r-tree */
136851     RtreeNode *pLeaf = 0;
136852 
136853     /* Figure out the rowid of the new row. */
136854     if( bHaveRowid==0 ){
136855       rc = newRowid(pRtree, &cell.iRowid);
136856     }
136857     *pRowid = cell.iRowid;
136858 
136859     if( rc==SQLITE_OK ){
136860       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
136861     }
136862     if( rc==SQLITE_OK ){
136863       int rc2;
136864       pRtree->iReinsertHeight = -1;
136865       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
136866       rc2 = nodeRelease(pRtree, pLeaf);
136867       if( rc==SQLITE_OK ){
136868         rc = rc2;
136869       }
136870     }
136871   }
136872 
136873 constraint:
136874   rtreeRelease(pRtree);
136875   return rc;
136876 }
136877 
136878 /*
136879 ** The xRename method for rtree module virtual tables.
136880 */
136881 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
136882   Rtree *pRtree = (Rtree *)pVtab;
136883   int rc = SQLITE_NOMEM;
136884   char *zSql = sqlite3_mprintf(
136885     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
136886     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
136887     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
136888     , pRtree->zDb, pRtree->zName, zNewName
136889     , pRtree->zDb, pRtree->zName, zNewName
136890     , pRtree->zDb, pRtree->zName, zNewName
136891   );
136892   if( zSql ){
136893     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
136894     sqlite3_free(zSql);
136895   }
136896   return rc;
136897 }
136898 
136899 static sqlite3_module rtreeModule = {
136900   0,                          /* iVersion */
136901   rtreeCreate,                /* xCreate - create a table */
136902   rtreeConnect,               /* xConnect - connect to an existing table */
136903   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
136904   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
136905   rtreeDestroy,               /* xDestroy - Drop a table */
136906   rtreeOpen,                  /* xOpen - open a cursor */
136907   rtreeClose,                 /* xClose - close a cursor */
136908   rtreeFilter,                /* xFilter - configure scan constraints */
136909   rtreeNext,                  /* xNext - advance a cursor */
136910   rtreeEof,                   /* xEof */
136911   rtreeColumn,                /* xColumn - read data */
136912   rtreeRowid,                 /* xRowid - read data */
136913   rtreeUpdate,                /* xUpdate - write data */
136914   0,                          /* xBegin - begin transaction */
136915   0,                          /* xSync - sync transaction */
136916   0,                          /* xCommit - commit transaction */
136917   0,                          /* xRollback - rollback transaction */
136918   0,                          /* xFindFunction - function overloading */
136919   rtreeRename,                /* xRename - rename the table */
136920   0,                          /* xSavepoint */
136921   0,                          /* xRelease */
136922   0                           /* xRollbackTo */
136923 };
136924 
136925 static int rtreeSqlInit(
136926   Rtree *pRtree,
136927   sqlite3 *db,
136928   const char *zDb,
136929   const char *zPrefix,
136930   int isCreate
136931 ){
136932   int rc = SQLITE_OK;
136933 
136934   #define N_STATEMENT 9
136935   static const char *azSql[N_STATEMENT] = {
136936     /* Read and write the xxx_node table */
136937     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
136938     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
136939     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
136940 
136941     /* Read and write the xxx_rowid table */
136942     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
136943     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
136944     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
136945 
136946     /* Read and write the xxx_parent table */
136947     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
136948     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
136949     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
136950   };
136951   sqlite3_stmt **appStmt[N_STATEMENT];
136952   int i;
136953 
136954   pRtree->db = db;
136955 
136956   if( isCreate ){
136957     char *zCreate = sqlite3_mprintf(
136958 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
136959 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
136960 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
136961 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
136962       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
136963     );
136964     if( !zCreate ){
136965       return SQLITE_NOMEM;
136966     }
136967     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
136968     sqlite3_free(zCreate);
136969     if( rc!=SQLITE_OK ){
136970       return rc;
136971     }
136972   }
136973 
136974   appStmt[0] = &pRtree->pReadNode;
136975   appStmt[1] = &pRtree->pWriteNode;
136976   appStmt[2] = &pRtree->pDeleteNode;
136977   appStmt[3] = &pRtree->pReadRowid;
136978   appStmt[4] = &pRtree->pWriteRowid;
136979   appStmt[5] = &pRtree->pDeleteRowid;
136980   appStmt[6] = &pRtree->pReadParent;
136981   appStmt[7] = &pRtree->pWriteParent;
136982   appStmt[8] = &pRtree->pDeleteParent;
136983 
136984   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
136985     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
136986     if( zSql ){
136987       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
136988     }else{
136989       rc = SQLITE_NOMEM;
136990     }
136991     sqlite3_free(zSql);
136992   }
136993 
136994   return rc;
136995 }
136996 
136997 /*
136998 ** The second argument to this function contains the text of an SQL statement
136999 ** that returns a single integer value. The statement is compiled and executed
137000 ** using database connection db. If successful, the integer value returned
137001 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
137002 ** code is returned and the value of *piVal after returning is not defined.
137003 */
137004 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
137005   int rc = SQLITE_NOMEM;
137006   if( zSql ){
137007     sqlite3_stmt *pStmt = 0;
137008     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
137009     if( rc==SQLITE_OK ){
137010       if( SQLITE_ROW==sqlite3_step(pStmt) ){
137011         *piVal = sqlite3_column_int(pStmt, 0);
137012       }
137013       rc = sqlite3_finalize(pStmt);
137014     }
137015   }
137016   return rc;
137017 }
137018 
137019 /*
137020 ** This function is called from within the xConnect() or xCreate() method to
137021 ** determine the node-size used by the rtree table being created or connected
137022 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
137023 ** Otherwise, an SQLite error code is returned.
137024 **
137025 ** If this function is being called as part of an xConnect(), then the rtree
137026 ** table already exists. In this case the node-size is determined by inspecting
137027 ** the root node of the tree.
137028 **
137029 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
137030 ** This ensures that each node is stored on a single database page. If the
137031 ** database page-size is so large that more than RTREE_MAXCELLS entries
137032 ** would fit in a single node, use a smaller node-size.
137033 */
137034 static int getNodeSize(
137035   sqlite3 *db,                    /* Database handle */
137036   Rtree *pRtree,                  /* Rtree handle */
137037   int isCreate,                   /* True for xCreate, false for xConnect */
137038   char **pzErr                    /* OUT: Error message, if any */
137039 ){
137040   int rc;
137041   char *zSql;
137042   if( isCreate ){
137043     int iPageSize = 0;
137044     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
137045     rc = getIntFromStmt(db, zSql, &iPageSize);
137046     if( rc==SQLITE_OK ){
137047       pRtree->iNodeSize = iPageSize-64;
137048       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
137049         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
137050       }
137051     }else{
137052       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137053     }
137054   }else{
137055     zSql = sqlite3_mprintf(
137056         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
137057         pRtree->zDb, pRtree->zName
137058     );
137059     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
137060     if( rc!=SQLITE_OK ){
137061       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137062     }
137063   }
137064 
137065   sqlite3_free(zSql);
137066   return rc;
137067 }
137068 
137069 /*
137070 ** This function is the implementation of both the xConnect and xCreate
137071 ** methods of the r-tree virtual table.
137072 **
137073 **   argv[0]   -> module name
137074 **   argv[1]   -> database name
137075 **   argv[2]   -> table name
137076 **   argv[...] -> column names...
137077 */
137078 static int rtreeInit(
137079   sqlite3 *db,                        /* Database connection */
137080   void *pAux,                         /* One of the RTREE_COORD_* constants */
137081   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
137082   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
137083   char **pzErr,                       /* OUT: Error message, if any */
137084   int isCreate                        /* True for xCreate, false for xConnect */
137085 ){
137086   int rc = SQLITE_OK;
137087   Rtree *pRtree;
137088   int nDb;              /* Length of string argv[1] */
137089   int nName;            /* Length of string argv[2] */
137090   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
137091 
137092   const char *aErrMsg[] = {
137093     0,                                                    /* 0 */
137094     "Wrong number of columns for an rtree table",         /* 1 */
137095     "Too few columns for an rtree table",                 /* 2 */
137096     "Too many columns for an rtree table"                 /* 3 */
137097   };
137098 
137099   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
137100   if( aErrMsg[iErr] ){
137101     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
137102     return SQLITE_ERROR;
137103   }
137104 
137105   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
137106 
137107   /* Allocate the sqlite3_vtab structure */
137108   nDb = (int)strlen(argv[1]);
137109   nName = (int)strlen(argv[2]);
137110   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
137111   if( !pRtree ){
137112     return SQLITE_NOMEM;
137113   }
137114   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
137115   pRtree->nBusy = 1;
137116   pRtree->base.pModule = &rtreeModule;
137117   pRtree->zDb = (char *)&pRtree[1];
137118   pRtree->zName = &pRtree->zDb[nDb+1];
137119   pRtree->nDim = (argc-4)/2;
137120   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
137121   pRtree->eCoordType = eCoordType;
137122   memcpy(pRtree->zDb, argv[1], nDb);
137123   memcpy(pRtree->zName, argv[2], nName);
137124 
137125   /* Figure out the node size to use. */
137126   rc = getNodeSize(db, pRtree, isCreate, pzErr);
137127 
137128   /* Create/Connect to the underlying relational database schema. If
137129   ** that is successful, call sqlite3_declare_vtab() to configure
137130   ** the r-tree table schema.
137131   */
137132   if( rc==SQLITE_OK ){
137133     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
137134       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137135     }else{
137136       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
137137       char *zTmp;
137138       int ii;
137139       for(ii=4; zSql && ii<argc; ii++){
137140         zTmp = zSql;
137141         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
137142         sqlite3_free(zTmp);
137143       }
137144       if( zSql ){
137145         zTmp = zSql;
137146         zSql = sqlite3_mprintf("%s);", zTmp);
137147         sqlite3_free(zTmp);
137148       }
137149       if( !zSql ){
137150         rc = SQLITE_NOMEM;
137151       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
137152         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
137153       }
137154       sqlite3_free(zSql);
137155     }
137156   }
137157 
137158   if( rc==SQLITE_OK ){
137159     *ppVtab = (sqlite3_vtab *)pRtree;
137160   }else{
137161     rtreeRelease(pRtree);
137162   }
137163   return rc;
137164 }
137165 
137166 
137167 /*
137168 ** Implementation of a scalar function that decodes r-tree nodes to
137169 ** human readable strings. This can be used for debugging and analysis.
137170 **
137171 ** The scalar function takes two arguments, a blob of data containing
137172 ** an r-tree node, and the number of dimensions the r-tree indexes.
137173 ** For a two-dimensional r-tree structure called "rt", to deserialize
137174 ** all nodes, a statement like:
137175 **
137176 **   SELECT rtreenode(2, data) FROM rt_node;
137177 **
137178 ** The human readable string takes the form of a Tcl list with one
137179 ** entry for each cell in the r-tree node. Each entry is itself a
137180 ** list, containing the 8-byte rowid/pageno followed by the
137181 ** <num-dimension>*2 coordinates.
137182 */
137183 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
137184   char *zText = 0;
137185   RtreeNode node;
137186   Rtree tree;
137187   int ii;
137188 
137189   UNUSED_PARAMETER(nArg);
137190   memset(&node, 0, sizeof(RtreeNode));
137191   memset(&tree, 0, sizeof(Rtree));
137192   tree.nDim = sqlite3_value_int(apArg[0]);
137193   tree.nBytesPerCell = 8 + 8 * tree.nDim;
137194   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
137195 
137196   for(ii=0; ii<NCELL(&node); ii++){
137197     char zCell[512];
137198     int nCell = 0;
137199     RtreeCell cell;
137200     int jj;
137201 
137202     nodeGetCell(&tree, &node, ii, &cell);
137203     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
137204     nCell = (int)strlen(zCell);
137205     for(jj=0; jj<tree.nDim*2; jj++){
137206 #ifndef SQLITE_RTREE_INT_ONLY
137207       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
137208                        (double)cell.aCoord[jj].f);
137209 #else
137210       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
137211                        cell.aCoord[jj].i);
137212 #endif
137213       nCell = (int)strlen(zCell);
137214     }
137215 
137216     if( zText ){
137217       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
137218       sqlite3_free(zText);
137219       zText = zTextNew;
137220     }else{
137221       zText = sqlite3_mprintf("{%s}", zCell);
137222     }
137223   }
137224 
137225   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
137226 }
137227 
137228 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
137229   UNUSED_PARAMETER(nArg);
137230   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
137231    || sqlite3_value_bytes(apArg[0])<2
137232   ){
137233     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
137234   }else{
137235     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
137236     sqlite3_result_int(ctx, readInt16(zBlob));
137237   }
137238 }
137239 
137240 /*
137241 ** Register the r-tree module with database handle db. This creates the
137242 ** virtual table module "rtree" and the debugging/analysis scalar
137243 ** function "rtreenode".
137244 */
137245 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
137246   const int utf8 = SQLITE_UTF8;
137247   int rc;
137248 
137249   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
137250   if( rc==SQLITE_OK ){
137251     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
137252   }
137253   if( rc==SQLITE_OK ){
137254 #ifdef SQLITE_RTREE_INT_ONLY
137255     void *c = (void *)RTREE_COORD_INT32;
137256 #else
137257     void *c = (void *)RTREE_COORD_REAL32;
137258 #endif
137259     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
137260   }
137261   if( rc==SQLITE_OK ){
137262     void *c = (void *)RTREE_COORD_INT32;
137263     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
137264   }
137265 
137266   return rc;
137267 }
137268 
137269 /*
137270 ** A version of sqlite3_free() that can be used as a callback. This is used
137271 ** in two places - as the destructor for the blob value returned by the
137272 ** invocation of a geometry function, and as the destructor for the geometry
137273 ** functions themselves.
137274 */
137275 static void doSqlite3Free(void *p){
137276   sqlite3_free(p);
137277 }
137278 
137279 /*
137280 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
137281 ** scalar user function. This C function is the callback used for all such
137282 ** registered SQL functions.
137283 **
137284 ** The scalar user functions return a blob that is interpreted by r-tree
137285 ** table MATCH operators.
137286 */
137287 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
137288   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
137289   RtreeMatchArg *pBlob;
137290   int nBlob;
137291 
137292   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
137293   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
137294   if( !pBlob ){
137295     sqlite3_result_error_nomem(ctx);
137296   }else{
137297     int i;
137298     pBlob->magic = RTREE_GEOMETRY_MAGIC;
137299     pBlob->xGeom = pGeomCtx->xGeom;
137300     pBlob->pContext = pGeomCtx->pContext;
137301     pBlob->nParam = nArg;
137302     for(i=0; i<nArg; i++){
137303 #ifdef SQLITE_RTREE_INT_ONLY
137304       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
137305 #else
137306       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
137307 #endif
137308     }
137309     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
137310   }
137311 }
137312 
137313 /*
137314 ** Register a new geometry function for use with the r-tree MATCH operator.
137315 */
137316 SQLITE_API int sqlite3_rtree_geometry_callback(
137317   sqlite3 *db,
137318   const char *zGeom,
137319   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
137320   void *pContext
137321 ){
137322   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
137323 
137324   /* Allocate and populate the context object. */
137325   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
137326   if( !pGeomCtx ) return SQLITE_NOMEM;
137327   pGeomCtx->xGeom = xGeom;
137328   pGeomCtx->pContext = pContext;
137329 
137330   /* Create the new user-function. Register a destructor function to delete
137331   ** the context object when it is no longer required.  */
137332   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
137333       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
137334   );
137335 }
137336 
137337 #if !SQLITE_CORE
137338 SQLITE_API int sqlite3_extension_init(
137339   sqlite3 *db,
137340   char **pzErrMsg,
137341   const sqlite3_api_routines *pApi
137342 ){
137343   SQLITE_EXTENSION_INIT2(pApi)
137344   return sqlite3RtreeInit(db);
137345 }
137346 #endif
137347 
137348 #endif
137349 
137350 /************** End of rtree.c ***********************************************/
137351 /************** Begin file icu.c *********************************************/
137352 /*
137353 ** 2007 May 6
137354 **
137355 ** The author disclaims copyright to this source code.  In place of
137356 ** a legal notice, here is a blessing:
137357 **
137358 **    May you do good and not evil.
137359 **    May you find forgiveness for yourself and forgive others.
137360 **    May you share freely, never taking more than you give.
137361 **
137362 *************************************************************************
137363 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
137364 **
137365 ** This file implements an integration between the ICU library
137366 ** ("International Components for Unicode", an open-source library
137367 ** for handling unicode data) and SQLite. The integration uses
137368 ** ICU to provide the following to SQLite:
137369 **
137370 **   * An implementation of the SQL regexp() function (and hence REGEXP
137371 **     operator) using the ICU uregex_XX() APIs.
137372 **
137373 **   * Implementations of the SQL scalar upper() and lower() functions
137374 **     for case mapping.
137375 **
137376 **   * Integration of ICU and SQLite collation seqences.
137377 **
137378 **   * An implementation of the LIKE operator that uses ICU to
137379 **     provide case-independent matching.
137380 */
137381 
137382 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
137383 
137384 /* Include ICU headers */
137385 #include <unicode/utypes.h>
137386 #include <unicode/uregex.h>
137387 #include <unicode/ustring.h>
137388 #include <unicode/ucol.h>
137389 
137390 /* #include <assert.h> */
137391 
137392 #ifndef SQLITE_CORE
137393   SQLITE_EXTENSION_INIT1
137394 #else
137395 #endif
137396 
137397 /*
137398 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
137399 ** operator.
137400 */
137401 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
137402 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
137403 #endif
137404 
137405 /*
137406 ** Version of sqlite3_free() that is always a function, never a macro.
137407 */
137408 static void xFree(void *p){
137409   sqlite3_free(p);
137410 }
137411 
137412 /*
137413 ** Compare two UTF-8 strings for equality where the first string is
137414 ** a "LIKE" expression. Return true (1) if they are the same and
137415 ** false (0) if they are different.
137416 */
137417 static int icuLikeCompare(
137418   const uint8_t *zPattern,   /* LIKE pattern */
137419   const uint8_t *zString,    /* The UTF-8 string to compare against */
137420   const UChar32 uEsc         /* The escape character */
137421 ){
137422   static const int MATCH_ONE = (UChar32)'_';
137423   static const int MATCH_ALL = (UChar32)'%';
137424 
137425   int iPattern = 0;       /* Current byte index in zPattern */
137426   int iString = 0;        /* Current byte index in zString */
137427 
137428   int prevEscape = 0;     /* True if the previous character was uEsc */
137429 
137430   while( zPattern[iPattern]!=0 ){
137431 
137432     /* Read (and consume) the next character from the input pattern. */
137433     UChar32 uPattern;
137434     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
137435     assert(uPattern!=0);
137436 
137437     /* There are now 4 possibilities:
137438     **
137439     **     1. uPattern is an unescaped match-all character "%",
137440     **     2. uPattern is an unescaped match-one character "_",
137441     **     3. uPattern is an unescaped escape character, or
137442     **     4. uPattern is to be handled as an ordinary character
137443     */
137444     if( !prevEscape && uPattern==MATCH_ALL ){
137445       /* Case 1. */
137446       uint8_t c;
137447 
137448       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
137449       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
137450       ** test string.
137451       */
137452       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
137453         if( c==MATCH_ONE ){
137454           if( zString[iString]==0 ) return 0;
137455           U8_FWD_1_UNSAFE(zString, iString);
137456         }
137457         iPattern++;
137458       }
137459 
137460       if( zPattern[iPattern]==0 ) return 1;
137461 
137462       while( zString[iString] ){
137463         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
137464           return 1;
137465         }
137466         U8_FWD_1_UNSAFE(zString, iString);
137467       }
137468       return 0;
137469 
137470     }else if( !prevEscape && uPattern==MATCH_ONE ){
137471       /* Case 2. */
137472       if( zString[iString]==0 ) return 0;
137473       U8_FWD_1_UNSAFE(zString, iString);
137474 
137475     }else if( !prevEscape && uPattern==uEsc){
137476       /* Case 3. */
137477       prevEscape = 1;
137478 
137479     }else{
137480       /* Case 4. */
137481       UChar32 uString;
137482       U8_NEXT_UNSAFE(zString, iString, uString);
137483       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
137484       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
137485       if( uString!=uPattern ){
137486         return 0;
137487       }
137488       prevEscape = 0;
137489     }
137490   }
137491 
137492   return zString[iString]==0;
137493 }
137494 
137495 /*
137496 ** Implementation of the like() SQL function.  This function implements
137497 ** the build-in LIKE operator.  The first argument to the function is the
137498 ** pattern and the second argument is the string.  So, the SQL statements:
137499 **
137500 **       A LIKE B
137501 **
137502 ** is implemented as like(B, A). If there is an escape character E,
137503 **
137504 **       A LIKE B ESCAPE E
137505 **
137506 ** is mapped to like(B, A, E).
137507 */
137508 static void icuLikeFunc(
137509   sqlite3_context *context,
137510   int argc,
137511   sqlite3_value **argv
137512 ){
137513   const unsigned char *zA = sqlite3_value_text(argv[0]);
137514   const unsigned char *zB = sqlite3_value_text(argv[1]);
137515   UChar32 uEsc = 0;
137516 
137517   /* Limit the length of the LIKE or GLOB pattern to avoid problems
137518   ** of deep recursion and N*N behavior in patternCompare().
137519   */
137520   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
137521     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
137522     return;
137523   }
137524 
137525 
137526   if( argc==3 ){
137527     /* The escape character string must consist of a single UTF-8 character.
137528     ** Otherwise, return an error.
137529     */
137530     int nE= sqlite3_value_bytes(argv[2]);
137531     const unsigned char *zE = sqlite3_value_text(argv[2]);
137532     int i = 0;
137533     if( zE==0 ) return;
137534     U8_NEXT(zE, i, nE, uEsc);
137535     if( i!=nE){
137536       sqlite3_result_error(context,
137537           "ESCAPE expression must be a single character", -1);
137538       return;
137539     }
137540   }
137541 
137542   if( zA && zB ){
137543     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
137544   }
137545 }
137546 
137547 /*
137548 ** This function is called when an ICU function called from within
137549 ** the implementation of an SQL scalar function returns an error.
137550 **
137551 ** The scalar function context passed as the first argument is
137552 ** loaded with an error message based on the following two args.
137553 */
137554 static void icuFunctionError(
137555   sqlite3_context *pCtx,       /* SQLite scalar function context */
137556   const char *zName,           /* Name of ICU function that failed */
137557   UErrorCode e                 /* Error code returned by ICU function */
137558 ){
137559   char zBuf[128];
137560   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
137561   zBuf[127] = '\0';
137562   sqlite3_result_error(pCtx, zBuf, -1);
137563 }
137564 
137565 /*
137566 ** Function to delete compiled regexp objects. Registered as
137567 ** a destructor function with sqlite3_set_auxdata().
137568 */
137569 static void icuRegexpDelete(void *p){
137570   URegularExpression *pExpr = (URegularExpression *)p;
137571   uregex_close(pExpr);
137572 }
137573 
137574 /*
137575 ** Implementation of SQLite REGEXP operator. This scalar function takes
137576 ** two arguments. The first is a regular expression pattern to compile
137577 ** the second is a string to match against that pattern. If either
137578 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
137579 ** is 1 if the string matches the pattern, or 0 otherwise.
137580 **
137581 ** SQLite maps the regexp() function to the regexp() operator such
137582 ** that the following two are equivalent:
137583 **
137584 **     zString REGEXP zPattern
137585 **     regexp(zPattern, zString)
137586 **
137587 ** Uses the following ICU regexp APIs:
137588 **
137589 **     uregex_open()
137590 **     uregex_matches()
137591 **     uregex_close()
137592 */
137593 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
137594   UErrorCode status = U_ZERO_ERROR;
137595   URegularExpression *pExpr;
137596   UBool res;
137597   const UChar *zString = sqlite3_value_text16(apArg[1]);
137598 
137599   (void)nArg;  /* Unused parameter */
137600 
137601   /* If the left hand side of the regexp operator is NULL,
137602   ** then the result is also NULL.
137603   */
137604   if( !zString ){
137605     return;
137606   }
137607 
137608   pExpr = sqlite3_get_auxdata(p, 0);
137609   if( !pExpr ){
137610     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
137611     if( !zPattern ){
137612       return;
137613     }
137614     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
137615 
137616     if( U_SUCCESS(status) ){
137617       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
137618     }else{
137619       assert(!pExpr);
137620       icuFunctionError(p, "uregex_open", status);
137621       return;
137622     }
137623   }
137624 
137625   /* Configure the text that the regular expression operates on. */
137626   uregex_setText(pExpr, zString, -1, &status);
137627   if( !U_SUCCESS(status) ){
137628     icuFunctionError(p, "uregex_setText", status);
137629     return;
137630   }
137631 
137632   /* Attempt the match */
137633   res = uregex_matches(pExpr, 0, &status);
137634   if( !U_SUCCESS(status) ){
137635     icuFunctionError(p, "uregex_matches", status);
137636     return;
137637   }
137638 
137639   /* Set the text that the regular expression operates on to a NULL
137640   ** pointer. This is not really necessary, but it is tidier than
137641   ** leaving the regular expression object configured with an invalid
137642   ** pointer after this function returns.
137643   */
137644   uregex_setText(pExpr, 0, 0, &status);
137645 
137646   /* Return 1 or 0. */
137647   sqlite3_result_int(p, res ? 1 : 0);
137648 }
137649 
137650 /*
137651 ** Implementations of scalar functions for case mapping - upper() and
137652 ** lower(). Function upper() converts its input to upper-case (ABC).
137653 ** Function lower() converts to lower-case (abc).
137654 **
137655 ** ICU provides two types of case mapping, "general" case mapping and
137656 ** "language specific". Refer to ICU documentation for the differences
137657 ** between the two.
137658 **
137659 ** To utilise "general" case mapping, the upper() or lower() scalar
137660 ** functions are invoked with one argument:
137661 **
137662 **     upper('ABC') -> 'abc'
137663 **     lower('abc') -> 'ABC'
137664 **
137665 ** To access ICU "language specific" case mapping, upper() or lower()
137666 ** should be invoked with two arguments. The second argument is the name
137667 ** of the locale to use. Passing an empty string ("") or SQL NULL value
137668 ** as the second argument is the same as invoking the 1 argument version
137669 ** of upper() or lower().
137670 **
137671 **     lower('I', 'en_us') -> 'i'
137672 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
137673 **
137674 ** http://www.icu-project.org/userguide/posix.html#case_mappings
137675 */
137676 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
137677   const UChar *zInput;
137678   UChar *zOutput;
137679   int nInput;
137680   int nOutput;
137681 
137682   UErrorCode status = U_ZERO_ERROR;
137683   const char *zLocale = 0;
137684 
137685   assert(nArg==1 || nArg==2);
137686   if( nArg==2 ){
137687     zLocale = (const char *)sqlite3_value_text(apArg[1]);
137688   }
137689 
137690   zInput = sqlite3_value_text16(apArg[0]);
137691   if( !zInput ){
137692     return;
137693   }
137694   nInput = sqlite3_value_bytes16(apArg[0]);
137695 
137696   nOutput = nInput * 2 + 2;
137697   zOutput = sqlite3_malloc(nOutput);
137698   if( !zOutput ){
137699     return;
137700   }
137701 
137702   if( sqlite3_user_data(p) ){
137703     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137704   }else{
137705     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
137706   }
137707 
137708   if( !U_SUCCESS(status) ){
137709     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
137710     return;
137711   }
137712 
137713   sqlite3_result_text16(p, zOutput, -1, xFree);
137714 }
137715 
137716 /*
137717 ** Collation sequence destructor function. The pCtx argument points to
137718 ** a UCollator structure previously allocated using ucol_open().
137719 */
137720 static void icuCollationDel(void *pCtx){
137721   UCollator *p = (UCollator *)pCtx;
137722   ucol_close(p);
137723 }
137724 
137725 /*
137726 ** Collation sequence comparison function. The pCtx argument points to
137727 ** a UCollator structure previously allocated using ucol_open().
137728 */
137729 static int icuCollationColl(
137730   void *pCtx,
137731   int nLeft,
137732   const void *zLeft,
137733   int nRight,
137734   const void *zRight
137735 ){
137736   UCollationResult res;
137737   UCollator *p = (UCollator *)pCtx;
137738   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
137739   switch( res ){
137740     case UCOL_LESS:    return -1;
137741     case UCOL_GREATER: return +1;
137742     case UCOL_EQUAL:   return 0;
137743   }
137744   assert(!"Unexpected return value from ucol_strcoll()");
137745   return 0;
137746 }
137747 
137748 /*
137749 ** Implementation of the scalar function icu_load_collation().
137750 **
137751 ** This scalar function is used to add ICU collation based collation
137752 ** types to an SQLite database connection. It is intended to be called
137753 ** as follows:
137754 **
137755 **     SELECT icu_load_collation(<locale>, <collation-name>);
137756 **
137757 ** Where <locale> is a string containing an ICU locale identifier (i.e.
137758 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
137759 ** collation sequence to create.
137760 */
137761 static void icuLoadCollation(
137762   sqlite3_context *p,
137763   int nArg,
137764   sqlite3_value **apArg
137765 ){
137766   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
137767   UErrorCode status = U_ZERO_ERROR;
137768   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
137769   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
137770   UCollator *pUCollator;    /* ICU library collation object */
137771   int rc;                   /* Return code from sqlite3_create_collation_x() */
137772 
137773   assert(nArg==2);
137774   zLocale = (const char *)sqlite3_value_text(apArg[0]);
137775   zName = (const char *)sqlite3_value_text(apArg[1]);
137776 
137777   if( !zLocale || !zName ){
137778     return;
137779   }
137780 
137781   pUCollator = ucol_open(zLocale, &status);
137782   if( !U_SUCCESS(status) ){
137783     icuFunctionError(p, "ucol_open", status);
137784     return;
137785   }
137786   assert(p);
137787 
137788   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
137789       icuCollationColl, icuCollationDel
137790   );
137791   if( rc!=SQLITE_OK ){
137792     ucol_close(pUCollator);
137793     sqlite3_result_error(p, "Error registering collation function", -1);
137794   }
137795 }
137796 
137797 /*
137798 ** Register the ICU extension functions with database db.
137799 */
137800 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
137801   struct IcuScalar {
137802     const char *zName;                        /* Function name */
137803     int nArg;                                 /* Number of arguments */
137804     int enc;                                  /* Optimal text encoding */
137805     void *pContext;                           /* sqlite3_user_data() context */
137806     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
137807   } scalars[] = {
137808     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
137809 
137810     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
137811     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
137812     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137813     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
137814 
137815     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
137816     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
137817     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137818     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
137819 
137820     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
137821     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
137822 
137823     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
137824   };
137825 
137826   int rc = SQLITE_OK;
137827   int i;
137828 
137829   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
137830     struct IcuScalar *p = &scalars[i];
137831     rc = sqlite3_create_function(
137832         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
137833     );
137834   }
137835 
137836   return rc;
137837 }
137838 
137839 #if !SQLITE_CORE
137840 SQLITE_API int sqlite3_extension_init(
137841   sqlite3 *db,
137842   char **pzErrMsg,
137843   const sqlite3_api_routines *pApi
137844 ){
137845   SQLITE_EXTENSION_INIT2(pApi)
137846   return sqlite3IcuInit(db);
137847 }
137848 #endif
137849 
137850 #endif
137851 
137852 /************** End of icu.c *************************************************/
137853 /************** Begin file fts3_icu.c ****************************************/
137854 /*
137855 ** 2007 June 22
137856 **
137857 ** The author disclaims copyright to this source code.  In place of
137858 ** a legal notice, here is a blessing:
137859 **
137860 **    May you do good and not evil.
137861 **    May you find forgiveness for yourself and forgive others.
137862 **    May you share freely, never taking more than you give.
137863 **
137864 *************************************************************************
137865 ** This file implements a tokenizer for fts3 based on the ICU library.
137866 */
137867 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137868 #ifdef SQLITE_ENABLE_ICU
137869 
137870 /* #include <assert.h> */
137871 /* #include <string.h> */
137872 
137873 #include <unicode/ubrk.h>
137874 /* #include <unicode/ucol.h> */
137875 /* #include <unicode/ustring.h> */
137876 #include <unicode/utf16.h>
137877 
137878 typedef struct IcuTokenizer IcuTokenizer;
137879 typedef struct IcuCursor IcuCursor;
137880 
137881 struct IcuTokenizer {
137882   sqlite3_tokenizer base;
137883   char *zLocale;
137884 };
137885 
137886 struct IcuCursor {
137887   sqlite3_tokenizer_cursor base;
137888 
137889   UBreakIterator *pIter;      /* ICU break-iterator object */
137890   int nChar;                  /* Number of UChar elements in pInput */
137891   UChar *aChar;               /* Copy of input using utf-16 encoding */
137892   int *aOffset;               /* Offsets of each character in utf-8 input */
137893 
137894   int nBuffer;
137895   char *zBuffer;
137896 
137897   int iToken;
137898 };
137899 
137900 /*
137901 ** Create a new tokenizer instance.
137902 */
137903 static int icuCreate(
137904   int argc,                            /* Number of entries in argv[] */
137905   const char * const *argv,            /* Tokenizer creation arguments */
137906   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
137907 ){
137908   IcuTokenizer *p;
137909   int n = 0;
137910 
137911   if( argc>0 ){
137912     n = strlen(argv[0])+1;
137913   }
137914   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
137915   if( !p ){
137916     return SQLITE_NOMEM;
137917   }
137918   memset(p, 0, sizeof(IcuTokenizer));
137919 
137920   if( n ){
137921     p->zLocale = (char *)&p[1];
137922     memcpy(p->zLocale, argv[0], n);
137923   }
137924 
137925   *ppTokenizer = (sqlite3_tokenizer *)p;
137926 
137927   return SQLITE_OK;
137928 }
137929 
137930 /*
137931 ** Destroy a tokenizer
137932 */
137933 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
137934   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
137935   sqlite3_free(p);
137936   return SQLITE_OK;
137937 }
137938 
137939 /*
137940 ** Prepare to begin tokenizing a particular string.  The input
137941 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
137942 ** used to incrementally tokenize this string is returned in
137943 ** *ppCursor.
137944 */
137945 static int icuOpen(
137946   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
137947   const char *zInput,                    /* Input string */
137948   int nInput,                            /* Length of zInput in bytes */
137949   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
137950 ){
137951   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
137952   IcuCursor *pCsr;
137953 
137954   const int32_t opt = U_FOLD_CASE_DEFAULT;
137955   UErrorCode status = U_ZERO_ERROR;
137956   int nChar;
137957 
137958   UChar32 c;
137959   int iInput = 0;
137960   int iOut = 0;
137961 
137962   *ppCursor = 0;
137963 
137964   if( zInput==0 ){
137965     nInput = 0;
137966     zInput = "";
137967   }else if( nInput<0 ){
137968     nInput = strlen(zInput);
137969   }
137970   nChar = nInput+1;
137971   pCsr = (IcuCursor *)sqlite3_malloc(
137972       sizeof(IcuCursor) +                /* IcuCursor */
137973       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
137974       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
137975   );
137976   if( !pCsr ){
137977     return SQLITE_NOMEM;
137978   }
137979   memset(pCsr, 0, sizeof(IcuCursor));
137980   pCsr->aChar = (UChar *)&pCsr[1];
137981   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
137982 
137983   pCsr->aOffset[iOut] = iInput;
137984   U8_NEXT(zInput, iInput, nInput, c);
137985   while( c>0 ){
137986     int isError = 0;
137987     c = u_foldCase(c, opt);
137988     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
137989     if( isError ){
137990       sqlite3_free(pCsr);
137991       return SQLITE_ERROR;
137992     }
137993     pCsr->aOffset[iOut] = iInput;
137994 
137995     if( iInput<nInput ){
137996       U8_NEXT(zInput, iInput, nInput, c);
137997     }else{
137998       c = 0;
137999     }
138000   }
138001 
138002   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
138003   if( !U_SUCCESS(status) ){
138004     sqlite3_free(pCsr);
138005     return SQLITE_ERROR;
138006   }
138007   pCsr->nChar = iOut;
138008 
138009   ubrk_first(pCsr->pIter);
138010   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
138011   return SQLITE_OK;
138012 }
138013 
138014 /*
138015 ** Close a tokenization cursor previously opened by a call to icuOpen().
138016 */
138017 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
138018   IcuCursor *pCsr = (IcuCursor *)pCursor;
138019   ubrk_close(pCsr->pIter);
138020   sqlite3_free(pCsr->zBuffer);
138021   sqlite3_free(pCsr);
138022   return SQLITE_OK;
138023 }
138024 
138025 /*
138026 ** Extract the next token from a tokenization cursor.
138027 */
138028 static int icuNext(
138029   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
138030   const char **ppToken,               /* OUT: *ppToken is the token text */
138031   int *pnBytes,                       /* OUT: Number of bytes in token */
138032   int *piStartOffset,                 /* OUT: Starting offset of token */
138033   int *piEndOffset,                   /* OUT: Ending offset of token */
138034   int *piPosition                     /* OUT: Position integer of token */
138035 ){
138036   IcuCursor *pCsr = (IcuCursor *)pCursor;
138037 
138038   int iStart = 0;
138039   int iEnd = 0;
138040   int nByte = 0;
138041 
138042   while( iStart==iEnd ){
138043     UChar32 c;
138044 
138045     iStart = ubrk_current(pCsr->pIter);
138046     iEnd = ubrk_next(pCsr->pIter);
138047     if( iEnd==UBRK_DONE ){
138048       return SQLITE_DONE;
138049     }
138050 
138051     while( iStart<iEnd ){
138052       int iWhite = iStart;
138053       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
138054       if( u_isspace(c) ){
138055         iStart = iWhite;
138056       }else{
138057         break;
138058       }
138059     }
138060     assert(iStart<=iEnd);
138061   }
138062 
138063   do {
138064     UErrorCode status = U_ZERO_ERROR;
138065     if( nByte ){
138066       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
138067       if( !zNew ){
138068         return SQLITE_NOMEM;
138069       }
138070       pCsr->zBuffer = zNew;
138071       pCsr->nBuffer = nByte;
138072     }
138073 
138074     u_strToUTF8(
138075         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
138076         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
138077         &status                                  /* Output success/failure */
138078     );
138079   } while( nByte>pCsr->nBuffer );
138080 
138081   *ppToken = pCsr->zBuffer;
138082   *pnBytes = nByte;
138083   *piStartOffset = pCsr->aOffset[iStart];
138084   *piEndOffset = pCsr->aOffset[iEnd];
138085   *piPosition = pCsr->iToken++;
138086 
138087   return SQLITE_OK;
138088 }
138089 
138090 /*
138091 ** The set of routines that implement the simple tokenizer
138092 */
138093 static const sqlite3_tokenizer_module icuTokenizerModule = {
138094   0,                           /* iVersion */
138095   icuCreate,                   /* xCreate  */
138096   icuDestroy,                  /* xCreate  */
138097   icuOpen,                     /* xOpen    */
138098   icuClose,                    /* xClose   */
138099   icuNext,                     /* xNext    */
138100 };
138101 
138102 /*
138103 ** Set *ppModule to point at the implementation of the ICU tokenizer.
138104 */
138105 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
138106   sqlite3_tokenizer_module const**ppModule
138107 ){
138108   *ppModule = &icuTokenizerModule;
138109 }
138110 
138111 #endif /* defined(SQLITE_ENABLE_ICU) */
138112 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138113 
138114 /************** End of fts3_icu.c ********************************************/